qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
287,587 |
<p>I have the following code, I'm trying to get a table with 4 columns across. If I run out of columns, create a new row and make 4 more coumns. rinse. lather. repeat.</p>
<pre><code><tbody>
<%
int i = 0;
foreach (ItmXtnMultimedia multimedia in ViewData.Model.ItmXtnMultimedia) {
if (i%4 == 0 && i== 0)
{
%><tr><%
}
if (i%4 == 0 && i != 0)
{
%></tr><tr><%
}
%>
<td><%= multimedia.ImgTag100 %></td>
<%
i++;
} %>
</code></pre>
<p></p>
<p>It works, but it sucks. Is there something built in to the framework or an extension method I can use? I guess I could roll my own, but figured there had to be something out there.</p>
|
[
{
"answer_id": 287667,
"author": "Ian P",
"author_id": 10853,
"author_profile": "https://Stackoverflow.com/users/10853",
"pm_score": 0,
"selected": false,
"text": "<p>You should replace the second if with else if.. Other than that, it's okay.</p>\n\n<pre><code>foreach (ItmXtnMultimedia multimedia in ViewData.Model.ItmXtnMultimedia) \n{\n if (i%4 == 0 && i== 0)\n {\n %><tr><%\n }\n else if (i%4 == 0 && i != 0)\n {\n %></tr><tr><%\n }\n %><td><%= multimedia.ImgTag100 %></td><%\n i++;\n}%>\n</code></pre>\n"
},
{
"answer_id": 287700,
"author": "Kyle West",
"author_id": 34133,
"author_profile": "https://Stackoverflow.com/users/34133",
"pm_score": 1,
"selected": false,
"text": "<p>Actually, I popped the fir out of the loop... (still smells though)</p>\n\n<pre><code> <tbody>\n <tr>\n <%\n int i = 0;\n foreach (ItmXtnMultimedia multimedia in ViewData.Model.ItmXtnMultimedia) {\n\n if (i%4 == 0)\n {\n %></tr><tr><%\n }\n %> \n <td><%= multimedia.ImgTag100 %></td> \n <%\n i++;\n } %> \n </tbody> \n</code></pre>\n"
},
{
"answer_id": 287726,
"author": "Eduardo Molteni",
"author_id": 2385,
"author_profile": "https://Stackoverflow.com/users/2385",
"pm_score": -1,
"selected": true,
"text": "<p>What about a little refactor?</p>\n\n<pre><code><%\nforeach (ItmXtnMultimedia multimedia in ViewData.Model.ItmXtnMultimedia) {\n manageColumnsForMe( 4 )\n %><td><%= multimedia.ImgTag100 %></td><%\n } \n%>\n</code></pre>\n\n<p>And the put the other code in a function using a static variable to store i</p>\n\n<p>You can reuse the same function with different number of columns</p>\n"
},
{
"answer_id": 287748,
"author": "HectorMac",
"author_id": 1400,
"author_profile": "https://Stackoverflow.com/users/1400",
"pm_score": 0,
"selected": false,
"text": "<p>I am assuming ViewData.Model.ItmXtnMultimedia is a list of some sort:</p>\n\n<pre><code><tbody>\n<%\n for (int i = 0; i < ViewData.Model.ItmXtnMultimedia.Count; i++ )\n {\n %><tr><%\n for (int j = 0; i < 4; j++)\n {\n if (i < ViewData.Model.ItmXtnMultimedia.Count)\n {\n %><td><%= ViewData.Model.ItmXtnMultimedia[i].ImgTag100 %> %></td><%\n }\n else\n {\n %><td></td><%\n }\n }\n %></tr><%\n } \n%>\n</tbody>\n</code></pre>\n\n<p>Still a mess of code, but maybe more readable?</p>\n"
},
{
"answer_id": 287790,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>This is a good place to create an extension method. Here's some almost-compilable C# pseudocode:</p>\n\n<pre><code>public static void IDunnoWhatToCallThis<T>(\n this HtmlHelper me, \n T[] items,\n int columns,\n Action headerTemplate,\n Action<T> itemTemplate,\n Action newRowTemplate,\n Action footerTemplate )\n{\n headerTemplate();\n\n for(int i = 0;i < items.Length; i++)\n {\n if(i != 0 && i%columns == 0)\n newRowTemplate();\n\n itemTemplate(items[i]);\n }\n\n footerTemplate();\n}\n</code></pre>\n\n<p>And here's an example in use:</p>\n\n<pre><code><% Html.IDunnoWhatToCallThis(\n ViewData.Model.ItmXtnMultimedia,\n 4,\n () => %><table><tr><%,\n (item) => %><td><%= item.ImgTag100 %></td><%,\n () => %></tr><tr><%,\n () => %></tr></table><%);%>\n</code></pre>\n\n<p>I LOVE helpers like this, mixing inline code, lambdas and markup. Its like watching magic.</p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/287587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34133/"
] |
I have the following code, I'm trying to get a table with 4 columns across. If I run out of columns, create a new row and make 4 more coumns. rinse. lather. repeat.
```
<tbody>
<%
int i = 0;
foreach (ItmXtnMultimedia multimedia in ViewData.Model.ItmXtnMultimedia) {
if (i%4 == 0 && i== 0)
{
%><tr><%
}
if (i%4 == 0 && i != 0)
{
%></tr><tr><%
}
%>
<td><%= multimedia.ImgTag100 %></td>
<%
i++;
} %>
```
It works, but it sucks. Is there something built in to the framework or an extension method I can use? I guess I could roll my own, but figured there had to be something out there.
|
What about a little refactor?
```
<%
foreach (ItmXtnMultimedia multimedia in ViewData.Model.ItmXtnMultimedia) {
manageColumnsForMe( 4 )
%><td><%= multimedia.ImgTag100 %></td><%
}
%>
```
And the put the other code in a function using a static variable to store i
You can reuse the same function with different number of columns
|
287,588 |
<p>Why does the select statement below return two different values ?</p>
<pre><code>declare @tempDec decimal
set @tempDec = 1.0 / (1.0 + 1.0)
select @tempDec, 1.0 / (1.0 + 1.0)
</code></pre>
|
[
{
"answer_id": 287605,
"author": "Chloraphil",
"author_id": 16162,
"author_profile": "https://Stackoverflow.com/users/16162",
"pm_score": 1,
"selected": false,
"text": "<p>I found out from a coworker just as I posted this.</p>\n\n<p>You need to specify the default precision and scale.</p>\n\n<p>This works in this scenario:\ndeclare @tempDec decimal(3,2)</p>\n\n<p>From MSDN:</p>\n\n<p>decimal[ (p[ , s] )] and numeric[ (p[ , s] )] \nFixed precision and scale numbers. When maximum precision is used, valid values are from - 10^38 +1 through 10^38 - 1. The SQL-92 synonyms for decimal are dec and dec(p, s). numeric is functionally equivalent to decimal.</p>\n\n<p>p (precision) \nThe maximum total number of decimal digits that can be stored, both to the left and to the right of the decimal point. The precision must be a value from 1 through the maximum precision of 38. The default precision is 18.</p>\n\n<p>s (scale) \nThe maximum number of decimal digits that can be stored to the right of the decimal point. Scale must be a value from 0 through p. Scale can be specified only if precision is specified. The default scale is 0; therefore, 0 <= s <= p. Maximum storage sizes vary, based on the precision.</p>\n"
},
{
"answer_id": 288285,
"author": "Gordon Bell",
"author_id": 16473,
"author_profile": "https://Stackoverflow.com/users/16473",
"pm_score": 3,
"selected": true,
"text": "<p>That's fine for literals like 1.0, but if you're pulling the data from table columns, you need to cast/convert the first evaluated number in your equation:</p>\n\n<pre><code>convert(decimal, [col1]) / ([col2] + [col3])\n</code></pre>\n\n<p>-or-</p>\n\n<pre><code>convert(decimal(15, 2), [col1]) / ([col2] + [col3])\n</code></pre>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/287588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16162/"
] |
Why does the select statement below return two different values ?
```
declare @tempDec decimal
set @tempDec = 1.0 / (1.0 + 1.0)
select @tempDec, 1.0 / (1.0 + 1.0)
```
|
That's fine for literals like 1.0, but if you're pulling the data from table columns, you need to cast/convert the first evaluated number in your equation:
```
convert(decimal, [col1]) / ([col2] + [col3])
```
-or-
```
convert(decimal(15, 2), [col1]) / ([col2] + [col3])
```
|
287,592 |
<p>Why does the following have the effect it does - it prints a terminal full of random characters and then exits leaving a command prompt that produces garbage when you type in it. (I tried it because I thought it would produce a seg fault).</p>
<p><img src="https://i.stack.imgur.com/kGkf4.png" alt="http://oi38.tinypic.com/r9qxbt.jpg"></p>
<pre><code>#include <stdio.h>
int main(){
char* s = "lololololololol";
while(1){
printf("%c", *s);
s++;
}
}
</code></pre>
<p>it was compiled with:</p>
<pre>gcc -std=c99 hello.c</pre>
|
[
{
"answer_id": 287602,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 3,
"selected": false,
"text": "<p>You are just printing out what is in memory because your loop doesn't stop at the end of the string. Each random byte is interpreted as a character. It will seg fault when you reach the end of the memory page (and get into unreadable territory).</p>\n"
},
{
"answer_id": 287607,
"author": "mipadi",
"author_id": 28804,
"author_profile": "https://Stackoverflow.com/users/28804",
"pm_score": 3,
"selected": false,
"text": "<p>Because you have an infinite loop (<code>while(1)</code>), and you keep getting the current value of pointer (<code>*s</code>), and then moving the pointer one char forward (<code>s++</code>). This has the effect of marching well past the end of the string into \"garbage\" (uninitialized memory), which gets printed to the console as a result.</p>\n"
},
{
"answer_id": 287613,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": false,
"text": "<p>It will eventually seg fault, but before that it'll print out whatever bytes are in the same page. That's why you see random chars on the screen.</p>\n\n<p>Those may well include escape sequences to change (say) the character encoding of the console. That's why you end up with gibberish when you type on the console after it's exited, too.</p>\n"
},
{
"answer_id": 287636,
"author": "Jim Buck",
"author_id": 2666,
"author_profile": "https://Stackoverflow.com/users/2666",
"pm_score": 3,
"selected": false,
"text": "<p>In addition to what everyone else said in regards to you ignoring the string terminal character and just printing willy-nilly what's in memory past the string, the reason why your command prompt is also \"garbage\" is that by printing a particular \"unprintable\" character, your terminal session was left in a strange character mode. (I don't know which character it is or what mode change it does, but maybe someone else can pipe in about it that knows better than I.)</p>\n"
},
{
"answer_id": 287820,
"author": "John Rudy",
"author_id": 14048,
"author_profile": "https://Stackoverflow.com/users/14048",
"pm_score": 2,
"selected": false,
"text": "<p>Expanding ever so slightly on the answers given here (which are all excellent) ... I ran into this more than once myself when I was just beginning with C, and it's an easy mistake to make.</p>\n\n<p>A quick tweak to your <code>while</code> loop will fix it. Everyone else has given you the why, I'll hook you up with the how:</p>\n\n<pre><code>#include <stdio.h>\n\nint main() {\n char *s = \"lolololololololol\";\n while (*s != '\\0') {\n printf(\"%c\", *s);\n s++;\n }\n}\n</code></pre>\n\n<p>Note that instead of an infinite loop (<code>while(1)</code>), we're doing a loop check to ensure that the pointer we're pulling isn't the null-terminator for the string, thus avoiding the overrun you're encountering.</p>\n\n<p>If you're stuck absolutely needing <code>while(1)</code> (for example, if this is homework and the instructor wants you to use it), use the <code>break</code> keyword to exit the loop. The following code smells, at least to me, but it works:</p>\n\n<pre><code>#include <stdio.h>\n\nint main() {\n char *s = \"lolololololololol\";\n while (1) {\n if (*s == '\\0')\n break;\n printf(\"%c\", *s);\n s++;\n }\n}\n</code></pre>\n\n<p>Both produce the same console output, with no line break at the end:</p>\n\n<blockquote>\n <p>lolololololololol</p>\n</blockquote>\n"
},
{
"answer_id": 300133,
"author": "tomjen",
"author_id": 21133,
"author_profile": "https://Stackoverflow.com/users/21133",
"pm_score": 1,
"selected": false,
"text": "<p>Your loop doesn't terminate, so println prints whatever is in the memory after the text you write; eventually it will access memory it is not allowed to read, causing it to segfault.</p>\n\n<p>You can change the loop as the others suggested, or you can take advantage of fact that in c, zero is false and null (which terminates all strings) is also zero, so you can construct the loop as:</p>\n\n<pre><code>while (*s) {\n</code></pre>\n\n<p>Rather than:</p>\n\n<pre><code>while (*s != '\\0')\n</code></pre>\n\n<p>The first one may be more difficult to understand, but it does have the advantage of brevity so it is often used to save a bit of typing.</p>\n"
},
{
"answer_id": 335477,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Also, you can usually get back to your command prompt by using the 'reset' command, typing blindly of course. (type Enter, reset, Enter)</p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/287592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Why does the following have the effect it does - it prints a terminal full of random characters and then exits leaving a command prompt that produces garbage when you type in it. (I tried it because I thought it would produce a seg fault).

```
#include <stdio.h>
int main(){
char* s = "lololololololol";
while(1){
printf("%c", *s);
s++;
}
}
```
it was compiled with:
```
gcc -std=c99 hello.c
```
|
It will eventually seg fault, but before that it'll print out whatever bytes are in the same page. That's why you see random chars on the screen.
Those may well include escape sequences to change (say) the character encoding of the console. That's why you end up with gibberish when you type on the console after it's exited, too.
|
287,594 |
<p>I have a rather simple scenario where I have two tables in which I want to add data. They are managed with primary key/foreign key. I want to add new data into TABLE A and then retrieve the Id and insert into TABLE B. </p>
<p>I can certainly do it with a stored procedure, but I'm looking at trying to do it using Linq. </p>
<p>What is the best approach ? </p>
<p>I can certainly get the ID and do two separate inserts but that doesn't certainly seem to be a very good way of doing things.</p>
<pre><code>db.Table.InsertOnSubmit(dbObject);
db.SubmitChanges();
Int32 id = dbOject.Id;
//Rest of the code
</code></pre>
<p>Any way to elegantly do this?</p>
|
[
{
"answer_id": 313042,
"author": "BigJoe714",
"author_id": 37786,
"author_profile": "https://Stackoverflow.com/users/37786",
"pm_score": 5,
"selected": true,
"text": "<p>Do you have the relationship defined between the 2 tables in the object relational designed? If so, you can have linq take care of assigning the ID property of the second table automatically.</p>\n\n<p>Example...<br/>\nTable A β Order<br/>\nOrderId<br/>\nOrderDate<br/><br/>\nTable B β Order Item<br/>\nOrderItemId<br/>\nOrderId<br/>\nItemId<br/><br/></p>\n\n<p>Code (Using LINQ-to-SQL):</p>\n\n<pre><code>Order order = new Order();\nOrder.OrderDate = DateTime.Now();\ndataContext.InsertOnSubmit(order);\n\nOrderItem item1 = new OrderItem();\nItem1.ItemId = 123;\n//Note: We set the Order property, which is an Order object\n// We do not set the OrderId property\n// LINQ will know to use the Id that is assigned from the order above\nItem1.Order = order; \ndataContext.InsertOnSubmit(item1);\n\ndataContext.SubmitChanges();\n</code></pre>\n"
},
{
"answer_id": 6775668,
"author": "Hitendra",
"author_id": 855875,
"author_profile": "https://Stackoverflow.com/users/855875",
"pm_score": 1,
"selected": false,
"text": "<p>hi i insert data into three table using this code </p>\n\n<pre><code> Product_Table AddProducttbl = new Product_Table();\n Product_Company Companytbl = new Product_Company();\n Product_Category Categorytbl = new Product_Category();\n\n // genrate product id's\n long Productid = (from p in Accountdc.Product_Tables \n select p.Product_ID ).FirstOrDefault();\n if (Productid == 0)\n Productid++;\n else\n Productid = (from lng in Accountdc.Product_Tables \n select lng.Product_ID ).Max() + 1;\n try\n {\n AddProducttbl.Product_ID = Productid;\n AddProducttbl.Product_Name = Request.Form[\"ProductName\"];\n AddProducttbl.Reorder_Label = Request.Form[\"ReorderLevel\"];\n AddProducttbl.Unit = Convert.ToDecimal(Request.Form[\"Unit\"]);\n AddProducttbl.Selling_Price = Convert.ToDecimal(Request.Form[\"Selling_Price\"]);\n AddProducttbl.MRP = Convert.ToDecimal(Request.Form[\"MRP\"]);\n // Accountdc.Product_Tables.InsertOnSubmit(AddProducttbl );\n // genrate category id's\n long Companyid = (from c in Accountdc.Product_Companies\n select c.Product_Company_ID).FirstOrDefault();\n if (Companyid == 0)\n Companyid++;\n else\n Companyid = (from Ct in Accountdc.Product_Companies\n select Ct.Product_Company_ID).Max() + 1;\n\n Companytbl.Product_Company_ID = Companyid;\n Companytbl.Product_Company_Name = Request.Form[\"Company\"];\n\n AddProducttbl.Product_Company = Companytbl;\n //Genrate Category id's\n long Categoryid = (from ct in Accountdc.Product_Categories\n select ct.Product_Category_ID).FirstOrDefault();\n if (Categoryid == 0)\n Categoryid++;\n else\n Categoryid = (from Ct in Accountdc.Product_Categories\n select Ct.Product_Category_ID).Max() + 1;\n Categorytbl.Product_Category_ID = Categoryid;\n Categorytbl.Product_Category_Name = Request.Form[\"Category\"];\n AddProducttbl.Product_Category = Categorytbl;\n\n Accountdc.Product_Tables.InsertOnSubmit(AddProducttbl);\n Accountdc.SubmitChanges();\n\n }\n catch \n {\n ViewData[\"submit Error\"] = \"No Product Submit\";\n }\n</code></pre>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/287594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31148/"
] |
I have a rather simple scenario where I have two tables in which I want to add data. They are managed with primary key/foreign key. I want to add new data into TABLE A and then retrieve the Id and insert into TABLE B.
I can certainly do it with a stored procedure, but I'm looking at trying to do it using Linq.
What is the best approach ?
I can certainly get the ID and do two separate inserts but that doesn't certainly seem to be a very good way of doing things.
```
db.Table.InsertOnSubmit(dbObject);
db.SubmitChanges();
Int32 id = dbOject.Id;
//Rest of the code
```
Any way to elegantly do this?
|
Do you have the relationship defined between the 2 tables in the object relational designed? If so, you can have linq take care of assigning the ID property of the second table automatically.
Example...
Table A β Order
OrderId
OrderDate
Table B β Order Item
OrderItemId
OrderId
ItemId
Code (Using LINQ-to-SQL):
```
Order order = new Order();
Order.OrderDate = DateTime.Now();
dataContext.InsertOnSubmit(order);
OrderItem item1 = new OrderItem();
Item1.ItemId = 123;
//Note: We set the Order property, which is an Order object
// We do not set the OrderId property
// LINQ will know to use the Id that is assigned from the order above
Item1.Order = order;
dataContext.InsertOnSubmit(item1);
dataContext.SubmitChanges();
```
|
287,595 |
<p>This seems like a very simple and a very common problem. The simplest example I can think of is this:</p>
<p>The form has five checkboxes with a "check all/check none" checkbox above them. When a user selects checking all checkboxes, I toggle the states of the "children" - obviously I don't want to fire the check events of all the children until I am done setting all of the checkboxes.</p>
<p>I can't find a form-wide suspend control event. If I'm simply missing it then great simple answer. Barring a simple solution that I am just missing, what is the best way (best practice? accepted solution?) to suspend form control events?</p>
|
[
{
"answer_id": 287659,
"author": "Ryan Lundy",
"author_id": 5486,
"author_profile": "https://Stackoverflow.com/users/5486",
"pm_score": 2,
"selected": false,
"text": "<p>From your other question, I'm going to guess you're using VB .NET. So, RemoveHandler is your best bet. Normally in VB people set up event handlers using the Handles clause. But you can also do it this way:</p>\n\n<pre><code>AddHandler chk1.CheckedChanged, AddressOf DoSomething\n</code></pre>\n\n<p>where DoSomething might look like this:</p>\n\n<pre><code>Private Sub DoSomething(ByVal sender As Object, ByVal e As EventArgs)\n ' whatever\nEnd Sub\n</code></pre>\n\n<p>AddHandler wires up the event, so it'll fire. To get it not to fire, use RemoveHandler:</p>\n\n<pre><code>RemoveHandler chk1.CheckedChanged, AddressOf DoSomething\n</code></pre>\n\n<p>Before updating the Checked property of your child checkboxes, call RemoveHandler on each of them; then when you're done, call AddHandler to put the event handlers back. If all your checkboxes use the same handler, you can put them in a collection and loop through the collection to add or remove the handlers.</p>\n"
},
{
"answer_id": 287671,
"author": "Rob Stevenson-Leggett",
"author_id": 4950,
"author_profile": "https://Stackoverflow.com/users/4950",
"pm_score": 4,
"selected": true,
"text": "<p>I've come across this before and usually seen people do this:</p>\n\n<pre><code>/*SNIP*/\n\nprivate bool isMassUpdate;\n\npublic void Check1_Check(object sender, EventArgs e)\n{\n if(!isMassUpdate)\n {\n do some stuff\n }\n}\n\n/*SNIP*/\n</code></pre>\n\n<p>You can also detach and reattach the event handlers, however, I'm told this can be a source of memory leaks.</p>\n\n<p>Information on memory leaks and event handlers: They're not directly linked to attaching and detaching, but we've seen in one of our applications that bad referencing of event handlers down inheritance trees can cause it.</p>\n\n<ul>\n<li><p><em><a href=\"http://blogs.msdn.com/tess/archive/2006/01/23/net-memory-leak-case-study-the-event-handlers-that-made-the-memory-baloon.aspx\" rel=\"nofollow noreferrer\">.NET Memory Leak Case Study: The Event Handlers That Made The Memory Baloon</a></em></p></li>\n<li><p><em><a href=\"http://forum.umbraco.org/yaf_postst6558_Net-Experts-Question-on-Event-Handlers-and-Memory-Leaks.aspx\" rel=\"nofollow noreferrer\">On event handlers and memory leaks</a></em></p></li>\n</ul>\n"
},
{
"answer_id": 287683,
"author": "Will Dean",
"author_id": 987,
"author_profile": "https://Stackoverflow.com/users/987",
"pm_score": 1,
"selected": false,
"text": "<p>You could also consider handling 'click' events for the buttons, rather than check-changed. That might be nearer to your intent.</p>\n"
},
{
"answer_id": 288284,
"author": "DJ.",
"author_id": 10492,
"author_profile": "https://Stackoverflow.com/users/10492",
"pm_score": 1,
"selected": false,
"text": "<p>In my <a href=\"http://en.wikipedia.org/wiki/Visual_Basic#Timeline\" rel=\"nofollow noreferrer\">Visual Basic 6.0</a> application I had to handle users double-clicking <em>everything</em>, so on all my event handlers I have one line that checks a global variable</p>\n\n<pre><code>Private bSuspendEvents as Boolean\n\nPrivate Sub Button1_Click()\n\n On Error Goto ErrorHandler\n\n If bSuspendEvents then Exit Sub\n\n bSuspendEvents = True\n\n 'Do stuff\n\n NormalExit:\n bSuspendEvents = False\n Exit Sub\n\n ErrorHandler:\n 'Handle Error\n Resume NormalExit\n\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 288737,
"author": "Garo Yeriazarian",
"author_id": 2655,
"author_profile": "https://Stackoverflow.com/users/2655",
"pm_score": 3,
"selected": false,
"text": "<p>What I do in these cases instead of having a boolean value that suspends events, I use a counter. When the count is > 0, then suspend events, when the count = 0, then resume events. This helps with the problem if I have multiple things that could request a suspension of events.</p>\n\n<p>The other useful thing is if I need to suspend events in a block, I create a little helper class that is IDisposable that I can use in a \"using\" block (in C#) so I don't forget to decrement the counter once I'm out of scope.</p>\n"
},
{
"answer_id": 26172939,
"author": "Jim Fred",
"author_id": 101252,
"author_profile": "https://Stackoverflow.com/users/101252",
"pm_score": 1,
"selected": false,
"text": "<p>See Stack Overflow question <em><a href=\"https://stackoverflow.com/a/6604753/101252\">How do I ignore simple events firing when changing control states in C# Windows Forms?</a></em></p>\n\n<blockquote>\n <p>For the more general case, if you have complex relations between the controls, you could check which control fired the event by checking its own Focused property... each object is only dependent on itself.</p>\n</blockquote>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/287595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35555/"
] |
This seems like a very simple and a very common problem. The simplest example I can think of is this:
The form has five checkboxes with a "check all/check none" checkbox above them. When a user selects checking all checkboxes, I toggle the states of the "children" - obviously I don't want to fire the check events of all the children until I am done setting all of the checkboxes.
I can't find a form-wide suspend control event. If I'm simply missing it then great simple answer. Barring a simple solution that I am just missing, what is the best way (best practice? accepted solution?) to suspend form control events?
|
I've come across this before and usually seen people do this:
```
/*SNIP*/
private bool isMassUpdate;
public void Check1_Check(object sender, EventArgs e)
{
if(!isMassUpdate)
{
do some stuff
}
}
/*SNIP*/
```
You can also detach and reattach the event handlers, however, I'm told this can be a source of memory leaks.
Information on memory leaks and event handlers: They're not directly linked to attaching and detaching, but we've seen in one of our applications that bad referencing of event handlers down inheritance trees can cause it.
* *[.NET Memory Leak Case Study: The Event Handlers That Made The Memory Baloon](http://blogs.msdn.com/tess/archive/2006/01/23/net-memory-leak-case-study-the-event-handlers-that-made-the-memory-baloon.aspx)*
* *[On event handlers and memory leaks](http://forum.umbraco.org/yaf_postst6558_Net-Experts-Question-on-Event-Handlers-and-Memory-Leaks.aspx)*
|
287,596 |
<p>Is it safe to use MS SQL's WITH (NOLOCK) option for select statements and insert statements if you never modify a row, but only insert or delete rows?</p>
<p>I..e you never do an UPDATE to any of the rows.</p>
|
[
{
"answer_id": 287635,
"author": "Tom H",
"author_id": 5696608,
"author_profile": "https://Stackoverflow.com/users/5696608",
"pm_score": 4,
"selected": true,
"text": "<p>If you're asking whether or not you'll get data that may no longer be accurate, then it depends on your queries. For example, if you do something like:</p>\n\n<pre><code>SELECT\n my_id,\n my_date\nFROM\n My_Table\nWHERE\n my_date >= '2008-01-01'\n</code></pre>\n\n<p>at the same time that a row is being inserted with a date on or after 2008-01-01 then you may not get that new row. This can also affect queries which generate aggregates.</p>\n\n<p>If you are just mimicking updates through a delete/insert then you also may get an \"old\" version of the data.</p>\n"
},
{
"answer_id": 287647,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 0,
"selected": false,
"text": "<p>If you are never doing any UPDATEs, then why does locking give you a problem in the first place?</p>\n\n<p>If there are referential integrity or trigger-firing issues at play, then NOLOCK is just going to turn those errors into mysterious inconsistencies.</p>\n"
},
{
"answer_id": 287657,
"author": "dkretz",
"author_id": 31641,
"author_profile": "https://Stackoverflow.com/users/31641",
"pm_score": -1,
"selected": false,
"text": "<p>Not sure how SELECT statements could conflict if you're limiting yourself to INSERTs and DELETEs. INSERT is problematic because there may have been conflicting primary keys inserted during your query, for instance. Both INSERTs and DELETEs both expose you to the conditions expressed in your WHERE clause, or JOINs, etc. may become invalid during your statement's execution.</p>\n"
},
{
"answer_id": 288141,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 1,
"selected": false,
"text": "<p>Not in general. (i.e. UPDATE is not the only locking issue)</p>\n\n<p>If you are inserting (or deleting) records and a select could potentially specify records which would be in that set, then yes, NOLOCK will give you a dirty read which may or may not include those records.</p>\n\n<p>If the inserts or deletes would never potentially be selected (for instance the data read is always yesterday's data, wheras today's data coming in or being manipulated is never read), then yes, it is \"safe\".</p>\n"
},
{
"answer_id": 3826521,
"author": "MrEs",
"author_id": 211718,
"author_profile": "https://Stackoverflow.com/users/211718",
"pm_score": 0,
"selected": false,
"text": "<p>Well 'safe' is a very generic term; it all depends on the context of your application and its use. But there is always a chance of skipping and double-counting previously committed rows when NOLOCK hint is used.</p>\n\n<p>Anyways, have a read of this:\n<a href=\"http://blogs.msdn.com/b/sqlcat/archive/2007/02/01/previously-committed-rows-might-be-missed-if-nolock-hint-is-used.aspx\" rel=\"nofollow\">http://blogs.msdn.com/b/sqlcat/archive/2007/02/01/previously-committed-rows-might-be-missed-if-nolock-hint-is-used.aspx</a></p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/287596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3153/"
] |
Is it safe to use MS SQL's WITH (NOLOCK) option for select statements and insert statements if you never modify a row, but only insert or delete rows?
I..e you never do an UPDATE to any of the rows.
|
If you're asking whether or not you'll get data that may no longer be accurate, then it depends on your queries. For example, if you do something like:
```
SELECT
my_id,
my_date
FROM
My_Table
WHERE
my_date >= '2008-01-01'
```
at the same time that a row is being inserted with a date on or after 2008-01-01 then you may not get that new row. This can also affect queries which generate aggregates.
If you are just mimicking updates through a delete/insert then you also may get an "old" version of the data.
|
287,630 |
<p>I have a right outer join, that almost does what I want...</p>
<pre><code>SELECT
users_usr.firstname_usr,
users_usr.lastname_usr,
credit_acc.given_credit_acc,
users_usr.created_usr,
users_usr.sitenum_usr,
users_usr.original_aff_usr,
users_usr.id_usr
FROM
credit_acc
right Outer Join users_usr ON credit_acc.uid_usr = users_usr.id_usr
</code></pre>
<p>The problem is, I want to add a </p>
<pre><code>where credit_acc.type_acc = 'init'
</code></pre>
<p>But this gets rid of all users who don't have a row in credit_acc... which is WHY I need a right outer join.</p>
<p>Is there a way to get this without having to do two queries and a union?</p>
|
[
{
"answer_id": 287638,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 3,
"selected": true,
"text": "<pre><code>SELECT\nusers_usr.firstname_usr,\nusers_usr.lastname_usr,\ncredit_acc.given_credit_acc,\nusers_usr.created_usr,\nusers_usr.sitenum_usr,\nusers_usr.original_aff_usr,\nusers_usr.id_usr\nFROM\ncredit_acc\nright Outer Join users_usr ON credit_acc.uid_usr = users_usr.id_usr\nWHERE credit_acc.type_acc = 'init' OR credit_acc.type_acc is NULL\n</code></pre>\n\n<p>Or, as @Tomalak pointed out:</p>\n\n<pre><code>WHERE COALESCE(credit_acc.type_acc, 'init') = 'init'\n</code></pre>\n\n<p>which <em>may</em> be faster (see comments).</p>\n"
},
{
"answer_id": 287648,
"author": "Ben Noland",
"author_id": 32899,
"author_profile": "https://Stackoverflow.com/users/32899",
"pm_score": 1,
"selected": false,
"text": "<p>Have you tried the following?</p>\n\n<pre><code>SELECT\nusers_usr.firstname_usr,\nusers_usr.lastname_usr,\ncredit_acc.given_credit_acc,\nusers_usr.created_usr,\nusers_usr.sitenum_usr,\nusers_usr.original_aff_usr,\nusers_usr.id_usr\nFROM\ncredit_acc\nright Outer Join users_usr ON credit_acc.uid_usr = users_usr.id_usr and credit_acc.type_acc = 'init'\n</code></pre>\n"
},
{
"answer_id": 287651,
"author": "gpojd",
"author_id": 28071,
"author_profile": "https://Stackoverflow.com/users/28071",
"pm_score": 2,
"selected": false,
"text": "<p>If the row doesn't exist, <em>credit_acc.type_acc</em> should be null. You could try something like this: </p>\n\n<pre><code>WHERE credit_acc.type_acc = 'init' OR credit_acc.type_acc IS NULL;\n</code></pre>\n\n<p>That will only work if there are no null fields in <em>credit_acc.type_acc</em>. </p>\n"
},
{
"answer_id": 287664,
"author": "Skeolan",
"author_id": 9640,
"author_profile": "https://Stackoverflow.com/users/9640",
"pm_score": 0,
"selected": false,
"text": "<p>You want all records from the two tables, joined on user-id, WHERE credit_acc is 'init' OR where there isn't a credit_acc row to be joined? How about</p>\n\n<pre><code>where credit_acc.type_acc is null OR credit_acc.type_acc = 'init'\n</code></pre>\n"
},
{
"answer_id": 287861,
"author": "Dave Costa",
"author_id": 6568,
"author_profile": "https://Stackoverflow.com/users/6568",
"pm_score": 0,
"selected": false,
"text": "<p>I would make the predicate:</p>\n\n<pre><code>WHERE credit_acc.uid_usr IS NULL OR credit_acc.type_acc = 'init'\n</code></pre>\n\n<p>This would give you rows where there is no match on UID_USR, and rows where there is a match and the account type is 'init'.</p>\n\n<p>The other solution proposed (checking type_acc for NULL) would also give you rows where there is a match on UID_USR and the actual value for account type is NULL.</p>\n\n<p>If credit_acc.type_acc can't be NULL, there's no difference between the two. If it can, you need to decide whether you want to include those rows in your result set.</p>\n"
},
{
"answer_id": 287922,
"author": "Charles Bretana",
"author_id": 32632,
"author_profile": "https://Stackoverflow.com/users/32632",
"pm_score": 0,
"selected": false,
"text": "<p>Just add another predicate to the Join Condition.</p>\n\n<pre><code>SELECT U.firstname_usr, U.lastname_usr, C.given_credit_acc, \n U.created_usr, U.sitenum_usr, U.original_aff_usr, U.id_usr\nFrom credit_acc C Right Join users_usr U\n On C.uid_usr = U.id_usr\n And C.type_acc = 'init'\n</code></pre>\n\n<p>This works because Join conditions are applied BEFORE the non-matching records from \"other\" side of an \"Outer\" join are added to the result set, whereas Where Conditions are applied after the two tables are joined... </p>\n\n<p>This syntax more clearly represents your intent as well... </p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/287630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13704/"
] |
I have a right outer join, that almost does what I want...
```
SELECT
users_usr.firstname_usr,
users_usr.lastname_usr,
credit_acc.given_credit_acc,
users_usr.created_usr,
users_usr.sitenum_usr,
users_usr.original_aff_usr,
users_usr.id_usr
FROM
credit_acc
right Outer Join users_usr ON credit_acc.uid_usr = users_usr.id_usr
```
The problem is, I want to add a
```
where credit_acc.type_acc = 'init'
```
But this gets rid of all users who don't have a row in credit\_acc... which is WHY I need a right outer join.
Is there a way to get this without having to do two queries and a union?
|
```
SELECT
users_usr.firstname_usr,
users_usr.lastname_usr,
credit_acc.given_credit_acc,
users_usr.created_usr,
users_usr.sitenum_usr,
users_usr.original_aff_usr,
users_usr.id_usr
FROM
credit_acc
right Outer Join users_usr ON credit_acc.uid_usr = users_usr.id_usr
WHERE credit_acc.type_acc = 'init' OR credit_acc.type_acc is NULL
```
Or, as @Tomalak pointed out:
```
WHERE COALESCE(credit_acc.type_acc, 'init') = 'init'
```
which *may* be faster (see comments).
|
287,632 |
<p>Very odd problem as this is working perfectly on our old Classic ASP site. We are basically querying the database and exporting around 2200 lines of text to a Text File through Response.Write to be output to a dialog box and allows the user to save the file.</p>
<p>Response.Clear()
Response.ClearContent()
Response.ClearHeaders()</p>
<pre><code> Dim fileName As String = "TECH" & test & ".txt"
Response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}", fileName))
Response.ContentType = "text/plain"
Response.Write(strHeader)
Dim sw As New IO.StringWriter()
Dim dtRow As DataRow
For Each dtRow In dt3.Rows
sw.Write(dtRow.Item("RECORD") & vbCrLf)
Next
Response.Write(sw.ToString)
Response.Write(strTrailer & intRecCount)
Response.End()
</code></pre>
<p>I can either use StringWriter or simply use Response.Write(dt.Rows(i).Item("RECORD").toString</p>
<p>Either way, the Export is causing a horrendous hang on our development site. My local machine causes no hang and is almost instantaneous. The recordset isn't very large, and the lines it is writing are small. </p>
<p>Anyone have any idea why this would be hanging? It does EVENTUALLY allow for a save and display the file, but it's well over 3-4 minutes.</p>
|
[
{
"answer_id": 287637,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 3,
"selected": true,
"text": "<p>Attach a remote debugger and find where its hanging?</p>\n\n<p>You need to figure out if its the string writer loop, or the actual query code (which is not provided here).</p>\n"
},
{
"answer_id": 287643,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "<p>Sounds like maybe you're overflowing the output buffer. Perhaps add a counter in there to flush every few hundred lines.</p>\n\n<p>Also, the Response object basically does most of the work for a StringWriter for you. Using the StringWriter as an intermediary is probably redundant.</p>\n"
},
{
"answer_id": 287725,
"author": "Sunny Milenov",
"author_id": 8220,
"author_profile": "https://Stackoverflow.com/users/8220",
"pm_score": 0,
"selected": false,
"text": "<p>Both using StringWriter and DataTable are overkill.</p>\n\n<p>Why not use directly SqlReader to get the results from the database, and while reading the reader, write directly to the output stream? Much faster, and much less memory consumed.</p>\n\n<p>As an answer to your second question - why the ASP was working OK, I doubt that there you have stored the same content 3 times in memory in order to output it (in the DataTable, in the StringWriter and in the output buffer). My ASP is a little bit rusty, but I would guess that there you are using database reader of some sort.</p>\n\n<p>Also, better employ some logging infrastructure (NLog, log4net), so you can output some timing about which operation delays how much, as an alternative to attaching a remote debugger.</p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/287632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Very odd problem as this is working perfectly on our old Classic ASP site. We are basically querying the database and exporting around 2200 lines of text to a Text File through Response.Write to be output to a dialog box and allows the user to save the file.
Response.Clear()
Response.ClearContent()
Response.ClearHeaders()
```
Dim fileName As String = "TECH" & test & ".txt"
Response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}", fileName))
Response.ContentType = "text/plain"
Response.Write(strHeader)
Dim sw As New IO.StringWriter()
Dim dtRow As DataRow
For Each dtRow In dt3.Rows
sw.Write(dtRow.Item("RECORD") & vbCrLf)
Next
Response.Write(sw.ToString)
Response.Write(strTrailer & intRecCount)
Response.End()
```
I can either use StringWriter or simply use Response.Write(dt.Rows(i).Item("RECORD").toString
Either way, the Export is causing a horrendous hang on our development site. My local machine causes no hang and is almost instantaneous. The recordset isn't very large, and the lines it is writing are small.
Anyone have any idea why this would be hanging? It does EVENTUALLY allow for a save and display the file, but it's well over 3-4 minutes.
|
Attach a remote debugger and find where its hanging?
You need to figure out if its the string writer loop, or the actual query code (which is not provided here).
|
287,645 |
<p>I want to discover at run-time ONLY the static Methods of a class, how can I do this?
Or, how to differentiate between static and non-static methods.</p>
|
[
{
"answer_id": 287654,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 9,
"selected": true,
"text": "<p>Use <code>Modifier.isStatic(method.getModifiers())</code>.</p>\n\n<pre><code>/**\n * Returns the public static methods of a class or interface,\n * including those declared in super classes and interfaces.\n */\npublic static List<Method> getStaticMethods(Class<?> clazz) {\n List<Method> methods = new ArrayList<Method>();\n for (Method method : clazz.getMethods()) {\n if (Modifier.isStatic(method.getModifiers())) {\n methods.add(method);\n }\n }\n return Collections.unmodifiableList(methods);\n}\n</code></pre>\n\n<p>Note: This method is actually dangerous from a security standpoint. Class.getMethods \"bypass[es] SecurityManager checks depending on the immediate caller's class loader\" (see section 6 of the Java secure coding guidelines).</p>\n\n<p>Disclaimer: Not tested or even compiled.</p>\n\n<p>Note <code>Modifier</code> should be used with care. Flags represented as ints are not type safe. A common mistake is to test a modifier flag on a type of reflection object that it does not apply to. It may be the case that a flag in the same position is set to denote some other information.</p>\n"
},
{
"answer_id": 287674,
"author": "Daniel Spiewak",
"author_id": 9815,
"author_profile": "https://Stackoverflow.com/users/9815",
"pm_score": 3,
"selected": false,
"text": "<p>To flesh out the previous (correct) answer, here is a full code snippet which does what you want (exceptions ignored):</p>\n\n<pre><code>public Method[] getStatics(Class<?> c) {\n Method[] all = c.getDeclaredMethods()\n List<Method> back = new ArrayList<Method>();\n\n for (Method m : all) {\n if (Modifier.isStatic(m.getModifiers())) {\n back.add(m);\n }\n }\n\n return back.toArray(new Method[back.size()]);\n}\n</code></pre>\n"
},
{
"answer_id": 287681,
"author": "bruno conde",
"author_id": 31136,
"author_profile": "https://Stackoverflow.com/users/31136",
"pm_score": 4,
"selected": false,
"text": "<p>You can get the static methods like this:</p>\n\n<pre><code>for (Method m : MyClass.class.getMethods()) {\n if (Modifier.isStatic(m.getModifiers()))\n System.out.println(\"Static Method: \" + m.getName());\n}\n</code></pre>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/287645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/518/"
] |
I want to discover at run-time ONLY the static Methods of a class, how can I do this?
Or, how to differentiate between static and non-static methods.
|
Use `Modifier.isStatic(method.getModifiers())`.
```
/**
* Returns the public static methods of a class or interface,
* including those declared in super classes and interfaces.
*/
public static List<Method> getStaticMethods(Class<?> clazz) {
List<Method> methods = new ArrayList<Method>();
for (Method method : clazz.getMethods()) {
if (Modifier.isStatic(method.getModifiers())) {
methods.add(method);
}
}
return Collections.unmodifiableList(methods);
}
```
Note: This method is actually dangerous from a security standpoint. Class.getMethods "bypass[es] SecurityManager checks depending on the immediate caller's class loader" (see section 6 of the Java secure coding guidelines).
Disclaimer: Not tested or even compiled.
Note `Modifier` should be used with care. Flags represented as ints are not type safe. A common mistake is to test a modifier flag on a type of reflection object that it does not apply to. It may be the case that a flag in the same position is set to denote some other information.
|
287,655 |
<p>In OpenGL I'm trying to rotate a camera around a point, with camera being distance r from the point and facing the point when it rotates. In other words, I want the camera to move along the circumference of a circle at a radius r from the center, with the camera facing the center at any point along the circumference.</p>
<p>Lets say that in 3d space the center of the circle is (3, 0, 3);</p>
<p>I've tried:</p>
<pre><code>// move to center of circle
glTranslatef(-3, 0, -3)
// move a distance away from the circle
glTranslatef(0, 0, r);
// rotate along the y "up" axis
glRotatef(CameraAngle, 0, 1, 0);
</code></pre>
<p>where CameraAngle is the degrees being moved around the circle.</p>
<p>My end result is the camera is still rotating along the origin, not the center of the circle. Can anyone help me fix this problem? Thanks!</p>
|
[
{
"answer_id": 287675,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 6,
"selected": true,
"text": "<p>You need to either:</p>\n\n<ul>\n<li>rotate the camera around the origin and then translate it (*)</li>\n</ul>\n\n<p>or:</p>\n\n<ul>\n<li>use <code>gluLookAt</code> to keep the camera pointing at the center of the circle</li>\n</ul>\n\n<p>(*) rotation functions normally rotate about the origin. To rotate around another point <code>P</code> you have to:</p>\n\n<ul>\n<li>translate(-P)</li>\n<li>rotate</li>\n<li>translate(P)</li>\n</ul>\n"
},
{
"answer_id": 287689,
"author": "Drew Hall",
"author_id": 23934,
"author_profile": "https://Stackoverflow.com/users/23934",
"pm_score": 1,
"selected": false,
"text": "<p>I find problems like this much easier to solve with gluLookAt(). You define a path for the camera (a circle is easy!) and keep the \"center\" point fixed (i.e. the thing you're looking at).</p>\n\n<p>The only possible trick is defining a good up vector--but not usually too much work. If the path and the target point are in the same plane, you can use the same up vector each time!</p>\n"
},
{
"answer_id": 287848,
"author": "shoosh",
"author_id": 9611,
"author_profile": "https://Stackoverflow.com/users/9611",
"pm_score": 2,
"selected": false,
"text": "<p>Why bother with all the trouble of rotating the camera and not rotate the scene itself?<br>\nIt's much more straight forward. just rotate the modelview matrix around the origin. You'll get the exact same result.</p>\n"
},
{
"answer_id": 712850,
"author": "neoedmund",
"author_id": 86600,
"author_profile": "https://Stackoverflow.com/users/86600",
"pm_score": 4,
"selected": false,
"text": "<p>it is a little confusing, but i think you should:</p>\n\n<pre><code>// move camera a distance r away from the center\nglTranslatef(0, 0, -r);\n\n// rotate \nglRotatef(angley, 0, 1, 0);\nglRotatef(anglex, 1, 0, 0);\n\n// move to center of circle \nglTranslatef(-cx, -cy, -cz)\n</code></pre>\n\n<p>note the order must NOT be changed.</p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/287655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/396/"
] |
In OpenGL I'm trying to rotate a camera around a point, with camera being distance r from the point and facing the point when it rotates. In other words, I want the camera to move along the circumference of a circle at a radius r from the center, with the camera facing the center at any point along the circumference.
Lets say that in 3d space the center of the circle is (3, 0, 3);
I've tried:
```
// move to center of circle
glTranslatef(-3, 0, -3)
// move a distance away from the circle
glTranslatef(0, 0, r);
// rotate along the y "up" axis
glRotatef(CameraAngle, 0, 1, 0);
```
where CameraAngle is the degrees being moved around the circle.
My end result is the camera is still rotating along the origin, not the center of the circle. Can anyone help me fix this problem? Thanks!
|
You need to either:
* rotate the camera around the origin and then translate it (\*)
or:
* use `gluLookAt` to keep the camera pointing at the center of the circle
(\*) rotation functions normally rotate about the origin. To rotate around another point `P` you have to:
* translate(-P)
* rotate
* translate(P)
|
287,663 |
<p>I have 2 handlers using the same form. How do I remove the handlers before adding the new one (C#)?</p>
|
[
{
"answer_id": 287678,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": false,
"text": "<p>If you know what those handlers are, just remove them in the same way that you subscribed to them, except with -= instead of +=.</p>\n\n<p>If you don't know what the handlers are, you can't remove them - the idea being that the event encapsulation prevents one interested party from clobbering the interests of another class in observing an event.</p>\n\n<p>EDIT: I've been assuming that you're talking about an event implemented by a different class, e.g. a control. If your class \"owns\" the event, then just set the relevant variable to null.</p>\n"
},
{
"answer_id": 287694,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 4,
"selected": true,
"text": "<p>If you are working in the form itself, you should be able to do something like:</p>\n\n<p>PseudoCode:</p>\n\n<pre><code>Delegate[] events = Form1.SomeEvent.GetInvokationList();\n\nforeach (Delegate d in events)\n{\n Form1.SomeEvent -= d;\n}\n</code></pre>\n\n<p>From outside of the form, your SOL.</p>\n"
},
{
"answer_id": 3426847,
"author": "Greg B",
"author_id": 413393,
"author_profile": "https://Stackoverflow.com/users/413393",
"pm_score": 2,
"selected": false,
"text": "<p>I realize this question is rather old, but hopefully it will help someone out. You can unregister all the event handlers for any class with a little reflection.</p>\n\n<pre><code>public static void UnregisterAllEvents(object objectWithEvents)\n{\n Type theType = objectWithEvents.GetType();\n\n //Even though the events are public, the FieldInfo associated with them is private\n foreach (System.Reflection.FieldInfo field in theType.GetFields(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance))\n {\n //eventInfo will be null if this is a normal field and not an event.\n System.Reflection.EventInfo eventInfo = theType.GetEvent(field.Name);\n if (eventInfo != null)\n {\n MulticastDelegate multicastDelegate = field.GetValue(objectWithEvents) as MulticastDelegate;\n if (multicastDelegate != null)\n {\n foreach (Delegate _delegate in multicastDelegate.GetInvocationList())\n {\n eventInfo.RemoveEventHandler(objectWithEvents, _delegate);\n }\n }\n }\n }\n}\n</code></pre>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/287663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6013/"
] |
I have 2 handlers using the same form. How do I remove the handlers before adding the new one (C#)?
|
If you are working in the form itself, you should be able to do something like:
PseudoCode:
```
Delegate[] events = Form1.SomeEvent.GetInvokationList();
foreach (Delegate d in events)
{
Form1.SomeEvent -= d;
}
```
From outside of the form, your SOL.
|
287,679 |
<p>How do I create tabbed navigation with the "Current" tab highlighted in the UI?</p>
|
[
{
"answer_id": 287688,
"author": "Kyle West",
"author_id": 34133,
"author_profile": "https://Stackoverflow.com/users/34133",
"pm_score": 4,
"selected": true,
"text": "<p>Before MVC I looked at the file path and figured out which tab was currrent. Now it's a lot easier, you can assign the current tab based on the current controller.</p>\n\n<p>Check it out ...</p>\n\n<p>Most of the work happens in the usercontrol. </p>\n\n<pre><code>public partial class AdminNavigation : ViewUserControl\n{\n /// <summary>\n /// This hold a collection of controllers and their respective \"tabs.\" Each Tab should have at least one controller in the collection.\n /// </summary>\n private readonly IDictionary<Type, string> dict = new Dictionary<Type, string>();\n\n public AdminNavigation()\n {\n dict.Add(typeof(BrandController), \"catalog\");\n dict.Add(typeof(CatalogController), \"catalog\");\n dict.Add(typeof(GroupController), \"catalog\");\n dict.Add(typeof(ItemController), \"catalog\");\n dict.Add(typeof(ConfigurationController), \"configuration\");\n dict.Add(typeof(CustomerController), \"customer\");\n dict.Add(typeof(DashboardController), \"dashboard\");\n dict.Add(typeof(OrderController), \"order\");\n dict.Add(typeof(WebsiteController), \"website\");\n }\n\n protected string SetClass(string linkToCheck)\n {\n Type controller = ViewContext.Controller.GetType();\n // We need to determine if the linkToCheck is equal to the current controller using dict as a Map\n string dictValue;\n dict.TryGetValue(controller, out dictValue);\n\n if (dictValue == linkToCheck)\n {\n return \"current\";\n }\n return \"\";\n }\n}\n</code></pre>\n\n<p>Then in your .ascx part of the usercontol call into the SetClass method to check the link against the dict. Like so:</p>\n\n<pre><code><li class=\"<%= SetClass(\"customer\") %>\"><%= Html.ActionLink<CustomerController>(c=>c.Index(),\"Customers\",new{@class=\"nav_customers\"}) %></li>\n</code></pre>\n\n<p>All you need now is the CSS to highlight your current tab. There are a bunch of different ways to do this, but you can get started with some ideas here: <a href=\"http://webdeveloper.econsultant.com/css-menus-navigation-tabs/\" rel=\"noreferrer\">http://webdeveloper.econsultant.com/css-menus-navigation-tabs/</a>\nOh, and don't forget to put the usercontrol on your page (or MasterPage) ...</p>\n\n<pre><code><% Html.RenderPartial(\"AdminNavigation\"); %>\n</code></pre>\n"
},
{
"answer_id": 1254900,
"author": "Raleigh Buckner",
"author_id": 1153,
"author_profile": "https://Stackoverflow.com/users/1153",
"pm_score": 2,
"selected": false,
"text": "<p>One method I am using on a current project - this also helps for other page-specific CSS needs.</p>\n\n<p>First, an HTML helper that returns a string that represents the current controller and action:</p>\n\n<pre><code>public static string BodyClass(RouteData data) {\n return string.Format(\"{0}-{1}\", data.Values[\"Controller\"], data.Values[\"Action\"]).ToLower();\n}\n</code></pre>\n\n<p>Then, add a call to this helper in your master page:</p>\n\n<pre><code><body class=\"<%=AppHelper.BodyClass(ViewContext.RouteData) %>\">\n...\n</body>\n</code></pre>\n\n<p>Now, you can target specific pages with your CSS. To answer your exact question about navigation:</p>\n\n<pre><code>#primaryNavigation a { ... }\n.home-index #primaryNavigation a#home { ... }\n.home-about #primaryNavigation a#about { ... }\n.home-contact #primaryNavigation a#contact { ... }\n/* etc. */\n</code></pre>\n"
},
{
"answer_id": 2927323,
"author": "Tomas Jansson",
"author_id": 280693,
"author_profile": "https://Stackoverflow.com/users/280693",
"pm_score": 3,
"selected": false,
"text": "<p>I wrote some simple helper classes to solve this problem. The solution looks att both which controller that is used as well as which action in the controller.</p>\n\n<pre><code>public static string ActiveTab(this HtmlHelper helper, string activeController, string[] activeActions, string cssClass) \n{ \n string currentAction = helper.ViewContext.Controller. \n ValueProvider.GetValue(\"action\").RawValue.ToString();\n string currentController = helper.ViewContext.Controller. \n ValueProvider.GetValue(\"controller\").RawValue.ToString(); \n string cssClassToUse = currentController == activeController && \n activeActions.Contains(currentAction) \n ? cssClass \n : string.Empty; \n return cssClassToUse; \n} \n</code></pre>\n\n<p>You can the call this extension method with: </p>\n\n<pre><code>Html.ActiveTab(\"Home\", new string[] {\"Index\", \"Home\"}, \"active\")\n</code></pre>\n\n<p>This will return \"active\" if we are on the HomeController in either the \"Index\" or the \"Home\" action. I also added some extra overloads to ActiveTab to make it easier to use, you can read the whole blog post on: <a href=\"http://blog.tomasjansson.com/2010/09/asp-net-mvc-helper-for-active-tab-in-tab-menu/\" rel=\"noreferrer\">http://www.tomasjansson.com/blog/2010/05/asp-net-mvc-helper-for-active-tab-in-tab-menu/</a>\n<br/><br/>Hope this will help someone.</p>\n\n<p>Regards,\n--Tomas</p>\n"
},
{
"answer_id": 17540826,
"author": "Ξ Π Π Π Π Π",
"author_id": 687190,
"author_profile": "https://Stackoverflow.com/users/687190",
"pm_score": 1,
"selected": false,
"text": "<p>MVC's default <code>Site.css</code> comes with a class named <code>'selectedLink'</code> which should be used for this.</p>\n\n<p>Add the following to your <code>ul</code> list in <code>_Layout.cshtml</code>:</p>\n\n<pre><code>@{\n var controller = @HttpContext.Current.Request.RequestContext.RouteData.Values[\"controller\"].ToString();\n}\n<ul id=\"menu\"> \n <li>@Html.ActionLink(\"Home\", \"Index\", \"Home\", null, new { @class = controller == \"Home\" ? \"selectedLink\" : \"\" })</li>\n ...\n</ul>\n</code></pre>\n\n<p>I know this is not clean. But just a quick and dirty way to get things rolling without messing with partial views or any of that sort.</p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/287679",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34133/"
] |
How do I create tabbed navigation with the "Current" tab highlighted in the UI?
|
Before MVC I looked at the file path and figured out which tab was currrent. Now it's a lot easier, you can assign the current tab based on the current controller.
Check it out ...
Most of the work happens in the usercontrol.
```
public partial class AdminNavigation : ViewUserControl
{
/// <summary>
/// This hold a collection of controllers and their respective "tabs." Each Tab should have at least one controller in the collection.
/// </summary>
private readonly IDictionary<Type, string> dict = new Dictionary<Type, string>();
public AdminNavigation()
{
dict.Add(typeof(BrandController), "catalog");
dict.Add(typeof(CatalogController), "catalog");
dict.Add(typeof(GroupController), "catalog");
dict.Add(typeof(ItemController), "catalog");
dict.Add(typeof(ConfigurationController), "configuration");
dict.Add(typeof(CustomerController), "customer");
dict.Add(typeof(DashboardController), "dashboard");
dict.Add(typeof(OrderController), "order");
dict.Add(typeof(WebsiteController), "website");
}
protected string SetClass(string linkToCheck)
{
Type controller = ViewContext.Controller.GetType();
// We need to determine if the linkToCheck is equal to the current controller using dict as a Map
string dictValue;
dict.TryGetValue(controller, out dictValue);
if (dictValue == linkToCheck)
{
return "current";
}
return "";
}
}
```
Then in your .ascx part of the usercontol call into the SetClass method to check the link against the dict. Like so:
```
<li class="<%= SetClass("customer") %>"><%= Html.ActionLink<CustomerController>(c=>c.Index(),"Customers",new{@class="nav_customers"}) %></li>
```
All you need now is the CSS to highlight your current tab. There are a bunch of different ways to do this, but you can get started with some ideas here: <http://webdeveloper.econsultant.com/css-menus-navigation-tabs/>
Oh, and don't forget to put the usercontrol on your page (or MasterPage) ...
```
<% Html.RenderPartial("AdminNavigation"); %>
```
|
287,684 |
<p>I'm using this simple regular expression to validate a hex string:</p>
<pre><code>^[A-Fa-f0-9]{16}$
</code></pre>
<p>As you can see, I'm using a quantifier to validate that the string is 16 characters long. I was wondering if I can use another quantifier in the same regex to validate the string length to be either 16 or 18 (not 17).</p>
|
[
{
"answer_id": 287687,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 3,
"selected": false,
"text": "<pre><code>^(?:[A-Fa-f0-9]{16}|[A-Fa-f0-9]{18})$\n</code></pre>\n"
},
{
"answer_id": 287692,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": false,
"text": "<p>That's just a 16 character requirement with an optional 2 character afterwards:</p>\n\n<pre><code>^[A-Fa-f0-9]{16}([A-Fa-f0-9]{2})?$\n</code></pre>\n\n<p>The parentheses may not be required - I'm not enough of a regex guru to know offhand, I'm afraid. If anyone wants to edit it, do feel free...</p>\n"
},
{
"answer_id": 287693,
"author": "David Norman",
"author_id": 34502,
"author_profile": "https://Stackoverflow.com/users/34502",
"pm_score": 7,
"selected": true,
"text": "<p>I believe</p>\n\n<pre><code>^([A-Fa-f0-9]{2}){8,9}$\n</code></pre>\n\n<p>will work.</p>\n\n<p>This is nice because it generalizes to any even-length string.</p>\n"
},
{
"answer_id": 287853,
"author": "John Fiala",
"author_id": 9143,
"author_profile": "https://Stackoverflow.com/users/9143",
"pm_score": 0,
"selected": false,
"text": "<p>I'd probably go with</p>\n\n<pre><code>/^[a-f0-9]{16}([a-f0-9]{2})?$/i\n</code></pre>\n\n<p>myself. I think it's more readable to set the regex as case insensitive and only list the character range once. That said, just about all of these answers work.</p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/287684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24927/"
] |
I'm using this simple regular expression to validate a hex string:
```
^[A-Fa-f0-9]{16}$
```
As you can see, I'm using a quantifier to validate that the string is 16 characters long. I was wondering if I can use another quantifier in the same regex to validate the string length to be either 16 or 18 (not 17).
|
I believe
```
^([A-Fa-f0-9]{2}){8,9}$
```
will work.
This is nice because it generalizes to any even-length string.
|
287,685 |
<p>I have a bunch of controls (textbox and combobox) on a form with toolstripcontainer and toolstripbuttons for save, cancel etc for edits. We are using .Net 3.5 SP1<br>
There is bunch of logic written in control.lostfocus and control.leave events. These events are not being called when clicked on the toolstrip buttons. Is there a way to call these events manually when any of these buttons are pressed.</p>
<p>Thanks.<br>
Kishore</p>
<p>[Edit]</p>
<p>This is how I solved the problem. Thanks <em><a href="https://stackoverflow.com/questions/287685/raise-lostfocus-event-on-a-control-manually-c#287740">Chris Marasti-Georg</a></em> for the pointer. In the button click event I calling focus on the toolstrip instead of the button as the toolstripbutton does not have a focus event. We can access the toolstrip on which the button is placed using</p>
<p>((ToolStripButton)sender).Owner.Focus()</p>
<p>-Kishore</p>
|
[
{
"answer_id": 287732,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>You can extend those controls and then call the OnLostFocus and OnLeave protected methods of the base class...</p>\n"
},
{
"answer_id": 287740,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 3,
"selected": true,
"text": "<p>You could listen to the click events on the buttons, and in the handler call their focus method. That would (hopefully) cause the previously focused control to respond correctly. Add the following handler to each button's click event:</p>\n\n<pre><code>private void ButtonClick(object sender, EventArgs e) {\n if(sender != null) {\n sender.Focus();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 287763,
"author": "configurator",
"author_id": 9536,
"author_profile": "https://Stackoverflow.com/users/9536",
"pm_score": 1,
"selected": false,
"text": "<p>I'd suggest moving the login to a method outside the event handler and calling that method...</p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/287685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18169/"
] |
I have a bunch of controls (textbox and combobox) on a form with toolstripcontainer and toolstripbuttons for save, cancel etc for edits. We are using .Net 3.5 SP1
There is bunch of logic written in control.lostfocus and control.leave events. These events are not being called when clicked on the toolstrip buttons. Is there a way to call these events manually when any of these buttons are pressed.
Thanks.
Kishore
[Edit]
This is how I solved the problem. Thanks *[Chris Marasti-Georg](https://stackoverflow.com/questions/287685/raise-lostfocus-event-on-a-control-manually-c#287740)* for the pointer. In the button click event I calling focus on the toolstrip instead of the button as the toolstripbutton does not have a focus event. We can access the toolstrip on which the button is placed using
((ToolStripButton)sender).Owner.Focus()
-Kishore
|
You could listen to the click events on the buttons, and in the handler call their focus method. That would (hopefully) cause the previously focused control to respond correctly. Add the following handler to each button's click event:
```
private void ButtonClick(object sender, EventArgs e) {
if(sender != null) {
sender.Focus();
}
}
```
|
287,703 |
<p>I'm using IIS 6 with EPiserver CMS which requires all requests to go through aspnet_isapi.dll.</p>
<p>I want to gzip all my static files (js, css mainly). Trying to setup compression in IIS didn't work.</p>
<p>Is there a setting in EPiServer that will allow me to achieve this?
Can .net framework compress files automatically?</p>
|
[
{
"answer_id": 287771,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 3,
"selected": true,
"text": "<p>You'll need to configure the html extension in the IIS metabase <strong>as a dynamically compressed extension</strong>. You are probably treating it as a static page. If the .js and .css extensions are mapped to aspnet_isapi they are considered as dynamic pages. </p>\n\n<p>The setting in <a href=\"http://www.microsoft.com/technet/prodtechnol/windowsserver2003/library/iis/a0ea8e51-fb2a-4e80-9d5a-7fe3ae246570.mspx\" rel=\"nofollow noreferrer\">metabase.xml</a> should look like this: </p>\n\n<pre><code>HcScriptFileExtensions=\"asp\ndll \nexe \njs\ncss\"\n</code></pre>\n\n<p>Don't forget to remove the extensions from <code>HcFileExtensions</code> (for static files) if you inserted them there before. </p>\n\n<p><em>Hope this helps.</em></p>\n"
},
{
"answer_id": 2308722,
"author": "Chris",
"author_id": 278436,
"author_profile": "https://Stackoverflow.com/users/278436",
"pm_score": 1,
"selected": false,
"text": "<p>What if you wanted to gzip all files (for use in a web service with extensionless URLs)?</p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/287703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29555/"
] |
I'm using IIS 6 with EPiserver CMS which requires all requests to go through aspnet\_isapi.dll.
I want to gzip all my static files (js, css mainly). Trying to setup compression in IIS didn't work.
Is there a setting in EPiServer that will allow me to achieve this?
Can .net framework compress files automatically?
|
You'll need to configure the html extension in the IIS metabase **as a dynamically compressed extension**. You are probably treating it as a static page. If the .js and .css extensions are mapped to aspnet\_isapi they are considered as dynamic pages.
The setting in [metabase.xml](http://www.microsoft.com/technet/prodtechnol/windowsserver2003/library/iis/a0ea8e51-fb2a-4e80-9d5a-7fe3ae246570.mspx) should look like this:
```
HcScriptFileExtensions="asp
dll
exe
js
css"
```
Don't forget to remove the extensions from `HcFileExtensions` (for static files) if you inserted them there before.
*Hope this helps.*
|
287,713 |
<p>I thought this code would work, but the regular expression doesn't ever match the \r\n. I have viewed the data I am reading in a hex editor and verified there really is a hex D and hex A pattern in the file.</p>
<p>I have also tried the regular expressions /\xD\xA/m and /\x0D\x0A/m but they also didn't match.</p>
<p>This is my code right now:</p>
<pre><code> lines2 = lines.gsub( /\r\n/m, "\n" )
if ( lines == lines2 )
print "still the same\n"
else
print "made the change\n"
end
</code></pre>
<p>In addition to alternatives, it would be nice to know what I'm doing wrong (to facilitate some learning on my part). :)</p>
|
[
{
"answer_id": 287735,
"author": "Cameron Price",
"author_id": 35526,
"author_profile": "https://Stackoverflow.com/users/35526",
"pm_score": 4,
"selected": false,
"text": "<pre><code>lines2 = lines.split.join(\"\\n\")\n</code></pre>\n"
},
{
"answer_id": 287739,
"author": "mwilliams",
"author_id": 23909,
"author_profile": "https://Stackoverflow.com/users/23909",
"pm_score": 3,
"selected": false,
"text": "<p>How about the following?</p>\n\n<pre><code>irb(main):003:0> my_string = \"Some text with a carriage return \\r\"\n=> \"Some text with a carriage return \\r\"\nirb(main):004:0> my_string.gsub(/\\r/,\"\")\n=> \"Some text with a carriage return \"\nirb(main):005:0>\n</code></pre>\n\n<p>Or...</p>\n\n<pre><code>irb(main):007:0> my_string = \"Some text with a carriage return \\r\\n\"\n=> \"Some text with a carriage return \\r\\n\"\nirb(main):008:0> my_string.gsub(/\\r\\n/,\"\\n\")\n=> \"Some text with a carriage return \\n\"\nirb(main):009:0>\n</code></pre>\n"
},
{
"answer_id": 287810,
"author": "localshred",
"author_id": 29690,
"author_profile": "https://Stackoverflow.com/users/29690",
"pm_score": 5,
"selected": false,
"text": "<p>Generally when I deal with stripping \\r or \\n, I'll look for both by doing something like</p>\n\n<pre><code>lines.gsub(/\\r\\n?/, \"\\n\");\n</code></pre>\n\n<p>I've found that depending on how the data was saved (the OS used, editor used, Jupiter's relation to Io at the time) there may or may not be the newline after the carriage return. It does seem weird that you see both characters in hex mode. Hope this helps.</p>\n"
},
{
"answer_id": 287890,
"author": "RΓ΄mulo Ceccon",
"author_id": 23193,
"author_profile": "https://Stackoverflow.com/users/23193",
"pm_score": 6,
"selected": true,
"text": "<p>What do you get when you do <code>puts lines</code>? That will give you a clue.</p>\n\n<p>By default <code>File.open</code> opens the file in text mode, so your <code>\\r\\n</code> characters will be automatically converted to <code>\\n</code>. Maybe that's the reason <code>lines</code> are always equal to <code>lines2</code>. To prevent Ruby from parsing the line ends use the <code>rb</code> mode:</p>\n\n<pre>C:\\> copy con lala.txt\na\nfile\nwith\nmany\nlines\n^Z\n\nC:\\> irb\nirb(main):001:0> text = File.open('lala.txt').read\n=> \"a\\nfile\\nwith\\nmany\\nlines\\n\"\nirb(main):002:0> bin = File.open('lala.txt', 'rb').read\n=> \"a\\r\\nfile\\r\\nwith\\r\\nmany\\r\\nlines\\r\\n\"\nirb(main):003:0>\n</pre>\n\n<p>But from your question and code I see you simply need to open the file with the default modifier. You don't need any conversion and may use the shorter <code>File.read</code>.</p>\n"
},
{
"answer_id": 7095275,
"author": "Ian Vaughan",
"author_id": 119790,
"author_profile": "https://Stackoverflow.com/users/119790",
"pm_score": 7,
"selected": false,
"text": "<p>Use <a href=\"http://ruby-doc.org/core-2.0.0/String.html#method-i-strip\" rel=\"noreferrer\">String#strip</a></p>\n\n<blockquote>\n <p>Returns a copy of str with leading and trailing whitespace removed.</p>\n</blockquote>\n\n<p>e.g</p>\n\n<pre><code>\" hello \".strip #=> \"hello\" \n\"\\tgoodbye\\r\\n\".strip #=> \"goodbye\"\n</code></pre>\n\n<hr>\n\n<p>Using gsub</p>\n\n<pre><code>string = string.gsub(/\\r/,\" \")\nstring = string.gsub(/\\n/,\" \")\n</code></pre>\n"
},
{
"answer_id": 7100078,
"author": "Andrew Grimm",
"author_id": 38765,
"author_profile": "https://Stackoverflow.com/users/38765",
"pm_score": 2,
"selected": false,
"text": "<p>Why not read the file in text mode, rather than binary mode?</p>\n"
},
{
"answer_id": 8340835,
"author": "Joel AZEMAR",
"author_id": 552320,
"author_profile": "https://Stackoverflow.com/users/552320",
"pm_score": 4,
"selected": false,
"text": "<p><code>\"still the same\\n\".chomp</code><br>\nor<br>\n<code>\"still the same\\n\".chomp!</code></p>\n\n<p><a href=\"http://www.ruby-doc.org/core-1.9.3/String.html#method-i-chomp\">http://www.ruby-doc.org/core-1.9.3/String.html#method-i-chomp</a></p>\n"
},
{
"answer_id": 8891341,
"author": "Vik",
"author_id": 387402,
"author_profile": "https://Stackoverflow.com/users/387402",
"pm_score": 4,
"selected": false,
"text": "<pre><code>modified_string = string.gsub(/\\s+/, ' ').strip\n</code></pre>\n"
},
{
"answer_id": 16900610,
"author": "Alain Beauvois",
"author_id": 183331,
"author_profile": "https://Stackoverflow.com/users/183331",
"pm_score": 1,
"selected": false,
"text": "<p>You can use this :</p>\n\n<pre><code>my_string.strip.gsub(/\\s+/, ' ')\n</code></pre>\n"
},
{
"answer_id": 35652555,
"author": "neck",
"author_id": 2979547,
"author_profile": "https://Stackoverflow.com/users/2979547",
"pm_score": 5,
"selected": false,
"text": "<p>If you are using Rails, there is a <code>squish</code> method</p>\n\n<p><code>\"\\tgoodbye\\r\\n\".squish => \"goodbye\"</code></p>\n\n<p><code>\"\\tgood \\t\\r\\nbye\\r\\n\".squish => \"good bye\"</code></p>\n"
},
{
"answer_id": 45759253,
"author": "frenesim",
"author_id": 1451180,
"author_profile": "https://Stackoverflow.com/users/1451180",
"pm_score": 2,
"selected": false,
"text": "<pre><code>lines.map(&:strip).join(\" \")\n</code></pre>\n"
},
{
"answer_id": 46591610,
"author": "Nathan Crause",
"author_id": 251930,
"author_profile": "https://Stackoverflow.com/users/251930",
"pm_score": 3,
"selected": false,
"text": "<p>I think your regex is almost complete - here's what I would do:</p>\n\n<pre><code>lines2 = lines.gsub(/[\\r\\n]+/m, \"\\n\")\n</code></pre>\n\n<p>In the above, I've put \\r and \\n into a class (that way it doesn't matter in which order they might appear) and added the \"+\" qualifier (so that \"\\r\\n\\r\\n\\r\\n\" would also match once, and the whole thing replaced with \"\\n\")</p>\n"
},
{
"answer_id": 48784893,
"author": "k1r8r0wn",
"author_id": 3914672,
"author_profile": "https://Stackoverflow.com/users/3914672",
"pm_score": 2,
"selected": false,
"text": "<p>Just another variant:</p>\n\n<pre><code>lines.delete(\" \\n\")\n</code></pre>\n"
},
{
"answer_id": 49424962,
"author": "Dennis",
"author_id": 2695716,
"author_profile": "https://Stackoverflow.com/users/2695716",
"pm_score": 0,
"selected": false,
"text": "<pre><code>def dos2unix(input)\n input.each_byte.map { |c| c.chr unless c == 13 }.join\nend\n\nremove_all_the_carriage_returns = dos2unix(some_blob)\n</code></pre>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/287713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7893/"
] |
I thought this code would work, but the regular expression doesn't ever match the \r\n. I have viewed the data I am reading in a hex editor and verified there really is a hex D and hex A pattern in the file.
I have also tried the regular expressions /\xD\xA/m and /\x0D\x0A/m but they also didn't match.
This is my code right now:
```
lines2 = lines.gsub( /\r\n/m, "\n" )
if ( lines == lines2 )
print "still the same\n"
else
print "made the change\n"
end
```
In addition to alternatives, it would be nice to know what I'm doing wrong (to facilitate some learning on my part). :)
|
What do you get when you do `puts lines`? That will give you a clue.
By default `File.open` opens the file in text mode, so your `\r\n` characters will be automatically converted to `\n`. Maybe that's the reason `lines` are always equal to `lines2`. To prevent Ruby from parsing the line ends use the `rb` mode:
```
C:\> copy con lala.txt
a
file
with
many
lines
^Z
C:\> irb
irb(main):001:0> text = File.open('lala.txt').read
=> "a\nfile\nwith\nmany\nlines\n"
irb(main):002:0> bin = File.open('lala.txt', 'rb').read
=> "a\r\nfile\r\nwith\r\nmany\r\nlines\r\n"
irb(main):003:0>
```
But from your question and code I see you simply need to open the file with the default modifier. You don't need any conversion and may use the shorter `File.read`.
|
287,717 |
<p>I am currently trying to create a menu system for a game and cannot arrive at any really sound way to do it. There are several menu screens, each of them non-trivial, so that I would like to keep these as separate classes. The main problem I am having is passing control between these menu screens.</p>
<p>I tried building each of the screens as a singleton and call one screen from the other directly, ie. something like <code>[[MainMenu instance] display]</code> in Objective C. This is a bit messy, because (1) I have to write the singleton boilerplate code for each of the menu screens and (2) the classes get dependent on each other, sometimes I have to code around circular dependencies etc.</p>
<p>I thought about making the classes fully static to get around the instance management (which is a bit extra in this case, since there really is just one instance of each screen). But this also looks quite ugly, especially with ObjectiveΒ C having to βfakeβ class variables by declaring them <code>static</code>.</p>
<p>Then I thought about some βmanagerβ class that would create the instances and pass the control around, but I am not sure introducing an extra class would solve the problem, especially if this class was to be named Manager :-)</p>
<p>I should note that I <em>do</em> have a working system, it just doesnβt feel very nice. By which IΒ mean there is a bit of code duplication going on, if I am not careful the thing might hang, and so on. Any ideas? I am aware that this is underspecified, so that the discussion will probably be more of a brainstorming, but I am interested in the ideas anyway, even if they do not outright solve my problem.</p>
<p><strong>Update: Thank You all for the ideas. What I did in the end:</strong></p>
<p>I reworked the menu contents (buttons, graphics, etc.) to fit under one interface called <code>ScreenView</code>. This is a general interface that looks like this:</p>
<pre><code>@protocol ScreenView
- (void) draw;
- (BOOL) handlesPoint: (CGPoint) p;
- (void) appearWithAnimation;
- (void) disappearWithAnimation;
- (BOOL) hasFinishedAnimating;
@optional
- (void) fingerDown;
- (void) fingerUp;
@end
</code></pre>
<p>Thanks to this protocol I was able to throw away all the specific menu screens and create a general menu screen that takes a list of subviews to display and handles all the presentation like drawing, transitions, events and such. This general menu screen does not get subclassed much, because most of the menu screens are happy simply displaying a list of subviews. This would be the V in MVC.</p>
<p>Then I also created a controller class that handles all the events for a certain menu screen. (Obviously the C in MVC.) The root controller class handles the instance management, transitions between menus and some other little things. Most of the menu screens get a customized subclass of the controller that handles the events from the buttons and other subviews.</p>
<p>The number of classes got up, but the code is much cleaner, does not repeat itself and is less prone to errors. The instance management is still not perfect, but Iβm reasonably happy with the design. Once again, thank to all who answered.</p>
|
[
{
"answer_id": 287784,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I think a MenuManager class would be the way to go. You'd have one Menu base class which all the menu screens derive from, and the manager would have a pointer to the currently active menu screen. It could also, for example, keep track of previous menu screens for easy use of back buttons on menu screens in arbitrary menu screen calls. Maybe just use a std::vector for that so you don't have to recreate the previous menu screens when going back (this would also prevent loss of entered information, like in an Options menu with an Advanced submenu).</p>\n"
},
{
"answer_id": 287826,
"author": "wisequark",
"author_id": 33159,
"author_profile": "https://Stackoverflow.com/users/33159",
"pm_score": 1,
"selected": false,
"text": "<p>Putting all the contents of the menus into a dictionary, dumping to a plist and reading each as necessary by the menu screens is likely the simplest route but in all honesty, you should consider taking a more MVC-centric approach to solving the problem. The screens should be for presentation of data not the storage of it. If you provide for a clean separation of the data from the views, the problem solves itself.</p>\n"
},
{
"answer_id": 287931,
"author": "Bill K",
"author_id": 12943,
"author_profile": "https://Stackoverflow.com/users/12943",
"pm_score": 3,
"selected": true,
"text": "<p>One of the tricks I learned to decent design is always separate your data from your code. This will do WONDERS for your specific problem.</p>\n\n<p>By this I mean that the menu items (strings) and relationships between the menus should be stored somewhere either in an array or a separate file (and read into an array).</p>\n\n<p>You then use this array to instantiate all your menu classes.</p>\n\n<p>Once you recode it to work this way (I've done this with menus), all your code will fall into place, you'll also factor out--90% of your menuing code (each menu will no longer be it's own class, just the same class instantiated with its own unique data.</p>\n\n<p>The target of the menu items are stored in the \"data\" as well (as method pointers or class instances).</p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/287717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17279/"
] |
I am currently trying to create a menu system for a game and cannot arrive at any really sound way to do it. There are several menu screens, each of them non-trivial, so that I would like to keep these as separate classes. The main problem I am having is passing control between these menu screens.
I tried building each of the screens as a singleton and call one screen from the other directly, ie. something like `[[MainMenu instance] display]` in Objective C. This is a bit messy, because (1) I have to write the singleton boilerplate code for each of the menu screens and (2) the classes get dependent on each other, sometimes I have to code around circular dependencies etc.
I thought about making the classes fully static to get around the instance management (which is a bit extra in this case, since there really is just one instance of each screen). But this also looks quite ugly, especially with ObjectiveΒ C having to βfakeβ class variables by declaring them `static`.
Then I thought about some βmanagerβ class that would create the instances and pass the control around, but I am not sure introducing an extra class would solve the problem, especially if this class was to be named Manager :-)
I should note that I *do* have a working system, it just doesnβt feel very nice. By which IΒ mean there is a bit of code duplication going on, if I am not careful the thing might hang, and so on. Any ideas? I am aware that this is underspecified, so that the discussion will probably be more of a brainstorming, but I am interested in the ideas anyway, even if they do not outright solve my problem.
**Update: Thank You all for the ideas. What I did in the end:**
I reworked the menu contents (buttons, graphics, etc.) to fit under one interface called `ScreenView`. This is a general interface that looks like this:
```
@protocol ScreenView
- (void) draw;
- (BOOL) handlesPoint: (CGPoint) p;
- (void) appearWithAnimation;
- (void) disappearWithAnimation;
- (BOOL) hasFinishedAnimating;
@optional
- (void) fingerDown;
- (void) fingerUp;
@end
```
Thanks to this protocol I was able to throw away all the specific menu screens and create a general menu screen that takes a list of subviews to display and handles all the presentation like drawing, transitions, events and such. This general menu screen does not get subclassed much, because most of the menu screens are happy simply displaying a list of subviews. This would be the V in MVC.
Then I also created a controller class that handles all the events for a certain menu screen. (Obviously the C in MVC.) The root controller class handles the instance management, transitions between menus and some other little things. Most of the menu screens get a customized subclass of the controller that handles the events from the buttons and other subviews.
The number of classes got up, but the code is much cleaner, does not repeat itself and is less prone to errors. The instance management is still not perfect, but Iβm reasonably happy with the design. Once again, thank to all who answered.
|
One of the tricks I learned to decent design is always separate your data from your code. This will do WONDERS for your specific problem.
By this I mean that the menu items (strings) and relationships between the menus should be stored somewhere either in an array or a separate file (and read into an array).
You then use this array to instantiate all your menu classes.
Once you recode it to work this way (I've done this with menus), all your code will fall into place, you'll also factor out--90% of your menuing code (each menu will no longer be it's own class, just the same class instantiated with its own unique data.
The target of the menu items are stored in the "data" as well (as method pointers or class instances).
|
287,750 |
<p>I have a webpage where I want the user to see a new image when they put thier mouse over a certain part of the image. I used an image map.</p>
<pre><code><img src="pic.jpg" usemap="#picmap" />
<map id="picmap" name="picmap"><area shape="rect" coords ="10,20,30,40"
onMouseOver="mouse_on_write('mouse is on spot')"
onMouseOut="mouse_off('mouse is off spot')"
href="http://www....html" target="_blank" />
</map>
<p id="desc"></p>
</code></pre>
<p>Where in the header I defined these functions:</p>
<pre><code> <script type="text/javascript">
function mouse_off(txt)
{
document.getElementById("desc").innerHTML=txt;
document.p1.src="pic.jpg";
}
function mouse_on_write(txt)
{
document.getElementById("desc").innerHTML=txt;
document.p1.src="pic2.jpg";
</script>
</code></pre>
<p>It works, but it is slow. When the mouse is put over the second image it takes some few seconds to appear; my temporary solution was to drastically reduce the size of the images because they were huge (at 2.5mb they switch fast now, but still not seamless). <strong>How can I make the image switching more seamless without reduction in picture quality?</strong>
On second thought I realize that I could also just have both images displayed, at a small and a large scale, and <strong>on mouse over they would switch places; How would I do this?</strong> Would this reduce lag? </p>
|
[
{
"answer_id": 287766,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 1,
"selected": false,
"text": "<p>What you want todo is preload the images behind the scenes.</p>\n\n<p>Then, when moused over, the browser will already have that image in its cache and will switch it over very fast.</p>\n\n<pre><code>function preloadImage(imagePath)\n{\n var img = document.createElement('IMG');\n img.src = imagePath; \n}\n\npreloadImage('BigImage');\n</code></pre>\n"
},
{
"answer_id": 287780,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": 6,
"selected": true,
"text": "<p>You don't need to create any page elements, it can all be preloaded using JavaScript:</p>\n\n<pre><code>tempImg = new Image()\ntempImg.src=\"pic2.jpg\"\n</code></pre>\n\n<p>EDIT:</p>\n\n<p>If you have a lot of images, you can use the poor-man's multi-preloader:</p>\n\n<pre><code>preloads = \"red.gif,green.gif,blue.gif\".split(\",\")\nvar tempImg = []\n\nfor(var x=0;x<preloads.length;x++) {\n tempImg[x] = new Image()\n tempImg[x].src = preloads[x]\n}\n</code></pre>\n"
},
{
"answer_id": 287850,
"author": "Slartibartfast",
"author_id": 4433,
"author_profile": "https://Stackoverflow.com/users/4433",
"pm_score": 2,
"selected": false,
"text": "<p>You can also put both images in same file and offset it up and down. If it should affect element you are crossing over with mouse it could look like </p>\n\n<pre><code>a { \n background-image: url(back.png); \n background-repeat: no-repeat; \n background-attachment:fixed; \n background-position: 0 0;\n}\n\na:hover {\n background-image: url(back.png); \n background-repeat: no-repeat; \n background-attachment:fixed; \n background-position: 0 20px; \n} \n</code></pre>\n\n<p>This way it can work without javascript. </p>\n\n<p>If I understand your case correctly you still need javascript, but you can \"preload\" image this way nevertheless. </p>\n"
},
{
"answer_id": 287870,
"author": "Adam Lassek",
"author_id": 1249,
"author_profile": "https://Stackoverflow.com/users/1249",
"pm_score": 4,
"selected": false,
"text": "<p>Doing this with sprites is a good solution, because you don't have to wait to load the new image. Sprites work by combining the two images into one, and changing the background offset on mouseover.</p>\n\n<p>You can even do with with CSS instead, for much faster results. There's a good tutorial on this <a href=\"http://www.alistapart.com/articles/sprites/\" rel=\"noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 287882,
"author": "coppro",
"author_id": 16855,
"author_profile": "https://Stackoverflow.com/users/16855",
"pm_score": 0,
"selected": false,
"text": "<p>Use <code>display: none;</code>, then have the Javascript change it to <code>display: inline</code> when you want to display it. This has the added advantage of being able to put the image exactly where you want in the page's source, rather than having to add it with Javascript later.</p>\n"
},
{
"answer_id": 287908,
"author": "dshaw",
"author_id": 32595,
"author_profile": "https://Stackoverflow.com/users/32595",
"pm_score": 1,
"selected": false,
"text": "<p>Clever solution from Diodeus. However, unless there's a good reason NOT TO, you should really consider using sprites. It's a bit of work to get them setup, but the net efficiency is really worth it.</p>\n\n<p>This approach is the number one rule in Steve Souder's <a href=\"http://stevesouders.com/hpws/rules.php\" rel=\"nofollow noreferrer\">High Performance Web Sites</a>.</p>\n\n<p><strong>\"Rule 1 - Make Fewer HTTP Requests\"</strong> </p>\n\n<p>Good luck and have fun. - D.</p>\n"
},
{
"answer_id": 288114,
"author": "Andrew Hedges",
"author_id": 11577,
"author_profile": "https://Stackoverflow.com/users/11577",
"pm_score": 0,
"selected": false,
"text": "<p>Here's how I do it, in pure JavaScript:</p>\n\n<pre><code>var myImgs = ['path/to/img1.jpg', 'path/to/img2.gif'];\n\nfunction preload(imgs) {\n var img;\n for (var i = 0, len = imgs.length; i < len; ++i) {\n img = new Image();\n img.src = imgs[i];\n }\n}\n\npreload(myImgs);\n</code></pre>\n\n<p>That said, ALassek's suggestion of using CSS sprites is an excellent one, if you have scope to do it. The advantages of sprites are many: fewer HTTP requests, smaller download size (usually), works without JavaScript enabled.</p>\n"
},
{
"answer_id": 288300,
"author": "Kon",
"author_id": 22303,
"author_profile": "https://Stackoverflow.com/users/22303",
"pm_score": 1,
"selected": false,
"text": "<p>I've noticed that 'preloading' into .src to this day doesn't work consistently across all browsers - IE7 <strong>still</strong> can't figure out how to cache / use preloaded images - you can clearly see there's a server request made every time you mouse over.</p>\n\n<p>What I do is load in all images via standard HTML placement and just toggle style.display on and off.</p>\n"
},
{
"answer_id": 288698,
"author": "micmcg",
"author_id": 28416,
"author_profile": "https://Stackoverflow.com/users/28416",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://www.filamentgroup.com/lab/update_automatically_preload_images_from_css_with_jquery/\" rel=\"nofollow noreferrer\">http://www.filamentgroup.com/lab/update_automatically_preload_images_from_css_with_jquery/</a></p>\n\n<p>When we first launched the lab, we released a jQuery plugin that automatically preloads all images referenced in CSS files. We've found the script to be incredibly helpful in developing snappy applications where images are always ready when we need them. This post describes a significant update to the script which will make it even easier to integrate in existing projects.</p>\n"
},
{
"answer_id": 6990691,
"author": "Turadg",
"author_id": 46040,
"author_profile": "https://Stackoverflow.com/users/46040",
"pm_score": 3,
"selected": false,
"text": "<p>As of Javascript 1.6 this can be accomplished without any named variables:</p>\n\n<pre><code>imageList.forEach( function(path) { new Image().src=path } );\n</code></pre>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/287750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30181/"
] |
I have a webpage where I want the user to see a new image when they put thier mouse over a certain part of the image. I used an image map.
```
<img src="pic.jpg" usemap="#picmap" />
<map id="picmap" name="picmap"><area shape="rect" coords ="10,20,30,40"
onMouseOver="mouse_on_write('mouse is on spot')"
onMouseOut="mouse_off('mouse is off spot')"
href="http://www....html" target="_blank" />
</map>
<p id="desc"></p>
```
Where in the header I defined these functions:
```
<script type="text/javascript">
function mouse_off(txt)
{
document.getElementById("desc").innerHTML=txt;
document.p1.src="pic.jpg";
}
function mouse_on_write(txt)
{
document.getElementById("desc").innerHTML=txt;
document.p1.src="pic2.jpg";
</script>
```
It works, but it is slow. When the mouse is put over the second image it takes some few seconds to appear; my temporary solution was to drastically reduce the size of the images because they were huge (at 2.5mb they switch fast now, but still not seamless). **How can I make the image switching more seamless without reduction in picture quality?**
On second thought I realize that I could also just have both images displayed, at a small and a large scale, and **on mouse over they would switch places; How would I do this?** Would this reduce lag?
|
You don't need to create any page elements, it can all be preloaded using JavaScript:
```
tempImg = new Image()
tempImg.src="pic2.jpg"
```
EDIT:
If you have a lot of images, you can use the poor-man's multi-preloader:
```
preloads = "red.gif,green.gif,blue.gif".split(",")
var tempImg = []
for(var x=0;x<preloads.length;x++) {
tempImg[x] = new Image()
tempImg[x].src = preloads[x]
}
```
|
287,757 |
<p>I read the part of <a href="http://docs.python.org/library/configparser.html" rel="noreferrer">the docs</a> and saw that the <code>ConfigParser</code> returns a list of key/value pairs for the options within a section. I figured that keys did not need to be unique within a section, otherwise the parser would just return a mapping. I designed my config file schema around this assumption, then sadly realized that this is not the case:</p>
<pre><code>>>> from ConfigParser import ConfigParser
>>> from StringIO import StringIO
>>> fh = StringIO("""
... [Some Section]
... spam: eggs
... spam: ham
... """)
>>> parser = ConfigParser()
>>> parser.readfp(fh)
>>> print parser.items('Some Section')
[('spam', 'ham')]
</code></pre>
<p>Then I went back and found the part of the docs that I <em>should</em> have read:</p>
<blockquote>
<p>Sections are normally stored in a
builtin dictionary. An alternative
dictionary type can be passed to the
ConfigParser constructor. For example,
if a dictionary type is passed that
sorts its keys, the sections will be
sorted on write-back, as will be the
keys within each section.</p>
</blockquote>
<p>To keep my existing configuration file scheme (which I really like now ;) I'm thinking of passing a mapping-like object as mentioned above that accumulates values instead of clobbering them. Is there a simpler way to prevent key/value collapse that I'm missing? Instead of making a crazy adapter (that could break if <code>ConfigParser</code>'s implementation changes) should I just write a variant of the <code>ConfigParser</code> itself?</p>
<p>I feel like this may be one of those 'duh' moments where I'm only seeing the difficult solutions.</p>
<p><strong>[Edit:]</strong> Here's a more precise example of how I'd like to use the same key multiple times:</p>
<pre><code>[Ignored Paths]
ignore-extension: .swp
ignore-filename: tags
ignore-directory: bin
</code></pre>
<p>I dislike the comma-delimited-list syntax because it's hard on the eyes when you scale it to many values; for example, a comma delimited list of fifty extensions would not be particularly readable.</p>
|
[
{
"answer_id": 287942,
"author": "Jeremy Cantrell",
"author_id": 18866,
"author_profile": "https://Stackoverflow.com/users/18866",
"pm_score": 4,
"selected": true,
"text": "<p>ConfigParser isn't designed to handle such conditions. Furthermore, your config file doesn't make sense to me.</p>\n\n<p>ConfigParser gives you a dict-like structure for each section, so when you call parser.items(section), I'm expecting similar output to dict.items(), which is just a list of key/value tuples. I would never expect to see something like:</p>\n\n<pre><code>[('spam', 'eggs'), ('spam', 'ham')]\n</code></pre>\n\n<p>Not to mention, how would you expect the following to behave?:</p>\n\n<pre><code>parser.get('Some Section', 'spam')\n</code></pre>\n\n<p>Which is the intended way to retrieve values.</p>\n\n<p>If you want to store multiple values for the same key, I would suggest something like this in your config file:</p>\n\n<pre><code>[Some Section]\nspam: eggs, ham\n</code></pre>\n\n<p>And this in your code:</p>\n\n<pre><code>spam_values = [v.strip() for v in parser.get('Some Section', 'spam').split(',')]\n</code></pre>\n\n<p>Of course, this will only work for values that don't contain commas themselves or handle quoting. For that, you should employ a more advanced technique (see <a href=\"https://stackoverflow.com/questions/118096/how-can-i-parse-a-comma-delimited-string-into-a-list-caveat\">this</a> and <a href=\"https://stackoverflow.com/questions/118458/how-can-i-join-a-list-into-a-string-caveat\">this</a>).</p>\n\n<p>EDIT: If you don't mind the extra dependency, You could check out <a href=\"http://www.voidspace.org.uk/python/configobj.html\" rel=\"nofollow noreferrer\">ConfigObj</a>, which natively supports lists as a value type.</p>\n"
},
{
"answer_id": 13340655,
"author": "anatoly techtonik",
"author_id": 239247,
"author_profile": "https://Stackoverflow.com/users/239247",
"pm_score": 0,
"selected": false,
"text": "<p>This deficiency of ConfigParser is the reason why pyglet used <a href=\"http://code.google.com/p/pyglet/source/diff?spec=svnffc4fe58bc2179a75d3338aa821eb04649609871&old=95d2cfa3167ddd5ca7eb0cd25c277902370fd7f1&r=ffc4fe58bc2179a75d3338aa821eb04649609871&format=unidiff&path=%2Ftools%2Fepydoc%2Fepydoc%2Fcli.py\" rel=\"nofollow\">patched version of epydoc</a> to replace ConfigParser ini with this <a href=\"http://code.google.com/p/pyglet/source/diff?format=unidiff&path=/tools/epydoc.config&r=ffc4fe58bc2179a75d3338aa821eb04649609871&spec=svnffc4fe58bc2179a75d3338aa821eb04649609871\" rel=\"nofollow\">simple format</a>:</p>\n\n<pre><code>name: pyglet\nurl: http://www.pyglet.org/\n\noutput: html\ntarget: doc/api/\n... \nmodule: pyglet\n\nexclude: pyglet.gl.gl\nexclude: pyglet.gl.agl\nexclude: pyglet.gl.lib_agl\nexclude: pyglet.gl.wgl\n...\n</code></pre>\n\n<p>If you don't need sections - this approach can be useful.</p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/287757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3594/"
] |
I read the part of [the docs](http://docs.python.org/library/configparser.html) and saw that the `ConfigParser` returns a list of key/value pairs for the options within a section. I figured that keys did not need to be unique within a section, otherwise the parser would just return a mapping. I designed my config file schema around this assumption, then sadly realized that this is not the case:
```
>>> from ConfigParser import ConfigParser
>>> from StringIO import StringIO
>>> fh = StringIO("""
... [Some Section]
... spam: eggs
... spam: ham
... """)
>>> parser = ConfigParser()
>>> parser.readfp(fh)
>>> print parser.items('Some Section')
[('spam', 'ham')]
```
Then I went back and found the part of the docs that I *should* have read:
>
> Sections are normally stored in a
> builtin dictionary. An alternative
> dictionary type can be passed to the
> ConfigParser constructor. For example,
> if a dictionary type is passed that
> sorts its keys, the sections will be
> sorted on write-back, as will be the
> keys within each section.
>
>
>
To keep my existing configuration file scheme (which I really like now ;) I'm thinking of passing a mapping-like object as mentioned above that accumulates values instead of clobbering them. Is there a simpler way to prevent key/value collapse that I'm missing? Instead of making a crazy adapter (that could break if `ConfigParser`'s implementation changes) should I just write a variant of the `ConfigParser` itself?
I feel like this may be one of those 'duh' moments where I'm only seeing the difficult solutions.
**[Edit:]** Here's a more precise example of how I'd like to use the same key multiple times:
```
[Ignored Paths]
ignore-extension: .swp
ignore-filename: tags
ignore-directory: bin
```
I dislike the comma-delimited-list syntax because it's hard on the eyes when you scale it to many values; for example, a comma delimited list of fifty extensions would not be particularly readable.
|
ConfigParser isn't designed to handle such conditions. Furthermore, your config file doesn't make sense to me.
ConfigParser gives you a dict-like structure for each section, so when you call parser.items(section), I'm expecting similar output to dict.items(), which is just a list of key/value tuples. I would never expect to see something like:
```
[('spam', 'eggs'), ('spam', 'ham')]
```
Not to mention, how would you expect the following to behave?:
```
parser.get('Some Section', 'spam')
```
Which is the intended way to retrieve values.
If you want to store multiple values for the same key, I would suggest something like this in your config file:
```
[Some Section]
spam: eggs, ham
```
And this in your code:
```
spam_values = [v.strip() for v in parser.get('Some Section', 'spam').split(',')]
```
Of course, this will only work for values that don't contain commas themselves or handle quoting. For that, you should employ a more advanced technique (see [this](https://stackoverflow.com/questions/118096/how-can-i-parse-a-comma-delimited-string-into-a-list-caveat) and [this](https://stackoverflow.com/questions/118458/how-can-i-join-a-list-into-a-string-caveat)).
EDIT: If you don't mind the extra dependency, You could check out [ConfigObj](http://www.voidspace.org.uk/python/configobj.html), which natively supports lists as a value type.
|
287,783 |
<p>I am using an ancient version of Oracle (8.something) and my ADO.NET application needs to do some fairly large transactions. Large enough to not fin in our small rollback segments. Now we have a large rollback segment as well but it is not used by default.</p>
<p>Oracle has a command to select the rollback segment to be used (<code>SET TRANSACTION USE ROLLBACK SEGMENT MY_ROLLBACK_SEGMENT</code>) but it needs to be the first command issued in the transaction. Unfortunately, it seems that ADO.NET issues some other commands at the beginning of a transaction since issuing this command right after .BeginTransaction() throws an error about SET TRANSACTION not being the first command.</p>
<p>I am sure I am not the only one who faced this issue. How do you solve it or how would you get around it?</p>
<p>Thanks</p>
|
[
{
"answer_id": 289832,
"author": "pablo",
"author_id": 16112,
"author_profile": "https://Stackoverflow.com/users/16112",
"pm_score": 2,
"selected": true,
"text": "<p>If this is a 'one-off' requirement then one solution is to put the other rollback segments offline while you run your transactions then put them online when you've finished;</p>\n\n<pre><code>ALTER ROLLBACK SEGMENT <name> OFFLINE;\n\nALTER ROLLBACK SEGMENT <name> ONLINE;\n</code></pre>\n\n<p>Otherwise make all the rollback segments the same size.</p>\n"
},
{
"answer_id": 290399,
"author": "Freakent",
"author_id": 32747,
"author_profile": "https://Stackoverflow.com/users/32747",
"pm_score": 0,
"selected": false,
"text": "<p>I have absolutely no way of testing this, but you could try issuing a save point before your set transaction statement, e.g.</p>\n\n<blockquote>\n <p>SAVEPOINT use_big_rbs;</p>\n \n <p>SET TRANSACTION USE ROLLBACK SEGMENT big_rbs;</p>\n \n <p>UPDATE ...</p>\n \n <p>...</p>\n</blockquote>\n"
},
{
"answer_id": 291629,
"author": "Khb",
"author_id": 37817,
"author_profile": "https://Stackoverflow.com/users/37817",
"pm_score": 1,
"selected": false,
"text": "<p>I can't test this on Oracle 8, but on newer versions you can explicitly start a new transaction by issuing a commit and then altering the rollback segment.</p>\n\n<p>I assume this is a procedure / function.</p>\n\n<pre><code>begin\ncommit;\nSET TRANSACTION USE ROLLBACK SEGMENT UNDOTBS1;\n--Your code here\nend;\n</code></pre>\n\n<p>Regards\nK</p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/287783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8954/"
] |
I am using an ancient version of Oracle (8.something) and my ADO.NET application needs to do some fairly large transactions. Large enough to not fin in our small rollback segments. Now we have a large rollback segment as well but it is not used by default.
Oracle has a command to select the rollback segment to be used (`SET TRANSACTION USE ROLLBACK SEGMENT MY_ROLLBACK_SEGMENT`) but it needs to be the first command issued in the transaction. Unfortunately, it seems that ADO.NET issues some other commands at the beginning of a transaction since issuing this command right after .BeginTransaction() throws an error about SET TRANSACTION not being the first command.
I am sure I am not the only one who faced this issue. How do you solve it or how would you get around it?
Thanks
|
If this is a 'one-off' requirement then one solution is to put the other rollback segments offline while you run your transactions then put them online when you've finished;
```
ALTER ROLLBACK SEGMENT <name> OFFLINE;
ALTER ROLLBACK SEGMENT <name> ONLINE;
```
Otherwise make all the rollback segments the same size.
|
287,789 |
<p>I have a huge file that I must parse line by line. Speed is of the essence. </p>
<p>Example of a line:</p>
<blockquote>
<pre><code>Token-1 Here-is-the-Next-Token Last-Token-on-Line
^ ^
Current Position
Position after GetToken
</code></pre>
</blockquote>
<p>GetToken is called, returning "Here-is-the-Next-Token" and sets the CurrentPosition to the position of the last character of the token so that it is ready for the next call to GetToken. Tokens are separated by one or more spaces.</p>
<p>Assume the file is already in a StringList in memory. It fits in memory easily, say 200 MB.</p>
<p>I am worried only about the execution time for the parsing. What code will produce the absolute fastest execution in Delphi (Pascal)?</p>
|
[
{
"answer_id": 287803,
"author": "utku_karatas",
"author_id": 14716,
"author_profile": "https://Stackoverflow.com/users/14716",
"pm_score": 0,
"selected": false,
"text": "<p>Rolling your own is the fastest way for sure. For more on this topic, you could see <a href=\"http://synedit.sourceforge.net/\" rel=\"nofollow noreferrer\">Synedit's source code</a> which contains lexers (called highlighters in the project's context) for about any language on the market. I suggest you take one of those lexers as a base and modify for your own usage.</p>\n"
},
{
"answer_id": 287808,
"author": "Toon Krijthe",
"author_id": 18061,
"author_profile": "https://Stackoverflow.com/users/18061",
"pm_score": 2,
"selected": false,
"text": "<p>I made a lexical analyser based on a state engine (DFA). It works with a table and is pretty fast. But there are possible faster options. </p>\n\n<p>It also depends on the language. A simple language can possibly have a smart algorithm.</p>\n\n<p>The table is an array of records each containing 2 chars and 1 integer. For each token the lexer walks through the table, startting at position 0:</p>\n\n<pre><code>state := 0;\nresult := tkNoToken;\nwhile (result = tkNoToken) do begin\n if table[state].c1 > table[state].c2 then\n result := table[state].value\n else if (table[state].c1 <= c) and (c <= table[state].c2) then begin\n c := GetNextChar();\n state := table[state].value;\n end else\n Inc(state);\nend;\n</code></pre>\n\n<p>It is simple and works like a charm.</p>\n"
},
{
"answer_id": 287819,
"author": "Steve",
"author_id": 22712,
"author_profile": "https://Stackoverflow.com/users/22712",
"pm_score": 1,
"selected": false,
"text": "<p>I think the biggest bottleneck is always going to be getting the file into memory. Once you have it in memory (obviously not all of it at once, but I would work with buffers if I were you), the actual parsing should be insignificant.</p>\n"
},
{
"answer_id": 287865,
"author": "Bruce McGee",
"author_id": 19183,
"author_profile": "https://Stackoverflow.com/users/19183",
"pm_score": 0,
"selected": false,
"text": "<p>The fastest way to <strong>write</strong> the code would probably be to create a TStringList and assign each line in your text file to the CommaText property. By default, white space is a delimiter, so you will get one StringList item per token.</p>\n\n<pre><code>MyStringList.CommaText := s;\nfor i := 0 to MyStringList.Count - 1 do\nbegin\n // process each token here\nend;\n</code></pre>\n\n<p>You'll probably get better performance by parsing each line yourself, though.</p>\n"
},
{
"answer_id": 287876,
"author": "utku_karatas",
"author_id": 14716,
"author_profile": "https://Stackoverflow.com/users/14716",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a lame ass implementation of a very simple lexer. This might give you an idea. </p>\n\n<p>Note the limitations of this example - no buffering involved, no Unicode (this is an excerpt from a Delphi 7 project). You would probably need those in a serious implementation.</p>\n\n<pre><code>{ Implements a simpe lexer class. } \nunit Simplelexer;\n\ninterface\n\nuses Classes, Sysutils, Types, dialogs;\n\ntype\n\n ESimpleLexerFinished = class(Exception) end;\n\n TProcTableProc = procedure of object;\n\n // A very simple lexer that can handle numbers, words, symbols - no comment handling \n TSimpleLexer = class(TObject)\n private\n FLineNo: Integer;\n Run: Integer;\n fOffset: Integer;\n fRunOffset: Integer; // helper for fOffset\n fTokenPos: Integer;\n pSource: PChar;\n fProcTable: array[#0..#255] of TProcTableProc;\n fUseSimpleStrings: Boolean;\n fIgnoreSpaces: Boolean;\n procedure MakeMethodTables;\n procedure IdentProc;\n procedure NewLineProc;\n procedure NullProc;\n procedure NumberProc;\n procedure SpaceProc;\n procedure SymbolProc;\n procedure UnknownProc;\n public\n constructor Create;\n destructor Destroy; override;\n procedure Feed(const S: string);\n procedure Next;\n function GetToken: string;\n function GetLineNo: Integer;\n function GetOffset: Integer;\n\n property IgnoreSpaces: boolean read fIgnoreSpaces write fIgnoreSpaces;\n property UseSimpleStrings: boolean read fUseSimpleStrings write fUseSimpleStrings;\n end;\n\nimplementation\n\n{ TSimpleLexer }\n\nconstructor TSimpleLexer.Create;\nbegin\n makeMethodTables;\n fUseSimpleStrings := false;\n fIgnoreSpaces := false;\nend;\n\ndestructor TSimpleLexer.Destroy;\nbegin\n inherited;\nend;\n\nprocedure TSimpleLexer.Feed(const S: string);\nbegin\n Run := 0;\n FLineNo := 1;\n FOffset := 1;\n pSource := PChar(S);\nend;\n\nprocedure TSimpleLexer.Next;\nbegin\n fTokenPos := Run;\n foffset := Run - frunOffset + 1;\n fProcTable[pSource[Run]];\nend;\n\nfunction TSimpleLexer.GetToken: string;\nbegin\n SetString(Result, (pSource + fTokenPos), Run - fTokenPos);\nend;\n\nfunction TSimpleLexer.GetLineNo: Integer;\nbegin\n Result := FLineNo;\nend;\n\nfunction TSimpleLexer.GetOffset: Integer;\nbegin\n Result := foffset;\nend;\n\nprocedure TSimpleLexer.MakeMethodTables;\nvar\n I: Char;\nbegin\n for I := #0 to #255 do\n case I of\n '@', '&', '}', '{', ':', ',', ']', '[', '*',\n '^', ')', '(', ';', '/', '=', '-', '+', '#', '>', '<', '$',\n '.', '\"', #39:\n fProcTable[I] := SymbolProc;\n #13, #10: fProcTable[I] := NewLineProc;\n 'A'..'Z', 'a'..'z', '_': fProcTable[I] := IdentProc;\n #0: fProcTable[I] := NullProc;\n '0'..'9': fProcTable[I] := NumberProc;\n #1..#9, #11, #12, #14..#32: fProcTable[I] := SpaceProc;\n else\n fProcTable[I] := UnknownProc;\n end;\nend;\n\nprocedure TSimpleLexer.UnknownProc;\nbegin\n inc(run);\nend;\n\nprocedure TSimpleLexer.SymbolProc;\nbegin\n if fUseSimpleStrings then\n begin\n if pSource[run] = '\"' then\n begin\n Inc(run);\n while pSource[run] <> '\"' do\n begin\n Inc(run);\n if pSource[run] = #0 then\n begin\n NullProc;\n end;\n end;\n end;\n Inc(run);\n end\n else\n inc(run);\nend;\n\nprocedure TSimpleLexer.IdentProc;\nbegin\n while pSource[Run] in ['_', 'A'..'Z', 'a'..'z', '0'..'9'] do\n Inc(run);\nend;\n\nprocedure TSimpleLexer.NumberProc;\nbegin\n while pSource[run] in ['0'..'9'] do\n inc(run);\nend;\n\nprocedure TSimpleLexer.SpaceProc;\nbegin\n while pSource[run] in [#1..#9, #11, #12, #14..#32] do\n inc(run);\n if fIgnoreSpaces then Next;\nend;\n\nprocedure TSimpleLexer.NewLineProc;\nbegin\n inc(FLineNo);\n inc(run);\n case pSource[run - 1] of\n #13:\n if pSource[run] = #10 then inc(run);\n end;\n foffset := 1;\n fRunOffset := run;\nend;\n\nprocedure TSimpleLexer.NullProc;\nbegin\n raise ESimpleLexerFinished.Create('');\nend;\n\nend.\n</code></pre>\n"
},
{
"answer_id": 288000,
"author": "Despatcher",
"author_id": 10240,
"author_profile": "https://Stackoverflow.com/users/10240",
"pm_score": 1,
"selected": false,
"text": "<p>This begs another question - How big?\nGive us a clue like # of lines or # or Mb (Gb)?\nThen we will know if it fits in memory, needs to be disk based etc.</p>\n\n<p>At first pass I would use my WordList(S: String; AList: TStringlist);</p>\n\n<p>then you can access each token as Alist[n]...\nor sort them or whatever. </p>\n"
},
{
"answer_id": 288195,
"author": "Barry Kelly",
"author_id": 3712,
"author_profile": "https://Stackoverflow.com/users/3712",
"pm_score": 6,
"selected": true,
"text": "<ul>\n<li>Use PChar incrementing for speed of processing</li>\n<li>If some tokens are not needed, only copy token data on demand</li>\n<li>Copy PChar to local variable when actually scanning through characters</li>\n<li>Keep source data in a single buffer unless you must handle line by line, and even then, consider handling line processing as a separate token in the lexer recognizer</li>\n<li>Consider processing a byte array buffer that has come straight from the file, if you definitely know the encoding; if using Delphi 2009, use PAnsiChar instead of PChar, unless of course you know the encoding is UTF16-LE.</li>\n<li>If you know that the only whitespace is going to be #32 (ASCII space), or a similarly limited set of characters, there may be some clever bit manipulation hacks that can let you process 4 bytes at a time using Integer scanning. I wouldn't expect big wins here though, and the code will be as clear as mud.</li>\n</ul>\n\n<p>Here's a sample lexer that should be pretty efficient, but it assumes that all source data is in a single string. Reworking it to handle buffers is moderately tricky due to very long tokens.</p>\n\n<pre><code>type\n TLexer = class\n private\n FData: string;\n FTokenStart: PChar;\n FCurrPos: PChar;\n function GetCurrentToken: string;\n public\n constructor Create(const AData: string);\n function GetNextToken: Boolean;\n property CurrentToken: string read GetCurrentToken;\n end;\n\n{ TLexer }\n\nconstructor TLexer.Create(const AData: string);\nbegin\n FData := AData;\n FCurrPos := PChar(FData);\nend;\n\nfunction TLexer.GetCurrentToken: string;\nbegin\n SetString(Result, FTokenStart, FCurrPos - FTokenStart);\nend;\n\nfunction TLexer.GetNextToken: Boolean;\nvar\n cp: PChar;\nbegin\n cp := FCurrPos; // copy to local to permit register allocation\n\n // skip whitespace; this test could be converted to an unsigned int\n // subtraction and compare for only a single branch\n while (cp^ > #0) and (cp^ <= #32) do\n Inc(cp);\n\n // using null terminater for end of file\n Result := cp^ <> #0;\n\n if Result then\n begin\n FTokenStart := cp;\n Inc(cp);\n while cp^ > #32 do\n Inc(cp);\n end;\n\n FCurrPos := cp;\nend;\n</code></pre>\n"
},
{
"answer_id": 288330,
"author": "skamradt",
"author_id": 9217,
"author_profile": "https://Stackoverflow.com/users/9217",
"pm_score": 1,
"selected": false,
"text": "<p>Speed will always be relative to what you are doing once it is parsed. A lexical parser by far is the fastest method of converting to tokens from a text stream regardless of size. TParser in the classes unit is a great place to start. </p>\n\n<p>Personally its been a while since I needed to write a parser, but another more dated yet tried and true method would be to use LEX/YACC to build a grammar then have it convert the grammar into code you can use to perform your processing. <a href=\"http://www.geocities.com/robertzierer/Tools.html\" rel=\"nofollow noreferrer\">DYacc</a> is a Delphi version...not sure if it still compiles or not, but worth a look if you want to do things old school. The <a href=\"http://en.wikipedia.org/wiki/Principles_of_Compiler_Design\" rel=\"nofollow noreferrer\">dragon book</a> here would be of big help, if you can find a copy.</p>\n"
},
{
"answer_id": 289774,
"author": "mj2008",
"author_id": 5544,
"author_profile": "https://Stackoverflow.com/users/5544",
"pm_score": 2,
"selected": false,
"text": "<p>If speed is of the essence, custom code is the answer. Check out the Windows API that will map your file into memory. You can then just use a pointer to the next character to do your tokens, marching through as required.</p>\n\n<p>This is my code for doing a mapping:</p>\n\n<pre><code>procedure TMyReader.InitialiseMapping(szFilename : string);\nvar\n// nError : DWORD;\n bGood : boolean;\nbegin\n bGood := False;\n m_hFile := CreateFile(PChar(szFilename), GENERIC_READ, 0, nil, OPEN_EXISTING, 0, 0);\n if m_hFile <> INVALID_HANDLE_VALUE then\n begin\n m_hMap := CreateFileMapping(m_hFile, nil, PAGE_READONLY, 0, 0, nil);\n if m_hMap <> 0 then\n begin\n m_pMemory := MapViewOfFile(m_hMap, FILE_MAP_READ, 0, 0, 0);\n if m_pMemory <> nil then\n begin\n htlArray := Pointer(Integer(m_pMemory) + m_dwDataPosition);\n bGood := True;\n end\n else\n begin\n// nError := GetLastError;\n end;\n end;\n end;\n if not bGood then\n raise Exception.Create('Unable to map token file into memory');\nend;\n</code></pre>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/287789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30176/"
] |
I have a huge file that I must parse line by line. Speed is of the essence.
Example of a line:
>
>
> ```
> Token-1 Here-is-the-Next-Token Last-Token-on-Line
> ^ ^
> Current Position
> Position after GetToken
>
> ```
>
>
GetToken is called, returning "Here-is-the-Next-Token" and sets the CurrentPosition to the position of the last character of the token so that it is ready for the next call to GetToken. Tokens are separated by one or more spaces.
Assume the file is already in a StringList in memory. It fits in memory easily, say 200 MB.
I am worried only about the execution time for the parsing. What code will produce the absolute fastest execution in Delphi (Pascal)?
|
* Use PChar incrementing for speed of processing
* If some tokens are not needed, only copy token data on demand
* Copy PChar to local variable when actually scanning through characters
* Keep source data in a single buffer unless you must handle line by line, and even then, consider handling line processing as a separate token in the lexer recognizer
* Consider processing a byte array buffer that has come straight from the file, if you definitely know the encoding; if using Delphi 2009, use PAnsiChar instead of PChar, unless of course you know the encoding is UTF16-LE.
* If you know that the only whitespace is going to be #32 (ASCII space), or a similarly limited set of characters, there may be some clever bit manipulation hacks that can let you process 4 bytes at a time using Integer scanning. I wouldn't expect big wins here though, and the code will be as clear as mud.
Here's a sample lexer that should be pretty efficient, but it assumes that all source data is in a single string. Reworking it to handle buffers is moderately tricky due to very long tokens.
```
type
TLexer = class
private
FData: string;
FTokenStart: PChar;
FCurrPos: PChar;
function GetCurrentToken: string;
public
constructor Create(const AData: string);
function GetNextToken: Boolean;
property CurrentToken: string read GetCurrentToken;
end;
{ TLexer }
constructor TLexer.Create(const AData: string);
begin
FData := AData;
FCurrPos := PChar(FData);
end;
function TLexer.GetCurrentToken: string;
begin
SetString(Result, FTokenStart, FCurrPos - FTokenStart);
end;
function TLexer.GetNextToken: Boolean;
var
cp: PChar;
begin
cp := FCurrPos; // copy to local to permit register allocation
// skip whitespace; this test could be converted to an unsigned int
// subtraction and compare for only a single branch
while (cp^ > #0) and (cp^ <= #32) do
Inc(cp);
// using null terminater for end of file
Result := cp^ <> #0;
if Result then
begin
FTokenStart := cp;
Inc(cp);
while cp^ > #32 do
Inc(cp);
end;
FCurrPos := cp;
end;
```
|
287,794 |
<p>How should a relational database be designed to handle multi-valued attributes ?</p>
<p><strong>edit</strong>: To elaborate: </p>
<p>There are two ways I could think of for doing this -</p>
<ol>
<li>Trying something like putting comma separated values in the field, which appears a bit clumsy.</li>
<li>Create another table for the field and let the multiple values go to the field. This might lead to very large number of tables, if I have too many fields of this kind.</li>
</ol>
<p>The question is:</p>
<ol>
<li>Are there any more ways of handling this?</li>
<li>Which of the above two methods is generally used?</li>
</ol>
<p>Thanks in advance</p>
|
[
{
"answer_id": 287821,
"author": "Glenn",
"author_id": 25191,
"author_profile": "https://Stackoverflow.com/users/25191",
"pm_score": 1,
"selected": false,
"text": "<p>Is the relationship one-to-many or many-to-many? With the one-to-many relationship, I recommend a foreign key in the child table (the many) referencing the parent table (the one). With a many-to-many relationship, then your best bet will most probably be a separate table with foreign keys to both parent and child.</p>\n"
},
{
"answer_id": 287836,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 4,
"selected": false,
"text": "<p>In conventional relational database design, each row & column must store only one value. </p>\n\n<p>Don't store comma-separated lists or anything wacky like that.</p>\n\n<p>For example, say a sports team has seven members. You could do this:</p>\n\n<pre><code>CREATE TABLE team (\n team_id INT PRIMARY KEY,\n team_name VARCHAR(50),\n team_members VARCHAR(200)\n);\nINSERT INTO team VALUES (1,'Dwarfs', 'Sleepy,Dopey,Sneezy,Happy,Grumpy,Doc,Bashful')\n</code></pre>\n\n<p>But it's better to do this:</p>\n\n<pre><code>CREATE TABLE team (\n team_id INT PRIMARY KEY,\n team_name VARCHAR(50),\n);\nINSERT INTO team (team_name) VALUES ('Dwarfs');\n\nCREATE TABLE team_members (\n team_id INT,\n member_name VARCHAR(20),\n FOREIGN KEY (team_id) REFERENCES team(team_id)\n);\nINSERT INTO team_members VALUES \n (LAST_INSERT_ID(), 'Sleepy'),\n (LAST_INSERT_ID(), 'Dopey'),\n (LAST_INSERT_ID(), 'Sneezy'),\n (LAST_INSERT_ID(), 'Happy'),\n (LAST_INSERT_ID(), 'Grumpy'),\n (LAST_INSERT_ID(), 'Doc'),\n (LAST_INSERT_ID(), 'Bashful');\n</code></pre>\n\n<p><strong>nb:</strong> <code>LAST_INSERT_ID()</code> is a MySQL function. Similar solutions are available in other brands of database.</p>\n"
},
{
"answer_id": 287840,
"author": "Robert Walker",
"author_id": 28300,
"author_profile": "https://Stackoverflow.com/users/28300",
"pm_score": 1,
"selected": false,
"text": "<p>Read here <a href=\"http://dev.mysql.com/tech-resources/articles/intro-to-normalization.html\" rel=\"nofollow noreferrer\">http://dev.mysql.com/tech-resources/articles/intro-to-normalization.html</a> about the First (1NF), Second (2NF) and Third (3NF) normal forms of database design. There are more forms above 3NF, but usually 3NF is sufficient.</p>\n"
},
{
"answer_id": 1401556,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>If you are limited to working with a strictly relational database, then you need to store those values as rows in a table. And that was your question - how to do it with a relational database.\nHowever, there are many databases available that provide native storage of multiple values in a field which turns out to be a very good match for much real world data, easy to program with, and simpler to comprehend (without the explosion of tables you get with 3rd normal form).\nFor more info, see <a href=\"http://en.wikipedia.org/wiki/MultiValue\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/MultiValue</a>\n<a href=\"http://en.wikipedia.org/wiki/IBM_U2\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/IBM_U2</a>\n<a href=\"http://en.wikipedia.org/wiki/InterSystems\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/InterSystems</a></p>\n"
},
{
"answer_id": 61395384,
"author": "Tariq Imtinan",
"author_id": 7289093,
"author_profile": "https://Stackoverflow.com/users/7289093",
"pm_score": 1,
"selected": false,
"text": "<p>There are two possible approaches for this -</p>\n\n<ol>\n<li><strong>Relationship</strong> : Storing multiple values for one \nattribute of an entity is done through referenced key-foreign key \nrelationships. For more info, check <a href=\"https://lists.mysql.com/mysql/59610\" rel=\"nofollow noreferrer\">this</a>.</li>\n<li><strong>Set</strong> : A scalar datatype in mysql that can have zero or more values, each of which must be chosen from a list of permitted values specified when the table is created. For more info, please check <a href=\"https://dev.mysql.com/doc/refman/8.0/en/set.html\" rel=\"nofollow noreferrer\">this</a> and <a href=\"https://lists.mysql.com/mysql/59403\" rel=\"nofollow noreferrer\">this</a> link.</li>\n</ol>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/287794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30252/"
] |
How should a relational database be designed to handle multi-valued attributes ?
**edit**: To elaborate:
There are two ways I could think of for doing this -
1. Trying something like putting comma separated values in the field, which appears a bit clumsy.
2. Create another table for the field and let the multiple values go to the field. This might lead to very large number of tables, if I have too many fields of this kind.
The question is:
1. Are there any more ways of handling this?
2. Which of the above two methods is generally used?
Thanks in advance
|
In conventional relational database design, each row & column must store only one value.
Don't store comma-separated lists or anything wacky like that.
For example, say a sports team has seven members. You could do this:
```
CREATE TABLE team (
team_id INT PRIMARY KEY,
team_name VARCHAR(50),
team_members VARCHAR(200)
);
INSERT INTO team VALUES (1,'Dwarfs', 'Sleepy,Dopey,Sneezy,Happy,Grumpy,Doc,Bashful')
```
But it's better to do this:
```
CREATE TABLE team (
team_id INT PRIMARY KEY,
team_name VARCHAR(50),
);
INSERT INTO team (team_name) VALUES ('Dwarfs');
CREATE TABLE team_members (
team_id INT,
member_name VARCHAR(20),
FOREIGN KEY (team_id) REFERENCES team(team_id)
);
INSERT INTO team_members VALUES
(LAST_INSERT_ID(), 'Sleepy'),
(LAST_INSERT_ID(), 'Dopey'),
(LAST_INSERT_ID(), 'Sneezy'),
(LAST_INSERT_ID(), 'Happy'),
(LAST_INSERT_ID(), 'Grumpy'),
(LAST_INSERT_ID(), 'Doc'),
(LAST_INSERT_ID(), 'Bashful');
```
**nb:** `LAST_INSERT_ID()` is a MySQL function. Similar solutions are available in other brands of database.
|
287,832 |
<p>I am creating a form in HTML that will be printed, with fields that need to be written in by the recipient. Basically what I want is a single line that stretches from the end of the field label to the side of the page. Here's how I'm doing it right now:</p>
<pre><code><table width="100%">
<tr>
<td width="1%">
Label:
</td>
<td style="border-bottom-style:solid; border-bottom-width:1px;">
&nbsp;
</td>
</tr>
</table>
</code></pre>
<p>This works, but there must be an easier way to do this without needing a whole table element. Any ideas?</p>
|
[
{
"answer_id": 287838,
"author": "billjamesdev",
"author_id": 13824,
"author_profile": "https://Stackoverflow.com/users/13824",
"pm_score": 2,
"selected": false,
"text": "<p>How about using the span tag?</p>\n\n<pre><code><span style=\"border-bottom....\">Text</span>\n</code></pre>\n"
},
{
"answer_id": 287847,
"author": "Jon Smock",
"author_id": 25538,
"author_profile": "https://Stackoverflow.com/users/25538",
"pm_score": 3,
"selected": false,
"text": "<p>Here's my CSS:</p>\n\n<pre><code>span.print_underline\n{\n display: inline-block;\n height: 1em;\n border-bottom: 1px solid #000;\n}\n</code></pre>\n\n<p>So your HTML will look like:</p>\n\n<pre><code><span class=\"print_underline\" style=\"width: 200px\">&nbsp;</span>\n</code></pre>\n\n<p>I left the width out, so I could reuse it as much as I want, but you can specify the width.</p>\n\n<p>As a sidenote, I tested the same concept with a div tag instead of span tag, and it did not work in some situations. This is probably because it is semantically incorrect to put a div within a paragraph tag (which is why I used a span), and I generally use paragraph tags instead of using table rows like you've used.</p>\n"
},
{
"answer_id": 287859,
"author": "jishi",
"author_id": 33663,
"author_profile": "https://Stackoverflow.com/users/33663",
"pm_score": 2,
"selected": false,
"text": "<p>just have a div with appropriate margin to the left. Block-elements by default always expand to the full width.</p>\n\n<p>Meaning:</p>\n\n<pre>\n\nlabel {\n float: left;\n}\n\ndiv {\n margin-left: 10em;\n border-bottom: 1px solid black;\n height: 1em;\n}\n</pre>\n\n<p><code><label>label:</label></code></p>\n\n<p><code><div></div></code></p>\n\n<p>it won't stretch the full width between the label and the right side, but you can have the label hide the bottom-border (using background-color or something) and have the div expand all the way to the right aswell (without the margin).</p>\n\n<p>If you want correct semantics, you can even use an input instead of a div, set it's display to \"block\" and fix the borders and background.</p>\n"
},
{
"answer_id": 287868,
"author": "mson",
"author_id": 36902,
"author_profile": "https://Stackoverflow.com/users/36902",
"pm_score": 3,
"selected": true,
"text": "<p>I think your solution is better than the responses thus far. The only thing I'd change about your solution is that I'd use a css class instead of inline.</p>\n\n<p>Your solution will have better alignment than using spans. Your code will look cleaner with table elements than with spans as well.</p>\n\n<p>Also, you might want to consider putting in a textbox in your cell so that your users can input the information directly on the page before printing out.</p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/287832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23935/"
] |
I am creating a form in HTML that will be printed, with fields that need to be written in by the recipient. Basically what I want is a single line that stretches from the end of the field label to the side of the page. Here's how I'm doing it right now:
```
<table width="100%">
<tr>
<td width="1%">
Label:
</td>
<td style="border-bottom-style:solid; border-bottom-width:1px;">
</td>
</tr>
</table>
```
This works, but there must be an easier way to do this without needing a whole table element. Any ideas?
|
I think your solution is better than the responses thus far. The only thing I'd change about your solution is that I'd use a css class instead of inline.
Your solution will have better alignment than using spans. Your code will look cleaner with table elements than with spans as well.
Also, you might want to consider putting in a textbox in your cell so that your users can input the information directly on the page before printing out.
|
287,839 |
<p>[former title: Is there a way to force a relationship structure on a tag-based organizational methodology?]</p>
<p>I have some entities, and they have a series of attributes. Some of the attributes affect what other attributes the entity can have, many of the attributes are organized into groups, and occasionally entities are requited to have certain numbers of attributes from certain groups, or possibly a range of attributes from certain groups.</p>
<p>Is there a way to model these sorts of tag-to-tag relationships, such as requirement, grouping, exclusion, etc. using a database, or is this only possible with programmed "business rules"? Ideally, I would like the possible tags and their relationships to be easily configurable, and hence highly flexible.</p>
<p>One of the ways I have considered is to have the tags and possible relationships, and then you get a tag-tag-applied relationship sort of table, but this seems like a rather brittle approach.</p>
<p>So, is this possible in a more rigorous fashion, and if so, how would I even begin to go about it?</p>
|
[
{
"answer_id": 287977,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 3,
"selected": true,
"text": "<p><strong>edit</strong>: Your description of variable attributes that apply only depending on the values in other attributes is a non-relational, non-normalized design. RDBMS may not be the best solution for storing this kind of data. Probably RDF would be a good solution for data that requires this level of flexibility.</p>\n\n<p>My earlier answer, pertaining to RDBMS solutions, is below:</p>\n\n<hr>\n\n<p>Some people model flexible attributes with the <a href=\"http://en.wikipedia.org/wiki/Entity-attribute-value_model\" rel=\"nofollow noreferrer\">Entity-Attribute-Value</a> design, but this is often too unstructured and you end up fighting with data integrity problems. Use this only if you need a virtually limitless number of entity sub-types.</p>\n\n<p>Other people use <a href=\"http://en.wikipedia.org/wiki/Single_Table_Inheritance\" rel=\"nofollow noreferrer\">Single Table Inheritance</a>, where you put all attribute columns used by all sub-types into one very wide table, and leave them NULL on rows where the attribute is irrelevant to the sub-type. But this has limits because the table can grow too wide, and you lose the ability to make any attributes mandatory, because they must all be nullable.</p>\n\n<p>If you have a relatively small number of entity sub-types, I would recommend creating a dependent table for each group of required attributes. Define the dependent table's primary key as a foreign key to the parent table, so you get a one-to-one relationship.</p>\n\n<pre><code>CREATE TABLE Vehicles (\n vehicle_id INT PRIMARY KEY\n ...attributes common to all vehicles...\n);\n\nCREATE TABLE Automobiles (\n vehicle_id INT PRIMARY KEY,\n ...attributes specific to autos...\n FOREIGN KEY (vehicle_id) REFERENCES Vehicles(vehicle_id)\n);\n</code></pre>\n\n<p>You can also provide a little more data integrity by encoding the subtype in the primary key of the parent table. That's to make sure a row in <code>Automobiles</code> cannot reference a motorcycle in <code>Vehicles</code>.</p>\n\n<pre><code>CREATE TABLE Vehicles (\n vehicle_id INT,\n vehicle_type VARCHAR(10),\n ...attributes common to all vehicles...\n PRIMARY KEY (vehicle_id, vehicle_type),\n FOREIGN KEY (vehicle_type) REFERENCES VehicleTypes (vehicle_type)\n);\n\nCREATE TABLE Automobiles (\n vehicle_id INT,\n vehicle_type VARCHAR(10) CHECK (vehicle_type = 'Automobile'),\n ...attributes specific to autos...\n FOREIGN KEY (vehicle_id, vehicle_type) \n REFERENCES Vehicles(vehicle_id, vehicle_type)\n);\n</code></pre>\n\n<p>Of course, you need to create a new dependent table each time you define a new sub-type, but this design does give you a lot more structure to enforce data integrity, NOT NULL attributes, and so on. </p>\n\n<p>The only part you need to enforce in application logic is that to make sure to create a row in <code>Automobiles</code> for each row in <code>Vehicles</code> with <code>vehicle_type</code> = 'Automobile'.</p>\n"
},
{
"answer_id": 464252,
"author": "jennykwan",
"author_id": 45051,
"author_profile": "https://Stackoverflow.com/users/45051",
"pm_score": 2,
"selected": false,
"text": "<p>There's no difference between using databases to enforce your rules or using source code elsewhere. Code is data. That's the esoteric Lisp answer.</p>\n\n<p>The real question you're asking is whether this is easier in a relational database or in (I assume) an Algol family language. You didn't specify a RDBMS, so I'm going to assume ANSI. That makes this hard.</p>\n\n<p>BTW, this is easy in Prolog. But that's neither here nor there.</p>\n\n<p>I would say to use check constraints for everything. The mental shift needed for this approach is to realize that your UI will need a way to define these tag relationships. Traditionally, you would issue CRUD statements from the UI to the DB. Instead, you need to issue ALTER TABLE statements to CRUD check constraints.</p>\n\n<p>There are two problems with this approach:</p>\n\n<ul>\n<li>Such statements are not parameterizable in most RDBMS's. Think SQL injection.</li>\n<li>Implementations vary in their support for full ANSI check constraints. If subqueries aren't supported, forget it.</li>\n</ul>\n\n<p>If you could clarify your question with a specific RDBMS, then we can give you a better answer.</p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/287839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20770/"
] |
[former title: Is there a way to force a relationship structure on a tag-based organizational methodology?]
I have some entities, and they have a series of attributes. Some of the attributes affect what other attributes the entity can have, many of the attributes are organized into groups, and occasionally entities are requited to have certain numbers of attributes from certain groups, or possibly a range of attributes from certain groups.
Is there a way to model these sorts of tag-to-tag relationships, such as requirement, grouping, exclusion, etc. using a database, or is this only possible with programmed "business rules"? Ideally, I would like the possible tags and their relationships to be easily configurable, and hence highly flexible.
One of the ways I have considered is to have the tags and possible relationships, and then you get a tag-tag-applied relationship sort of table, but this seems like a rather brittle approach.
So, is this possible in a more rigorous fashion, and if so, how would I even begin to go about it?
|
**edit**: Your description of variable attributes that apply only depending on the values in other attributes is a non-relational, non-normalized design. RDBMS may not be the best solution for storing this kind of data. Probably RDF would be a good solution for data that requires this level of flexibility.
My earlier answer, pertaining to RDBMS solutions, is below:
---
Some people model flexible attributes with the [Entity-Attribute-Value](http://en.wikipedia.org/wiki/Entity-attribute-value_model) design, but this is often too unstructured and you end up fighting with data integrity problems. Use this only if you need a virtually limitless number of entity sub-types.
Other people use [Single Table Inheritance](http://en.wikipedia.org/wiki/Single_Table_Inheritance), where you put all attribute columns used by all sub-types into one very wide table, and leave them NULL on rows where the attribute is irrelevant to the sub-type. But this has limits because the table can grow too wide, and you lose the ability to make any attributes mandatory, because they must all be nullable.
If you have a relatively small number of entity sub-types, I would recommend creating a dependent table for each group of required attributes. Define the dependent table's primary key as a foreign key to the parent table, so you get a one-to-one relationship.
```
CREATE TABLE Vehicles (
vehicle_id INT PRIMARY KEY
...attributes common to all vehicles...
);
CREATE TABLE Automobiles (
vehicle_id INT PRIMARY KEY,
...attributes specific to autos...
FOREIGN KEY (vehicle_id) REFERENCES Vehicles(vehicle_id)
);
```
You can also provide a little more data integrity by encoding the subtype in the primary key of the parent table. That's to make sure a row in `Automobiles` cannot reference a motorcycle in `Vehicles`.
```
CREATE TABLE Vehicles (
vehicle_id INT,
vehicle_type VARCHAR(10),
...attributes common to all vehicles...
PRIMARY KEY (vehicle_id, vehicle_type),
FOREIGN KEY (vehicle_type) REFERENCES VehicleTypes (vehicle_type)
);
CREATE TABLE Automobiles (
vehicle_id INT,
vehicle_type VARCHAR(10) CHECK (vehicle_type = 'Automobile'),
...attributes specific to autos...
FOREIGN KEY (vehicle_id, vehicle_type)
REFERENCES Vehicles(vehicle_id, vehicle_type)
);
```
Of course, you need to create a new dependent table each time you define a new sub-type, but this design does give you a lot more structure to enforce data integrity, NOT NULL attributes, and so on.
The only part you need to enforce in application logic is that to make sure to create a row in `Automobiles` for each row in `Vehicles` with `vehicle_type` = 'Automobile'.
|
287,845 |
<p>I have a fair number of Python scripts that contain reusable code that are used and referenced by other Python scripts. However, these scripts tend to be scattered across different directories and I find it to be somewhat tedious to have to include (most often multiple) calls to sys.path.append on my top-level scripts. I just want to provide the 'import' statements without the additional file references in the same script.</p>
<p>Currently, I have this:</p>
<pre><code>import sys
sys.path.append('..//shared1//reusable_foo')
import Foo
sys.path.append('..//shared2//reusable_bar')
import Bar
</code></pre>
<p>My preference would be the following:</p>
<pre><code>import Foo
import Bar
</code></pre>
<p>My background is primarily in the .NET platform so I am accustomed to having meta files such as *.csproj, *.vbproj, *.sln, etc. to manage and contain the actual file path references outside of the source files. This allows me to just provide 'using' directives (equivalent to Python's import) without exposing all of the references and allowing for reuse of the path references themselves across multiple scripts.</p>
<p>Does Python have equivalent support for this and, if not, what are some techniques and approaches?</p>
|
[
{
"answer_id": 287884,
"author": "bouvard",
"author_id": 24608,
"author_profile": "https://Stackoverflow.com/users/24608",
"pm_score": 2,
"selected": false,
"text": "<p>If your reusable files are packaged (that is, they include an <code>__init__.py</code> file) and the path to that package is part of your PYTHONPATH or sys.path then you should be able to do just</p>\n\n<pre><code>import Foo\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/279237/python-import-a-module-from-a-folder#279287\">This question</a> provides a few more details.</p>\n\n<p>(Note: As Jim said, you could also drop your reusable code into your <code>site-packages</code> directory.)</p>\n"
},
{
"answer_id": 287886,
"author": "JimB",
"author_id": 32880,
"author_profile": "https://Stackoverflow.com/users/32880",
"pm_score": 3,
"selected": true,
"text": "<p>The simple answer is to put your reusable code in your site-packages directory, which is in your sys.path.</p>\n\n<p>You can also extend the search path by adding .pth files somewhere in your path.\nSee <a href=\"https://docs.python.org/2/install/#modifying-python-s-search-path\" rel=\"nofollow noreferrer\">https://docs.python.org/2/install/#modifying-python-s-search-path</a> for more details</p>\n\n<p>Oh, and python 2.6/3.0 adds support for PEP370, <a href=\"http://docs.python.org/whatsnew/2.6.html#pep-370-per-user-site-packages-directory\" rel=\"nofollow noreferrer\">Per-user site-packages Directory</a></p>\n"
},
{
"answer_id": 288123,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 1,
"selected": false,
"text": "<p>You can put the reusable stuff in <code>site-packages</code>. That's completely transparent, since it's in <code>sys.path</code> by default.</p>\n\n<p>You can put <code>someName.pth</code> files in <code>site-packages</code>. These files have the directory in which your actual reusable stuff lives. This is also completely transparent. And doesn't involve the extra step of installing a change in <code>site-packages</code>.</p>\n\n<p>You can put the directory of the reusable stuff on <code>PYTHONPATH</code>. That's a little less transparent, because you have to make sure it's set. Not rocket science, but not completely transparent.</p>\n"
},
{
"answer_id": 288174,
"author": "Jason Baker",
"author_id": 2147,
"author_profile": "https://Stackoverflow.com/users/2147",
"pm_score": 1,
"selected": false,
"text": "<p>In one project, I wanted to make sure that the user could put python scripts (that could basically be used as plugins) anywhere. My solution was to put the following in the config file for that project:</p>\n\n<pre><code>[server]\nPYPATH_APPEND: /home/jason:/usr/share/some_directory\n</code></pre>\n\n<p>That way, this would add /home/jason and /usr/share/some_directory to the python path at program launch.</p>\n\n<p>Then, it's just a simple matter of splitting the string by the colons and adding those directories to the end of the sys.path. You may want to consider putting a module in the site-packages directory that contains a function to read in that config file and add those directories to the sys.path (unfortunately, I don't have time at the moment to write an example).</p>\n\n<p>As others have mentioned, it's a good idea to put as much in site-packages as possible and also using .pth files. But this can be a good idea if you have a script that needs to import a bunch of stuff that's not in site-packages that you wouldn't want to import from other scripts.</p>\n\n<p>(there may also be a way to do this using .pth files, but I like being able to manipulate the python path in the same place as I put the rest of my configuration info)</p>\n"
},
{
"answer_id": 288908,
"author": "Jeremy Cantrell",
"author_id": 18866,
"author_profile": "https://Stackoverflow.com/users/18866",
"pm_score": 1,
"selected": false,
"text": "<p>The simplest way is to set (or add to) PYTHONPATH, and put (or symlink) your modules and packages into a path contained in PYTHONPATH.</p>\n"
},
{
"answer_id": 288944,
"author": "humble_guru",
"author_id": 23961,
"author_profile": "https://Stackoverflow.com/users/23961",
"pm_score": 0,
"selected": false,
"text": "<p>My solution was to package up one utility that would import the module:\nmy_util is in site packages</p>\n\n<pre><code>import my_util\n\nfoo = myutil.import_script('..//shared1//reusable_foo')\nif foo == None:\n sys.exit(1)\n\n\ndef import_script(script_path, log_status = True):\n \"\"\"\n imports a module and returns the handle\n \"\"\"\n lpath = os.path.split(script_path)\n\n if lpath[1] == '':\n log('Error in script \"%s\" in import_script' % (script_path))\n return None\n\n\n #check if path is already in sys.path so we don't repeat\n npath = None\n if lpath[0] == '':\n npath = '.'\n else:\n if lpath[0] not in sys.path:\n npath = lpath[0]\n\n if npath != None:\n try:\n sys.path.append(npath)\n except:\n if log_status == True:\n log('Error adding path \"%s\" in import_script' % npath)\n return None\n\n try: \n mod = __import__(lpath[1])\n except:\n error_trace,error_reason = FormatExceptionInfo()\n if log_status == True:\n log('Error importing \"%s\" module in import_script: %s' % (script_path, error_trace + error_reason))\n sys.path.remove(npath)\n return None\n\n return mod\n</code></pre>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/287845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
] |
I have a fair number of Python scripts that contain reusable code that are used and referenced by other Python scripts. However, these scripts tend to be scattered across different directories and I find it to be somewhat tedious to have to include (most often multiple) calls to sys.path.append on my top-level scripts. I just want to provide the 'import' statements without the additional file references in the same script.
Currently, I have this:
```
import sys
sys.path.append('..//shared1//reusable_foo')
import Foo
sys.path.append('..//shared2//reusable_bar')
import Bar
```
My preference would be the following:
```
import Foo
import Bar
```
My background is primarily in the .NET platform so I am accustomed to having meta files such as \*.csproj, \*.vbproj, \*.sln, etc. to manage and contain the actual file path references outside of the source files. This allows me to just provide 'using' directives (equivalent to Python's import) without exposing all of the references and allowing for reuse of the path references themselves across multiple scripts.
Does Python have equivalent support for this and, if not, what are some techniques and approaches?
|
The simple answer is to put your reusable code in your site-packages directory, which is in your sys.path.
You can also extend the search path by adding .pth files somewhere in your path.
See <https://docs.python.org/2/install/#modifying-python-s-search-path> for more details
Oh, and python 2.6/3.0 adds support for PEP370, [Per-user site-packages Directory](http://docs.python.org/whatsnew/2.6.html#pep-370-per-user-site-packages-directory)
|
287,849 |
<p>I'm trying to replace the programs that run from my startup directory with a batch script. The batch script will simply warn me that the programs are going to run and I can either continue running the script or stop it. </p>
<p>Here's the script as I have written so far:</p>
<pre><code>@echo off
echo You are about to run startup programs!
pause
::load outlook
cmd /k "C:\Program Files\Microsoft Office\Office12\OUTLOOK.EXE" /recycle
::load Visual Studio 2008
call "C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\devenv.exe"
</code></pre>
<p>Both of these commands will load the first program and wait until I close it to load the second. I want the script to load the processes simultaneously. How do I accomplish this?</p>
<p>Edit: When I use the start command it opens up a new shell with the string that I typed in as the title. The edited script looks like this:</p>
<pre><code>start "C:\Program Files\Microsoft Office\Office12\OUTLOOK.EXE"
::load Visual Studio 2008
start "C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\devenv.exe"
</code></pre>
|
[
{
"answer_id": 287866,
"author": "Carl Seleborg",
"author_id": 2095,
"author_profile": "https://Stackoverflow.com/users/2095",
"pm_score": 2,
"selected": false,
"text": "<p>There is the <code>start</code> command that will behave much like if you clicked the files in Explorer.</p>\n"
},
{
"answer_id": 287914,
"author": "RΓ΄mulo Ceccon",
"author_id": 23193,
"author_profile": "https://Stackoverflow.com/users/23193",
"pm_score": 4,
"selected": true,
"text": "<p>This works:</p>\n\n<pre>\n@echo off\necho You are about to run startup programs!\npause \n\n::load outlook\nstart /b \"\" \"C:\\Program Files\\Microsoft Office\\Office12\\OUTLOOK.EXE\" /recycle\n::load Visual Studio 2008\nstart /b \"\" \"C:\\Program Files\\Microsoft Visual Studio 9.0\\Common7\\IDE\\devenv.exe\"\n</pre>\n"
},
{
"answer_id": 287943,
"author": "aphoria",
"author_id": 2441,
"author_profile": "https://Stackoverflow.com/users/2441",
"pm_score": 2,
"selected": false,
"text": "<p>Use START like this:</p>\n\n<pre><code>START \"\" \"C:\\Program Files\\Microsoft Office\\Office12\\OUTLOOK.EXE\"\n</code></pre>\n\n<p>When your path is enclosed in quotes, START interprets it as the title for the window. Adding the \"\" makes it see your path as the program to run.</p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/287849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2916/"
] |
I'm trying to replace the programs that run from my startup directory with a batch script. The batch script will simply warn me that the programs are going to run and I can either continue running the script or stop it.
Here's the script as I have written so far:
```
@echo off
echo You are about to run startup programs!
pause
::load outlook
cmd /k "C:\Program Files\Microsoft Office\Office12\OUTLOOK.EXE" /recycle
::load Visual Studio 2008
call "C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\devenv.exe"
```
Both of these commands will load the first program and wait until I close it to load the second. I want the script to load the processes simultaneously. How do I accomplish this?
Edit: When I use the start command it opens up a new shell with the string that I typed in as the title. The edited script looks like this:
```
start "C:\Program Files\Microsoft Office\Office12\OUTLOOK.EXE"
::load Visual Studio 2008
start "C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\devenv.exe"
```
|
This works:
```
@echo off
echo You are about to run startup programs!
pause
::load outlook
start /b "" "C:\Program Files\Microsoft Office\Office12\OUTLOOK.EXE" /recycle
::load Visual Studio 2008
start /b "" "C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\devenv.exe"
```
|
287,871 |
<p>How do I output colored text to the terminal in Python?</p>
|
[
{
"answer_id": 287896,
"author": "UberJumper",
"author_id": 34395,
"author_profile": "https://Stackoverflow.com/users/34395",
"pm_score": 5,
"selected": false,
"text": "<p>For Windows you cannot print to console with colors unless you're using the <a href=\"https://en.wikipedia.org/wiki/Windows_API\" rel=\"noreferrer\">Win32</a> API.</p>\n<p>For Linux it's as simple as using print, with the escape sequences outlined here:</p>\n<p><a href=\"http://www.linuxhowtos.org/Tips%20and%20Tricks/ansi_escape_sequences.htm\" rel=\"noreferrer\">Colors</a></p>\n<p>For the character to print like a box, it really depends on what font you are using for the console window. The pound symbol works well, but it depends on the font:</p>\n<pre><code>#\n</code></pre>\n"
},
{
"answer_id": 287919,
"author": "daharon",
"author_id": 23597,
"author_profile": "https://Stackoverflow.com/users/23597",
"pm_score": 4,
"selected": false,
"text": "<p>You can use the Python implementation of the <a href=\"https://en.wikipedia.org/wiki/Curses_%28programming_library%29\" rel=\"nofollow noreferrer\">curses</a> library:\n<em><a href=\"http://docs.python.org/library/curses.html\" rel=\"nofollow noreferrer\">curses β Terminal handling for character-cell displays</a></em></p>\n<p>Also, run this and you'll find your box:</p>\n<pre><code>for i in range(255):\n print i, chr(i)\n</code></pre>\n"
},
{
"answer_id": 287934,
"author": "Bryan Oakley",
"author_id": 7432,
"author_profile": "https://Stackoverflow.com/users/7432",
"pm_score": 7,
"selected": false,
"text": "<p>You want to learn about ANSI escape sequences. Here's a brief example:</p>\n<pre><code>CSI = "\\x1B["\nprint(CSI+"31;40m" + "Colored Text" + CSI + "0m")\n</code></pre>\n<p>For more information, see <em><a href=\"http://en.wikipedia.org/wiki/ANSI_escape_code\" rel=\"noreferrer\">ANSI escape code</a></em>.</p>\n<p>For a block character, try a Unicode character like \\u2588:</p>\n<pre><code>print(u"\\u2588")\n</code></pre>\n<p>Putting it all together:</p>\n<pre><code>print(CSI+"31;40m" + u"\\u2588" + CSI + "0m")\n</code></pre>\n"
},
{
"answer_id": 287944,
"author": "joeld",
"author_id": 19104,
"author_profile": "https://Stackoverflow.com/users/19104",
"pm_score": 11,
"selected": false,
"text": "<p>This somewhat depends on what platform you are on. The most common way to do this is by printing ANSI escape sequences. For a simple example, here's some Python code from the <a href=\"https://svn.blender.org/svnroot/bf-blender/trunk/blender/build_files/scons/tools/bcolors.py\" rel=\"noreferrer\">Blender build scripts</a>:</p>\n<pre><code>class bcolors:\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKCYAN = '\\033[96m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n</code></pre>\n<p>To use code like this, you can do something like:</p>\n<pre><code>print(bcolors.WARNING + "Warning: No active frommets remain. Continue?" + bcolors.ENDC)\n</code></pre>\n<p>Or, with Python 3.6+:</p>\n<pre><code>print(f"{bcolors.WARNING}Warning: No active frommets remain. Continue?{bcolors.ENDC}")\n</code></pre>\n<p>This will work on unixes including OS X, Linux and Windows (provided you use <a href=\"https://github.com/adoxa/ansicon\" rel=\"noreferrer\">ANSICON</a>, or in Windows 10 provided you enable <a href=\"https://msdn.microsoft.com/en-us/library/mt638032\" rel=\"noreferrer\">VT100 emulation</a>). There are ANSI codes for setting the color, moving the cursor, and more.</p>\n<p>If you are going to get complicated with this (and it sounds like you are if you are writing a game), you should look into the "<a href=\"https://en.wikipedia.org/wiki/Curses_%28programming_library%29\" rel=\"noreferrer\">curses</a>" module, which handles a lot of the complicated parts of this for you. The <a href=\"http://docs.python.org/howto/curses.html\" rel=\"noreferrer\" title=\"Python Curses howto\">Python Curses HowTO</a> is a good introduction.</p>\n<p>If you are not using extended ASCII (i.e., not on a PC), you are stuck with the ASCII characters below 127, and '#' or '@' is probably your best bet for a block. If you can ensure your terminal is using a IBM <a href=\"http://telecom.tbi.net/asc-ibm.html\" rel=\"noreferrer\">extended ASCII character set</a>, you have many more options. Characters 176, 177, 178 and 219 are the "block characters".</p>\n<p>Some modern text-based programs, such as "Dwarf Fortress", emulate text mode in a graphical mode, and use images of the classic PC font. You can find some of these bitmaps that you can use on the <a href=\"http://dwarffortresswiki.org/DF2014:Tilesets\" rel=\"noreferrer\">Dwarf Fortress Wiki</a> see (<a href=\"http://dwarffortresswiki.org/Tileset_repository\" rel=\"noreferrer\">user-made tilesets</a>).</p>\n<p>The <a href=\"http://en.wikipedia.org/wiki/TMDC\" rel=\"noreferrer\" title=\"text mode demo contest\">Text Mode Demo Contest</a> has more resources for doing graphics in text mode.</p>\n"
},
{
"answer_id": 287987,
"author": "suhib-alsisan",
"author_id": 37437,
"author_profile": "https://Stackoverflow.com/users/37437",
"pm_score": 4,
"selected": false,
"text": "<p>If you are programming a game perhaps you would like to change the background color and use only spaces? For example:</p>\n\n<pre><code>print \" \"+ \"\\033[01;41m\" + \" \" +\"\\033[01;46m\" + \" \" + \"\\033[01;42m\"\n</code></pre>\n"
},
{
"answer_id": 288030,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 3,
"selected": false,
"text": "<h2>For the characters</h2>\n\n<p>Your terminal most probably uses Unicode (typically UTF-8 encoded) characters, so it's only a matter of the appropriate font selection to see your favorite character. Unicode char U+2588, \"Full block\" is the one I would suggest you use.</p>\n\n<p>Try the following:</p>\n\n<pre><code>import unicodedata\nfp= open(\"character_list\", \"w\")\nfor index in xrange(65536):\n char= unichr(index)\n try: its_name= unicodedata.name(char)\n except ValueError: its_name= \"N/A\"\n fp.write(\"%05d %04x %s %s\\n\" % (index, index, char.encode(\"UTF-8\"), its_name)\nfp.close()\n</code></pre>\n\n<p>Examine the file later with your favourite viewer.</p>\n\n<h2>For the colors</h2>\n\n<p><a href=\"http://www.python.org/doc/2.5.2/lib/module-curses.html\" rel=\"noreferrer\">curses</a> is the module you want to use. Check this <a href=\"http://docs.python.org/howto/curses.html\" rel=\"noreferrer\">tutorial</a>.</p>\n"
},
{
"answer_id": 288556,
"author": "orip",
"author_id": 37020,
"author_profile": "https://Stackoverflow.com/users/37020",
"pm_score": 5,
"selected": false,
"text": "<p>On Windows you can use module 'win32console' (available in some Python distributions) or module 'ctypes' (Python 2.5 and up) to access the Win32 API.</p>\n\n<p>To see complete code that supports both ways, see the <a href=\"https://github.com/testoob/testoob/blob/master/src/testoob/reporting/colored.py\" rel=\"noreferrer\">color console reporting code</a> from <a href=\"https://github.com/testoob/testoob\" rel=\"noreferrer\">Testoob</a>.</p>\n\n<p>ctypes example:</p>\n\n<pre><code>import ctypes\n\n# Constants from the Windows API\nSTD_OUTPUT_HANDLE = -11\nFOREGROUND_RED = 0x0004 # text color contains red.\n\ndef get_csbi_attributes(handle):\n # Based on IPython's winconsole.py, written by Alexander Belchenko\n import struct\n csbi = ctypes.create_string_buffer(22)\n res = ctypes.windll.kernel32.GetConsoleScreenBufferInfo(handle, csbi)\n assert res\n\n (bufx, bufy, curx, cury, wattr,\n left, top, right, bottom, maxx, maxy) = struct.unpack(\"hhhhHhhhhhh\", csbi.raw)\n return wattr\n\n\nhandle = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)\nreset = get_csbi_attributes(handle)\n\nctypes.windll.kernel32.SetConsoleTextAttribute(handle, FOREGROUND_RED)\nprint \"Cherry on top\"\nctypes.windll.kernel32.SetConsoleTextAttribute(handle, reset)\n</code></pre>\n"
},
{
"answer_id": 293633,
"author": "Samat Jain",
"author_id": 14878,
"author_profile": "https://Stackoverflow.com/users/14878",
"pm_score": 10,
"selected": false,
"text": "<p>There is also the <a href=\"http://pypi.python.org/pypi/termcolor\" rel=\"noreferrer\">Python termcolor module</a>. Usage is pretty simple:</p>\n<pre><code>from termcolor import colored\n\nprint colored('hello', 'red'), colored('world', 'green')\n</code></pre>\n<p>Or in Python 3:</p>\n<pre><code>print(colored('hello', 'red'), colored('world', 'green'))\n</code></pre>\n<p>It may not be sophisticated enough, however, for game programming and the "colored blocks" that you want to do...</p>\n<p>To get the ANSI codes working on windows, first run</p>\n<pre><code>os.system('color')\n</code></pre>\n"
},
{
"answer_id": 1073959,
"author": "nosklo",
"author_id": 17160,
"author_profile": "https://Stackoverflow.com/users/17160",
"pm_score": 3,
"selected": false,
"text": "<p>Here's a <a href=\"https://en.wikipedia.org/wiki/Curses_%28programming_library%29\" rel=\"nofollow noreferrer\">curses</a> example:</p>\n<pre><code>import curses\n\ndef main(stdscr):\n stdscr.clear()\n if curses.has_colors():\n for i in xrange(1, curses.COLORS):\n curses.init_pair(i, i, curses.COLOR_BLACK)\n stdscr.addstr("COLOR %d! " % i, curses.color_pair(i))\n stdscr.addstr("BOLD! ", curses.color_pair(i) | curses.A_BOLD)\n stdscr.addstr("STANDOUT! ", curses.color_pair(i) | curses.A_STANDOUT)\n stdscr.addstr("UNDERLINE! ", curses.color_pair(i) | curses.A_UNDERLINE)\n stdscr.addstr("BLINK! ", curses.color_pair(i) | curses.A_BLINK)\n stdscr.addstr("DIM! ", curses.color_pair(i) | curses.A_DIM)\n stdscr.addstr("REVERSE! ", curses.color_pair(i) | curses.A_REVERSE)\n stdscr.refresh()\n stdscr.getch()\n\nif __name__ == '__main__':\n print "init..."\n curses.wrapper(main)\n</code></pre>\n"
},
{
"answer_id": 3332860,
"author": "priestc",
"author_id": 118495,
"author_profile": "https://Stackoverflow.com/users/118495",
"pm_score": 10,
"selected": false,
"text": "<p>The answer is <a href=\"https://pypi.python.org/pypi/colorama\" rel=\"noreferrer\">Colorama</a> for all cross-platform coloring in Python.</p>\n<p>It supports Python 3.5+ as well as Python 2.7.</p>\n<p>And as of January 2021 it is maintained.</p>\n<p>Example Code:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from colorama import Fore\nfrom colorama import Style\n\nprint(f"This is {Fore.GREEN}color{Style.RESET_ALL}!")\n</code></pre>\n<p>Example Screenshot:\n<a href=\"https://i.stack.imgur.com/q3D4W.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/q3D4W.png\" alt=\"example screenshot\" /></a></p>\n"
},
{
"answer_id": 7839185,
"author": "nmenezes",
"author_id": 608126,
"author_profile": "https://Stackoverflow.com/users/608126",
"pm_score": 2,
"selected": false,
"text": "<p>I wrote a simple module, available at:\n<a href=\"http://pypi.python.org/pypi/colorconsole\" rel=\"nofollow\">http://pypi.python.org/pypi/colorconsole</a></p>\n\n<p>It works with Windows, Mac OS X and Linux.\nIt uses ANSI for Linux and Mac, but native calls to console functions on Windows.\nYou have colors, cursor positioning and keyboard input. It is not a replacement for curses, but can be very useful if you need to use in simple scripts or ASCII games.</p>\n"
},
{
"answer_id": 8548994,
"author": "Erik Rose",
"author_id": 171721,
"author_profile": "https://Stackoverflow.com/users/171721",
"pm_score": 6,
"selected": false,
"text": "<p>My favorite way is with the <a href=\"http://pypi.python.org/pypi/blessings/\">Blessings</a> library (full disclosure: I wrote it). For example:</p>\n\n<pre><code>from blessings import Terminal\n\nt = Terminal()\nprint t.red('This is red.')\nprint t.bold_bright_red_on_black('Bright red on black')\n</code></pre>\n\n<p>To print colored bricks, the most reliable way is to print spaces with background colors. I use this technique to draw the progress bar in <a href=\"http://pypi.python.org/pypi/nose-progressive/\">nose-progressive</a>:</p>\n\n<pre><code>print t.on_green(' ')\n</code></pre>\n\n<p>You can print in specific locations as well:</p>\n\n<pre><code>with t.location(0, 5):\n print t.on_yellow(' ')\n</code></pre>\n\n<p>If you have to muck with other terminal capabilities in the course of your game, you can do that as well. You can use Python's standard string formatting to keep it readable:</p>\n\n<pre><code>print '{t.clear_eol}You just cleared a {t.bold}whole{t.normal} line!'.format(t=t)\n</code></pre>\n\n<p>The nice thing about Blessings is that it does its best to work on all sorts of terminals, not just the (overwhelmingly common) ANSI-color ones. It also keeps unreadable escape sequences out of your code while remaining concise to use. Have fun!</p>\n"
},
{
"answer_id": 8774709,
"author": "Giacomo Lacava",
"author_id": 1129851,
"author_profile": "https://Stackoverflow.com/users/1129851",
"pm_score": 4,
"selected": false,
"text": "<p>You could use <a href=\"https://github.com/kennethreitz/clint\" rel=\"nofollow noreferrer\">Clint</a>:</p>\n<pre><code>from clint.textui import colored\nprint colored.red('some warning message')\nprint colored.green('nicely done!')\n</code></pre>\n"
},
{
"answer_id": 11178541,
"author": "Brian M. Hunt",
"author_id": 19212,
"author_profile": "https://Stackoverflow.com/users/19212",
"pm_score": 2,
"selected": false,
"text": "<p>To address this problem I created a mind-numbingly simple package to print strings with interpolated color codes, called <a href=\"https://github.com/brianmhunt/icolor\" rel=\"nofollow\">icolor</a>.</p>\n\n<p>icolor includes two functions: <code>cformat</code> and <code>cprint</code>, each of which takes a string with substrings that are interpolated to map to ANSI escape sequences e.g.</p>\n\n<pre><code>from icolor import cformat # there is also cprint\n\ncformat(\"This is #RED;a red string, partially with a #xBLUE;blue background\")\n'This is \\x1b[31ma red string, partially with a \\x1b[44mblue background\\x1b[0m'\n</code></pre>\n\n<p>All the ANSI colors are included (e.g. <code>#RED;</code>, <code>#BLUE;</code>, etc.), as well as <code>#RESET;</code>, <code>#BOLD;</code> and others.</p>\n\n<p>Background colors have an <code>x</code> prefix, so a green background would be <code>#xGREEN;</code>.</p>\n\n<p>One can escape <code>#</code> with <code>##</code>.</p>\n\n<p>Given its simplicity, the best documentation is probably <a href=\"https://github.com/brianmhunt/icolor/blob/master/icolor.py\" rel=\"nofollow\">the code itself</a>.</p>\n\n<p>It is <a href=\"http://pypi.python.org/pypi/icolor/1.0\" rel=\"nofollow\">on PYPI</a>, so one can <code>sudo easy_install icolor</code>.</p>\n"
},
{
"answer_id": 11193790,
"author": "Navweb",
"author_id": 1422157,
"author_profile": "https://Stackoverflow.com/users/1422157",
"pm_score": 4,
"selected": false,
"text": "<p>If you are using Windows, then here you go!</p>\n<pre><code># Display text on a Windows console\n# Windows XP with Python 2.7 or Python&nbsp;3.2\nfrom ctypes import windll\n\n# Needed for Python2/Python3 diff\ntry:\n input = raw_input\nexcept:\n pass\nSTD_OUTPUT_HANDLE = -11\nstdout_handle = windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)\n# Look at the output and select the color you want.\n# For instance, hex E is yellow on black.\n# Hex 1E is yellow on blue.\n# Hex 2E is yellow on green and so on.\nfor color in range(0, 75):\n windll.kernel32.SetConsoleTextAttribute(stdout_handle, color)\n print("%X --> %s" % (color, "Have a fine day!"))\n input("Press Enter to go on ... ")\n</code></pre>\n"
},
{
"answer_id": 11278750,
"author": "Janus Troelsen",
"author_id": 309483,
"author_profile": "https://Stackoverflow.com/users/309483",
"pm_score": 5,
"selected": false,
"text": "<p>Note how well the <code>with</code> keyword mixes with modifiers like these that need to be reset (using Python 3 and Colorama):</p>\n<pre><code>from colorama import Fore, Style\nimport sys\n\nclass Highlight:\n def __init__(self, clazz, color):\n self.color = color\n self.clazz = clazz\n def __enter__(self):\n print(self.color, end="")\n def __exit__(self, type, value, traceback):\n if self.clazz == Fore:\n print(Fore.RESET, end="")\n else:\n assert self.clazz == Style\n print(Style.RESET_ALL, end="")\n sys.stdout.flush()\n\nwith Highlight(Fore, Fore.GREEN):\n print("this is highlighted")\nprint("this is not")\n</code></pre>\n"
},
{
"answer_id": 15647557,
"author": "Vishal",
"author_id": 197473,
"author_profile": "https://Stackoverflow.com/users/197473",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"https://raw.github.com/fabric/fabric/master/fabric/colors.py\">https://raw.github.com/fabric/fabric/master/fabric/colors.py</a></p>\n\n<pre><code>\"\"\"\n.. versionadded:: 0.9.2\n\nFunctions for wrapping strings in ANSI color codes.\n\nEach function within this module returns the input string ``text``, wrapped\nwith ANSI color codes for the appropriate color.\n\nFor example, to print some text as green on supporting terminals::\n\n from fabric.colors import green\n\n print(green(\"This text is green!\"))\n\nBecause these functions simply return modified strings, you can nest them::\n\n from fabric.colors import red, green\n\n print(red(\"This sentence is red, except for \" + \\\n green(\"these words, which are green\") + \".\"))\n\nIf ``bold`` is set to ``True``, the ANSI flag for bolding will be flipped on\nfor that particular invocation, which usually shows up as a bold or brighter\nversion of the original color on most terminals.\n\"\"\"\n\n\ndef _wrap_with(code):\n\n def inner(text, bold=False):\n c = code\n if bold:\n c = \"1;%s\" % c\n return \"\\033[%sm%s\\033[0m\" % (c, text)\n return inner\n\nred = _wrap_with('31')\ngreen = _wrap_with('32')\nyellow = _wrap_with('33')\nblue = _wrap_with('34')\nmagenta = _wrap_with('35')\ncyan = _wrap_with('36')\nwhite = _wrap_with('37')\n</code></pre>\n"
},
{
"answer_id": 17064509,
"author": "mms",
"author_id": 1364048,
"author_profile": "https://Stackoverflow.com/users/1364048",
"pm_score": 5,
"selected": false,
"text": "<p>I have wrapped <a href=\"https://stackoverflow.com/questions/287871/how-to-print-colored-text-in-python/287944#287944\">joeld's answer</a> into a module with global functions that I can use anywhere in my code.</p>\n<p>File: log.py</p>\n<pre class=\"lang-py prettyprint-override\"><code>def enable():\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n BOLD = "\\033[1m"\n\ndef disable():\n HEADER = ''\n OKBLUE = ''\n OKGREEN = ''\n WARNING = ''\n FAIL = ''\n ENDC = ''\n\ndef infog(msg):\n print(OKGREEN + msg + ENDC)\n\ndef info(msg):\n print(OKBLUE + msg + ENDC)\n\ndef warn(msg):\n print(WARNING + msg + ENDC)\n\ndef err(msg):\n print(FAIL + msg + ENDC)\n\nenable()\n</code></pre>\n<p>Use as follows:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import log\nlog.info("Hello, World!")\nlog.err("System Error")\n</code></pre>\n"
},
{
"answer_id": 18923126,
"author": "Diego Navarro",
"author_id": 933059,
"author_profile": "https://Stackoverflow.com/users/933059",
"pm_score": 2,
"selected": false,
"text": "<p>My two cents (<a href=\"https://github.com/dnmellen/pycolorterm\" rel=\"nofollow\">PyColorTerm</a>):</p>\n\n<p>Installation:</p>\n\n<pre><code>sudo apt-get install python-pip\npip install pycolorterm\n</code></pre>\n\n<p>Python script:</p>\n\n<pre><code>from pycolorterm import pycolorterm\n\nwith pycolorterm.pretty_output(pycolorterm.FG_GREEN) as out:\n out.write('Works OK!')\n</code></pre>\n\n<p>\"works OK!\" shows in green.</p>\n"
},
{
"answer_id": 21786287,
"author": "rabin utam",
"author_id": 2112485,
"author_profile": "https://Stackoverflow.com/users/2112485",
"pm_score": 9,
"selected": false,
"text": "<p>Print a string that starts a color/style, then the string, and then end the color/style change with <code>'\\x1b[0m'</code>:</p>\n<pre><code>print('\\x1b[6;30;42m' + 'Success!' + '\\x1b[0m')\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/RN3MN.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/RN3MN.png\" alt=\"Success with green background example\" /></a></p>\n<p>Get a table of format options for shell text with the following code:</p>\n<pre><code>def print_format_table():\n """\n prints table of formatted text format options\n """\n for style in range(8):\n for fg in range(30,38):\n s1 = ''\n for bg in range(40,48):\n format = ';'.join([str(style), str(fg), str(bg)])\n s1 += '\\x1b[%sm %s \\x1b[0m' % (format, format)\n print(s1)\n print('\\n')\n\nprint_format_table()\n</code></pre>\n<h1>Light-on-dark example (complete)</h1>\n<p><a href=\"https://i.stack.imgur.com/6otvY.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/6otvY.png\" alt=\"Enter image description here\" /></a></p>\n<h1>Dark-on-light example (partial)</h1>\n<p><img src=\"https://i.stack.imgur.com/lZr23.png\" alt=\"Top part of output\" /></p>\n<p>Reference: <a href=\"https://en.wikipedia.org/wiki/ANSI_escape_code#Colors\" rel=\"noreferrer\">https://en.wikipedia.org/wiki/ANSI_escape_code#Colors</a></p>\n"
},
{
"answer_id": 26445590,
"author": "GI Jack",
"author_id": 4157799,
"author_profile": "https://Stackoverflow.com/users/4157799",
"pm_score": 6,
"selected": false,
"text": "<p>I generated a class with all the colors using a <code>for</code> loop to iterate every combination of color up to 100, and then wrote a class with Python colors. Copy and paste as you will, GPLv2 by me:</p>\n<pre><code>class colors:\n '''Colors class:\n Reset all colors with colors.reset\n Two subclasses fg for foreground and bg for background.\n Use as colors.subclass.colorname.\n i.e. colors.fg.red or colors.bg.green\n Also, the generic bold, disable, underline, reverse, strikethrough,\n and invisible work with the main class\n i.e. colors.bold\n '''\n reset='\\033[0m'\n bold='\\033[01m'\n disable='\\033[02m'\n underline='\\033[04m'\n reverse='\\033[07m'\n strikethrough='\\033[09m'\n invisible='\\033[08m'\n class fg:\n black='\\033[30m'\n red='\\033[31m'\n green='\\033[32m'\n orange='\\033[33m'\n blue='\\033[34m'\n purple='\\033[35m'\n cyan='\\033[36m'\n lightgrey='\\033[37m'\n darkgrey='\\033[90m'\n lightred='\\033[91m'\n lightgreen='\\033[92m'\n yellow='\\033[93m'\n lightblue='\\033[94m'\n pink='\\033[95m'\n lightcyan='\\033[96m'\n class bg:\n black='\\033[40m'\n red='\\033[41m'\n green='\\033[42m'\n orange='\\033[43m'\n blue='\\033[44m'\n purple='\\033[45m'\n cyan='\\033[46m'\n lightgrey='\\033[47m'\n</code></pre>\n"
},
{
"answer_id": 26695185,
"author": "Robpol86",
"author_id": 1198943,
"author_profile": "https://Stackoverflow.com/users/1198943",
"pm_score": 2,
"selected": false,
"text": "<p>I wrote a module that handles colors in Linux, OSΒ X, and Windows. It supports all 16 colors on all platforms, you can set foreground and background colors at different times, and the string objects give sane results for things like len() and .capitalize().</p>\n<p><a href=\"https://github.com/Robpol86/colorclass\" rel=\"nofollow noreferrer\">https://github.com/Robpol86/colorclass</a></p>\n<p><img src=\"https://i.stack.imgur.com/j7EjM.png\" alt=\"Example on Windows cmd.exe\" /></p>\n"
},
{
"answer_id": 27233961,
"author": "Igor Ε arΔeviΔ",
"author_id": 364938,
"author_profile": "https://Stackoverflow.com/users/364938",
"pm_score": 2,
"selected": false,
"text": "<p>You can use shell escape characters that are available from any language.\nThese escape characters start with the ESC character followed by a number of arguments.</p>\n<p>For example, to output a red <em>"Hello, World!"</em> string in your terminal:</p>\n<pre><code>echo "\\e[31m Hello, World! \\e[0m"\n</code></pre>\n<p>Or from a Python script:</p>\n<pre><code>print("\\e[31m Hello world \\e[0m")\n</code></pre>\n<p>Also, I wrote an article about <a href=\"http://shiroyasha.github.io/escape-sequences-a-quick-guide.html\" rel=\"nofollow noreferrer\">Escape sequences</a> that can probably help you get a better grasp of this mechanism.</p>\n"
},
{
"answer_id": 28159385,
"author": "WebMaster",
"author_id": 4285493,
"author_profile": "https://Stackoverflow.com/users/4285493",
"pm_score": 3,
"selected": false,
"text": "<p>Use <a href=\"https://github.com/ilovecode1/pyfancy\" rel=\"nofollow noreferrer\">pyfancy</a>. It is a simple way to do color in the terminal!</p>\n<p>Example:</p>\n<pre><code>print(pyfancy.RED + "Hello Red" + pyfancy.END)\n</code></pre>\n"
},
{
"answer_id": 28388343,
"author": "Jossef Harush Kadouri",
"author_id": 3191896,
"author_profile": "https://Stackoverflow.com/users/3191896",
"pm_score": 4,
"selected": false,
"text": "<h2>YAY! Another version</h2>\n<p>While I find <a href=\"https://stackoverflow.com/a/26445590/3191896\">this answer</a> useful, I modified it a bit. This <a href=\"https://gist.github.com/Jossef/0ee20314577925b4027f\" rel=\"nofollow noreferrer\">GitHub Gist</a> is the result</p>\n<h3>Usage</h3>\n<pre><code>print colors.draw("i'm yellow", bold=True, fg_yellow=True)\n</code></pre>\n<p><img src=\"https://i.stack.imgur.com/q1mJ3.png\" alt=\"Enter image description here\" /></p>\n<p>In addition, you can wrap common usages:</p>\n<pre><code>print colors.error('sorry, ')\n</code></pre>\n<p><img src=\"https://i.stack.imgur.com/uGgd7.png\" alt=\"Asd\" /></p>\n<h3><a href=\"https://gist.github.com/Jossef/0ee20314577925b4027f\" rel=\"nofollow noreferrer\">https://gist.github.com/Jossef/0ee20314577925b4027f</a></h3>\n"
},
{
"answer_id": 29723536,
"author": "zahanm",
"author_id": 640185,
"author_profile": "https://Stackoverflow.com/users/640185",
"pm_score": 5,
"selected": false,
"text": "<p>Stupidly simple, based on <a href=\"https://stackoverflow.com/questions/287871/how-to-print-colored-text-in-python/287944#287944\">joeld's answer</a>:</p>\n<pre><code>class PrintInColor:\n RED = '\\033[91m'\n GREEN = '\\033[92m'\n YELLOW = '\\033[93m'\n LIGHT_PURPLE = '\\033[94m'\n PURPLE = '\\033[95m'\n END = '\\033[0m'\n\n @classmethod\n def red(cls, s, **kwargs):\n print(cls.RED + s + cls.END, **kwargs)\n\n @classmethod\n def green(cls, s, **kwargs):\n print(cls.GREEN + s + cls.END, **kwargs)\n\n @classmethod\n def yellow(cls, s, **kwargs):\n print(cls.YELLOW + s + cls.END, **kwargs)\n\n @classmethod\n def lightPurple(cls, s, **kwargs):\n print(cls.LIGHT_PURPLE + s + cls.END, **kwargs)\n\n @classmethod\n def purple(cls, s, **kwargs):\n print(cls.PURPLE + s + cls.END, **kwargs)\n</code></pre>\n<p>Then just</p>\n<pre><code>PrintInColor.red('hello', end=' ')\nPrintInColor.green('world')\n</code></pre>\n"
},
{
"answer_id": 29806601,
"author": "Grijesh Chauhan",
"author_id": 1673391,
"author_profile": "https://Stackoverflow.com/users/1673391",
"pm_score": 4,
"selected": false,
"text": "<p>If you are using <a href=\"https://www.djangoproject.com/\" rel=\"nofollow noreferrer\">Django</a>:</p>\n<pre><code>>>> from django.utils.termcolors import colorize\n>>> print colorize("Hello, World!", fg="blue", bg='red',\n... opts=('bold', 'blink', 'underscore',))\nHello World!\n>>> help(colorize)\n</code></pre>\n<p>Snapshot:</p>\n<p><img src=\"https://i.stack.imgur.com/vq4Rs.png\" alt=\"Image\" /></p>\n<p>(I generally use colored output for debugging on runserver terminal, so I added it.)</p>\n<p><sub>You can test if it is installed in your machine:\n<code>$ python -c "import django; print django.VERSION"</code>. To install it, check: <a href=\"https://docs.djangoproject.com/en/1.8/topics/install/\" rel=\"nofollow noreferrer\">How to install Django</a></sub></p>\n<p>Give it a <em>try</em>!!</p>\n"
},
{
"answer_id": 31310228,
"author": "drevicko",
"author_id": 420867,
"author_profile": "https://Stackoverflow.com/users/420867",
"pm_score": 3,
"selected": false,
"text": "<p>Yet another <a href=\"https://en.wikipedia.org/wiki/Python_Package_Index\" rel=\"nofollow noreferrer\">PyPI</a> module that wraps the PythonΒ 3 <em>print</em> function:</p>\n<p><a href=\"https://pypi.python.org/pypi/colorprint\" rel=\"nofollow noreferrer\">https://pypi.python.org/pypi/colorprint</a></p>\n<p>It's usable in Python 2.x if you also <code>from __future__ import print</code>. Here is a PythonΒ 2 example from the modules PyPI page:</p>\n<pre><code>from __future__ import print_function\nfrom colorprint import *\n\nprint('Hello', 'world', color='blue', end='', sep=', ')\nprint('!', color='red', format=['bold', 'blink'])\n</code></pre>\n<p>It outputs "Hello, world!" with the words in blue and the exclamation mark bold red and blinking.</p>\n"
},
{
"answer_id": 34443116,
"author": "gauravds",
"author_id": 1084917,
"author_profile": "https://Stackoverflow.com/users/1084917",
"pm_score": 6,
"selected": false,
"text": "<p>Try this simple code</p>\n<pre class=\"lang-py prettyprint-override\"><code>def prRed(prt):\n print(f"\\033[91m{prt}\\033[00m")\n\ndef prGreen(prt):\n print(f"\\033[92m{prt}\\033[00m")\n\ndef prYellow(prt):\n print(f"\\033[93m{prt}\\033[00m")\n\ndef prLightPurple(prt):\n print(f"\\033[94m{prt}\\033[00m")\n\ndef prPurple(prt):\n print(f"\\033[95m{prt}\\033[00m")\n\ndef prCyan(prt):\n print(f"\\033[96m{prt}\\033[00m")\n\ndef prLightGray(prt):\n print(f"\\033[97m{prt}\\033[00m")\n\ndef prBlack(prt):\n print(f"\\033[98m{prt}\\033[00m")\n\ndef prReset(prt):\n print(f"\\033[0m{prt}\\033[00m")\n\nprGreen("Hello, Green World!")\nprBlack("Hello, Black World!")\nprCyan("Hello, Cyan World!")\nprGreen("Hello, Green World!")\nprLightGray("Hello, Light Grey World!")\nprLightPurple("Hello, Light Purple World!")\nprPurple("Hello, Purple World!")\nprRed("Hello, Red World!")\nprYellow("Hello, Yellow World!")\nprReset("Hello, Reset World!")\n</code></pre>\n<p>Python 3 Example\n<a href=\"https://i.stack.imgur.com/VsUHx.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/VsUHx.png\" alt=\"Python 3 Example.\" /></a></p>\n<pre><code># python2\n def prRed(prt): print("\\033[91m {}\\033[00m" .format(prt))\n def prGreen(prt): print("\\033[92m {}\\033[00m" .format(prt))\n def prYellow(prt): print("\\033[93m {}\\033[00m" .format(prt))\n def prLightPurple(prt): print("\\033[94m {}\\033[00m" .format(prt))\n def prPurple(prt): print("\\033[95m {}\\033[00m" .format(prt))\n def prCyan(prt): print("\\033[96m {}\\033[00m" .format(prt))\n def prLightGray(prt): print("\\033[97m {}\\033[00m" .format(prt))\n def prBlack(prt): print("\\033[98m {}\\033[00m" .format(prt))\n\n prGreen("Hello, World!")\n</code></pre>\n"
},
{
"answer_id": 37051472,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://asciimatics.readthedocs.io/en/stable/intro.html\" rel=\"noreferrer\">asciimatics</a> provides a portable support for building text UI and animations:</p>\n\n<pre><code>#!/usr/bin/env python\nfrom asciimatics.effects import RandomNoise # $ pip install asciimatics\nfrom asciimatics.renderers import SpeechBubble, Rainbow\nfrom asciimatics.scene import Scene\nfrom asciimatics.screen import Screen\nfrom asciimatics.exceptions import ResizeScreenError\n\n\ndef demo(screen):\n render = Rainbow(screen, SpeechBubble('Rainbow'))\n effects = [RandomNoise(screen, signal=render)]\n screen.play([Scene(effects, -1)], stop_on_resize=True)\n\nwhile True:\n try:\n Screen.wrapper(demo)\n break\n except ResizeScreenError:\n pass\n</code></pre>\n\n<p>Asciicast:</p>\n\n<p><a href=\"https://asciinema.org/a/06sabwtc1bw5wfiq23a71ccxq?autoplay=1\" rel=\"noreferrer\"><img src=\"https://asciinema.org/a/06sabwtc1bw5wfiq23a71ccxq.png\" alt=\"rainbow-colored text among ascii noise\"></a></p>\n"
},
{
"answer_id": 39005305,
"author": "Ben174",
"author_id": 850927,
"author_profile": "https://Stackoverflow.com/users/850927",
"pm_score": 5,
"selected": false,
"text": "<p>I ended up doing this, and I felt it was cleanest:</p>\n<pre><code>formatters = {\n 'RED': '\\033[91m',\n 'GREEN': '\\033[92m',\n 'END': '\\033[0m',\n}\n\nprint 'Master is currently {RED}red{END}!'.format(**formatters)\nprint 'Help make master {GREEN}green{END} again!'.format(**formatters)\n</code></pre>\n"
},
{
"answer_id": 39452138,
"author": "qubodup",
"author_id": 188159,
"author_profile": "https://Stackoverflow.com/users/188159",
"pm_score": 8,
"selected": false,
"text": "<p>Define a string that starts a color and a string that ends the color. Then print your text with the start string at the front and the end string at the end.</p>\n<pre class=\"lang-py prettyprint-override\"><code>CRED = '\\033[91m'\nCEND = '\\033[0m'\nprint(CRED + "Error, does not compute!" + CEND)\n</code></pre>\n<p>This produces the following in Bash, in <code>urxvt</code> with a Zenburn-style color scheme:</p>\n<p><a href=\"https://i.stack.imgur.com/Iu3I1.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/Iu3I1.png\" alt=\"Output colors\" /></a></p>\n<p>Through experimentation, we can get more colors:</p>\n<p><a href=\"https://i.stack.imgur.com/j7e4i.gif\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/j7e4i.gif\" alt=\"Color matrix\" /></a></p>\n<p>Note: <code>\\33[5m</code> and <code>\\33[6m</code> are blinking.</p>\n<p>This way we can create a full color collection:</p>\n<pre><code>CEND = '\\33[0m'\nCBOLD = '\\33[1m'\nCITALIC = '\\33[3m'\nCURL = '\\33[4m'\nCBLINK = '\\33[5m'\nCBLINK2 = '\\33[6m'\nCSELECTED = '\\33[7m'\n\nCBLACK = '\\33[30m'\nCRED = '\\33[31m'\nCGREEN = '\\33[32m'\nCYELLOW = '\\33[33m'\nCBLUE = '\\33[34m'\nCVIOLET = '\\33[35m'\nCBEIGE = '\\33[36m'\nCWHITE = '\\33[37m'\n\nCBLACKBG = '\\33[40m'\nCREDBG = '\\33[41m'\nCGREENBG = '\\33[42m'\nCYELLOWBG = '\\33[43m'\nCBLUEBG = '\\33[44m'\nCVIOLETBG = '\\33[45m'\nCBEIGEBG = '\\33[46m'\nCWHITEBG = '\\33[47m'\n\nCGREY = '\\33[90m'\nCRED2 = '\\33[91m'\nCGREEN2 = '\\33[92m'\nCYELLOW2 = '\\33[93m'\nCBLUE2 = '\\33[94m'\nCVIOLET2 = '\\33[95m'\nCBEIGE2 = '\\33[96m'\nCWHITE2 = '\\33[97m'\n\nCGREYBG = '\\33[100m'\nCREDBG2 = '\\33[101m'\nCGREENBG2 = '\\33[102m'\nCYELLOWBG2 = '\\33[103m'\nCBLUEBG2 = '\\33[104m'\nCVIOLETBG2 = '\\33[105m'\nCBEIGEBG2 = '\\33[106m'\nCWHITEBG2 = '\\33[107m'\n</code></pre>\n<p>Here is the code to generate the test:</p>\n<pre class=\"lang-py prettyprint-override\"><code>x = 0\nfor i in range(24):\n colors = ""\n for j in range(5):\n code = str(x+j)\n colors = colors + "\\33[" + code + "m\\\\33[" + code + "m\\033[0m "\n print(colors)\n x = x + 5\n</code></pre>\n"
},
{
"answer_id": 42528796,
"author": "alvas",
"author_id": 610569,
"author_profile": "https://Stackoverflow.com/users/610569",
"pm_score": 5,
"selected": false,
"text": "<p>Building on <a href=\"https://stackoverflow.com/questions/287871/how-to-print-colored-text-in-python/287944#287944\">joeld's answer</a>, using <a href=\"https://pypi.python.org/pypi/lazyme\" rel=\"nofollow noreferrer\">https://pypi.python.org/pypi/lazyme</a> <br/>\n<code>pip install -U lazyme</code>:</p>\n<pre><code>from lazyme.string import color_print\n>>> color_print('abc')\nabc\n>>> color_print('abc', color='pink')\nabc\n>>> color_print('abc', color='red')\nabc\n>>> color_print('abc', color='yellow')\nabc\n>>> color_print('abc', color='green')\nabc\n>>> color_print('abc', color='blue', underline=True)\nabc\n>>> color_print('abc', color='blue', underline=True, bold=True)\nabc\n>>> color_print('abc', color='pink', underline=True, bold=True)\nabc\n</code></pre>\n<p>Screenshot:</p>\n<p><a href=\"https://i.stack.imgur.com/9NgeB.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/9NgeB.png\" alt=\"Enter image description here\" /></a></p>\n<hr />\n<p>Some updates to the <code>color_print</code> with new formatters, e.g.:</p>\n<pre><code>>>> from lazyme.string import palette, highlighter, formatter\n>>> from lazyme.string import color_print\n>>> palette.keys() # Available colors.\n['pink', 'yellow', 'cyan', 'magenta', 'blue', 'gray', 'default', 'black', 'green', 'white', 'red']\n>>> highlighter.keys() # Available highlights.\n['blue', 'pink', 'gray', 'black', 'yellow', 'cyan', 'green', 'magenta', 'white', 'red']\n>>> formatter.keys() # Available formatter,\n['hide', 'bold', 'italic', 'default', 'fast_blinking', 'faint', 'strikethrough', 'underline', 'blinking', 'reverse']\n</code></pre>\n<p>Note: <code>italic</code>, <code>fast blinking</code>, and <code>strikethrough</code> may not work on all terminals, and they don't work on Mac and Ubuntu.</p>\n<p>E.g.,</p>\n<pre><code>>>> color_print('foo bar', color='pink', highlight='white')\nfoo bar\n>>> color_print('foo bar', color='pink', highlight='white', reverse=True)\nfoo bar\n>>> color_print('foo bar', color='pink', highlight='white', bold=True)\nfoo bar\n>>> color_print('foo bar', color='pink', highlight='white', faint=True)\nfoo bar\n>>> color_print('foo bar', color='pink', highlight='white', faint=True, reverse=True)\nfoo bar\n>>> color_print('foo bar', color='pink', highlight='white', underline=True, reverse=True)\nfoo bar\n</code></pre>\n<p>Screenshot:</p>\n<p><a href=\"https://i.stack.imgur.com/HGNPc.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/HGNPc.png\" alt=\"Enter image description here\" /></a></p>\n"
},
{
"answer_id": 48723332,
"author": "Rotareti",
"author_id": 1612318,
"author_profile": "https://Stackoverflow.com/users/1612318",
"pm_score": 7,
"selected": false,
"text": "<p><a href=\"https://github.com/feluxe/sty\" rel=\"noreferrer\">sty</a> is similar to colorama, but it's less verbose, supports <a href=\"https://sty.mewo.dev/docs/coloring.html#coloring-with-8-bit-codes\" rel=\"noreferrer\">8-bit</a> and <a href=\"https://sty.mewo.dev/docs/coloring.html#coloring-with-24bit-codes\" rel=\"noreferrer\">24-bit</a> (RGB) colors, supports all <a href=\"https://sty.mewo.dev/docs/effects.html\" rel=\"noreferrer\">effects</a> (bold, underline, etc.), allows you to <a href=\"https://sty.mewo.dev/docs/customizing.html#add-custom-styles-to-a-register-object\" rel=\"noreferrer\">register your own styles</a>, is fully typed and high performant, supports <a href=\"https://sty.mewo.dev/docs/muting.html#the-mute-and-unmute-methods\" rel=\"noreferrer\">muting</a>, is not messing with globals such as <code>sys.stdout</code>, is really flexible, well <a href=\"https://sty.mewo.dev/\" rel=\"noreferrer\">documented</a> and more...</p>\n<p><strong>Examples:</strong></p>\n<pre class=\"lang-py prettyprint-override\"><code>from sty import fg, bg, ef, rs\n\nfoo = fg.red + 'This is red text!' + fg.rs\nbar = bg.blue + 'This has a blue background!' + bg.rs\nbaz = ef.italic + 'This is italic text' + rs.italic\nqux = fg(201) + 'This is pink text using 8bit colors' + fg.rs\nqui = fg(255, 10, 10) + 'This is red text using 24bit colors.' + fg.rs\n\n# Add custom colors:\n\nfrom sty import Style, RgbFg\n\nfg.orange = Style(RgbFg(255, 150, 50))\n\nbuf = fg.orange + 'Yay, Im orange.' + fg.rs\n\nprint(foo, bar, baz, qux, qui, buf, sep='\\n')\n</code></pre>\n<p>prints:</p>\n<p><a href=\"https://i.stack.imgur.com/4BIdi.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/4BIdi.png\" alt=\"Enter image description here\" /></a></p>\n<p><strong>Demo:</strong></p>\n<p><a href=\"https://i.stack.imgur.com/S8wtO.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/S8wtO.png\" alt=\"Enter image description here\" /></a></p>\n"
},
{
"answer_id": 50025330,
"author": "Andriy Makukha",
"author_id": 5407270,
"author_profile": "https://Stackoverflow.com/users/5407270",
"pm_score": 6,
"selected": false,
"text": "<pre><code># Pure Python 3.x demo, 256 colors\n# Works with bash under Linux and MacOS\n\nfg = lambda text, color: "\\33[38;5;" + str(color) + "m" + text + "\\33[0m"\nbg = lambda text, color: "\\33[48;5;" + str(color) + "m" + text + "\\33[0m"\n\ndef print_six(row, format, end="\\n"):\n for col in range(6):\n color = row*6 + col - 2\n if color>=0:\n text = "{:3d}".format(color)\n print (format(text,color), end=" ")\n else:\n print(end=" ") # four spaces\n print(end=end)\n\nfor row in range(0, 43):\n print_six(row, fg, " ")\n print_six(row, bg)\n\n# Simple usage: print(fg("text", 160))\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/qqMmX.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/qqMmX.png\" alt=\"Text with altering foreground and background, colors 0..141\" /></a>\n<a href=\"https://i.stack.imgur.com/3X16v.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/3X16v.png\" alt=\"Text with altering foreground and background, colors 142..255\" /></a></p>\n<p><a href=\"https://code.labstack.com/VfphHQ14\" rel=\"noreferrer\">Try it online</a></p>\n"
},
{
"answer_id": 50447424,
"author": "kmario23",
"author_id": 2956066,
"author_profile": "https://Stackoverflow.com/users/2956066",
"pm_score": 4,
"selected": false,
"text": "<p>An easier option would be to use the <code>cprint</code> function from the <a href=\"https://pypi.org/project/termcolor/\" rel=\"nofollow noreferrer\"><code>termcolor</code></a> package.</p>\n<p><a href=\"https://i.stack.imgur.com/v35jK.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/v35jK.png\" alt=\"color-print-python\" /></a></p>\n<p>It also supports <code>%s, %d</code> format of printing:</p>\n<p><a href=\"https://i.stack.imgur.com/BvgXH.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/BvgXH.png\" alt=\"Enter image description here\" /></a></p>\n<p>Results can be terminal dependant, so review the <strong>Terminal Properties</strong> section of the package documentation.</p>\n<ul>\n<li>Windows Command Prompt and Python IDLE don't work</li>\n</ul>\n<p><a href=\"https://i.stack.imgur.com/46mp4.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/46mp4.png\" alt=\"enter image description here\" /></a></p>\n<p><a href=\"https://i.stack.imgur.com/4A7ug.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/4A7ug.png\" alt=\"enter image description here\" /></a></p>\n<ul>\n<li>JupyterLab notebook does work</li>\n</ul>\n<p><a href=\"https://i.stack.imgur.com/kFhyO.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/kFhyO.png\" alt=\"enter image description here\" /></a></p>\n"
},
{
"answer_id": 52032616,
"author": "Al Po",
"author_id": 1224072,
"author_profile": "https://Stackoverflow.com/users/1224072",
"pm_score": 2,
"selected": false,
"text": "<p>I am new to Python and I'm excited every time I discover topics, like this one. But this time (suddenly) I feel like I have what to say. Especially because a few minutes ago I discovered a <em>wow</em> thing in Python (at least for me now):</p>\n<p><a href=\"https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager\" rel=\"nofollow noreferrer\"><strong>Context Managers</strong></a></p>\n<pre><code>from contextlib import contextmanager\n# FORECOLOR\nBLACKFC,REDFC,GREENFC,YELLOWFC,BLUEFC = '38;30m','38;31m','38;32m','38;33m','38;34m'\n# BACKGOUND\nBLACKBG,REDBG,GREENBG,YELLOWBG,BLUEBG = '48;40m','48;41m','48;42m','48;43m','48;44m'\n\n@contextmanager\ndef printESC(prefix, color, text):\n print("{prefix}{color}{text}".format(prefix=prefix, color=color, text=text), end='')\n yield\n print("{prefix}0m".format(prefix=prefix))\n\nwith printESC('\\x1B[', REDFC, 'Colored Text'):\n pass\n</code></pre>\n<p><a href=\"https://repl.it/@VoldemarShalomo/Escape-sequences-for-visual-effects-in-terminal\" rel=\"nofollow noreferrer\">Example</a></p>\n<p>Or just like this:</p>\n<pre><code># FORECOLOR\nBLACKFC,REDFC,GREENFC,YELLOWFC,BLUEFC = '38;30m','38;31m','38;32m','38;33m','38;34m'\n# BACKGOUND\nBLACKBG,REDBG,GREENBG,YELLOWBG,BLUEBG = '48;40m','48;41m','48;42m','48;43m','48;44m'\n\ndef printESC(prefix, color, text):\n print("{prefix}{color}{text}".format(prefix=prefix, color=color, text=text), end='')\n print("{prefix}0m".format(prefix=prefix))\n\nprintESC('\\x1B[', REDFC, 'Colored Text')\n</code></pre>\n"
},
{
"answer_id": 54955094,
"author": "SimpleBinary",
"author_id": 11073514,
"author_profile": "https://Stackoverflow.com/users/11073514",
"pm_score": 7,
"selected": false,
"text": "<p>Here's a solution that works on Windows 10 natively.</p>\n<p>Using a system call, such as <code>os.system("")</code>, allows colours to be printed in Command Prompt and Powershell natively:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import os\n\n# System call\nos.system("")\n\n# Class of different styles\nclass style():\n BLACK = '\\033[30m'\n RED = '\\033[31m'\n GREEN = '\\033[32m'\n YELLOW = '\\033[33m'\n BLUE = '\\033[34m'\n MAGENTA = '\\033[35m'\n CYAN = '\\033[36m'\n WHITE = '\\033[37m'\n UNDERLINE = '\\033[4m'\n RESET = '\\033[0m'\n\nprint(style.YELLOW + "Hello, World!")\n</code></pre>\n<p>Note: Windows does not fully support ANSI codes, whether through system calls or modules. Not all text decoration is supported, and although the bright colours display, they are identical to the regular colours.</p>\n<p>Thanks to @j-l for finding an even shorter method.</p>\n<p><strong>tl;dr</strong>: Add <code>os.system("")</code></p>\n"
},
{
"answer_id": 58149095,
"author": "Vishal",
"author_id": 197473,
"author_profile": "https://Stackoverflow.com/users/197473",
"pm_score": 5,
"selected": false,
"text": "<pre class=\"lang-py prettyprint-override\"><code>def black(text):\n print('\\033[30m', text, '\\033[0m', sep='')\n\ndef red(text):\n print('\\033[31m', text, '\\033[0m', sep='')\n\ndef green(text):\n print('\\033[32m', text, '\\033[0m', sep='')\n\ndef yellow(text):\n print('\\033[33m', text, '\\033[0m', sep='')\n\ndef blue(text):\n print('\\033[34m', text, '\\033[0m', sep='')\n\ndef magenta(text):\n print('\\033[35m', text, '\\033[0m', sep='')\n\ndef cyan(text):\n print('\\033[36m', text, '\\033[0m', sep='')\n\ndef gray(text):\n print('\\033[90m', text, '\\033[0m', sep='')\n\n\nblack(\"BLACK\")\nred(\"RED\")\ngreen(\"GREEN\")\nyellow(\"YELLOW\")\nblue(\"BLACK\")\nmagenta(\"MAGENTA\")\ncyan(\"CYAN\")\ngray(\"GRAY\")\n</code></pre>\n\n<p><a href=\"https://code.labstack.com/EoyDRCvJ\" rel=\"noreferrer\"><strong>Try online</strong></a> </p>\n"
},
{
"answer_id": 59274139,
"author": "hooman",
"author_id": 12168946,
"author_profile": "https://Stackoverflow.com/users/12168946",
"pm_score": 2,
"selected": false,
"text": "<p>The simplest way I can find is not to use ANSI escape codes, but use <code>Fore</code> from import module <code>colorama</code>. Take a look at the code below:</p>\n\n<pre><code>from colorama import Fore, Style\n\nprint(Fore.MAGENTA + \"IZZ MAGENTA BRUH.\")\n\nprint(Style.RESET_ALL + \"IZZ BACK TO NORMALZ.\")\n</code></pre>\n\n<p>compared to the ANSI escape code:</p>\n\n<pre><code>print(\"\\u001b[31m IZZ RED (NO MAGENTA ON ANSI CODES).\\u001b[0m\")\n\nprint(\"BACK TO NORMALZ.\")\n</code></pre>\n"
},
{
"answer_id": 59582215,
"author": "BeastCoder",
"author_id": 10146757,
"author_profile": "https://Stackoverflow.com/users/10146757",
"pm_score": 5,
"selected": false,
"text": "<p>I have a <a href=\"https://github.com/SuperMaZingCoder/ColorIt\" rel=\"noreferrer\">library called colorit</a>. It is super simple.</p>\n<p>Here are some examples:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from colorit import *\n\n# Use this to ensure that ColorIt will be usable by certain command line interfaces\n# Note: This clears the terminal\ninit_colorit()\n\n# Foreground\nprint(color("This text is red", Colors.red))\nprint(color("This text is orange", Colors.orange))\nprint(color("This text is yellow", Colors.yellow))\nprint(color("This text is green", Colors.green))\nprint(color("This text is blue", Colors.blue))\nprint(color("This text is purple", Colors.purple))\nprint(color("This text is white", Colors.white))\n\n# Background\nprint(background("This text has a background that is red", Colors.red))\nprint(background("This text has a background that is orange", Colors.orange))\nprint(background("This text has a background that is yellow", Colors.yellow))\nprint(background("This text has a background that is green", Colors.green))\nprint(background("This text has a background that is blue", Colors.blue))\nprint(background("This text has a background that is purple", Colors.purple))\nprint(background("This text has a background that is white", Colors.white))\n\n# Custom\nprint(color("This color has a custom grey text color", (150, 150, 150)))\nprint(background("This color has a custom grey background", (150, 150, 150)))\n\n# Combination\nprint(\n background(\n color("This text is blue with a white background", Colors.blue), Colors.white\n )\n)\n\n# If you are using Windows Command Line, this is so that it doesn't close immediately\ninput()\n</code></pre>\n<p>This gives you:</p>\n<p><a href=\"https://i.stack.imgur.com/AESCH.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/AESCH.png\" alt=\"Picture of ColorIt\" /></a></p>\n<p>It's also worth noting that this is cross platform and has been tested on Mac, Linux, and Windows.</p>\n<p>You might want to try it out: <a href=\"https://github.com/SuperMaZingCoder/colorit\" rel=\"noreferrer\">https://github.com/SuperMaZingCoder/colorit</a></p>\n<p><code>colorit</code> is now available to be installed with PyPi! You can install it with <code>pip install color-it</code> on Windows and <code>pip3 install color-it</code> on macOS and Linux.</p>\n"
},
{
"answer_id": 60252056,
"author": "Gerry P",
"author_id": 10798917,
"author_profile": "https://Stackoverflow.com/users/10798917",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a simple function I use to print a text message in color without having to remember ANSI codes but rather using standard RGB tuples to define the foreground and background colors.</p>\n<pre><code>def print_in_color(txt_msg, fore_tuple, back_tuple, ):\n # Prints the text_msg in the foreground color specified by fore_tuple with the background specified by back_tuple\n # text_msg is the text, fore_tuple is foreground color tuple (r,g,b), back_tuple is background tuple (r,g,b)\n rf,bf,gf = fore_tuple\n rb,gb,bb = back_tuple\n msg = '{0}' + txt_msg\n mat = '\\33[38;2;' + str(rf) + ';' + str(gf) + ';' + str(bf) + ';48;2;' + str(rb) + ';' +str(gb) + ';' + str(bb) + 'm'\n print(msg .format(mat))\n print('\\33[0m') # Returns default print color to back to black\n\n# Example of use using a message with variables\nfore_color = 'cyan'\nback_color = 'dark green'\nmsg = 'foreground color is {0} and the background color is {1}'.format(fore_color, back_color)\nprint_in_color(msg, (0,255,255), (0,127,127))\n</code></pre>\n"
},
{
"answer_id": 61219634,
"author": "Edgardo ObregΓ³n",
"author_id": 12901164,
"author_profile": "https://Stackoverflow.com/users/12901164",
"pm_score": 3,
"selected": false,
"text": "<p>I suggest this new library <strong>Printy</strong>. They just released version 1.2.0 as a cross-platform library.</p>\n<p>Check it out:\n<a href=\"https://github.com/edraobdu/printy\" rel=\"nofollow noreferrer\">Printy on GitHub</a></p>\n<p>It is based on flags so you can do stuff like</p>\n<pre class=\"lang-py prettyprint-override\"><code>from printy import printy\n\n# With global flags, this will apply a bold (B) red (r) color and an underline (U) to the whole text\nprinty("Hello, World!", "rBU")\n\n# With inline formats, this will apply a dim (D)\n#blue (b) to the word 'Hello' and a stroken (S)\n#yellow (y) to the word 'world', and the rest will remain as the predefined format\nprinty("this is a [bD]Hello@ [yS]world@ text")\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/1YRLS.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/1YRLS.png\" alt=\"Enter image description here\" /></a></p>\n"
},
{
"answer_id": 61960902,
"author": "CircuitSacul",
"author_id": 13314450,
"author_profile": "https://Stackoverflow.com/users/13314450",
"pm_score": 6,
"selected": false,
"text": "<p>This is, in my opinion, the easiest method. As long as you have the RGB values of the color you want, this should work:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def colored(r, g, b, text):\n return f"\\033[38;2;{r};{g};{b}m{text}\\033[0m"\n</code></pre>\n<p>An example of printing red text:</p>\n<pre class=\"lang-py prettyprint-override\"><code>text = 'Hello, World!'\ncolored_text = colored(255, 0, 0, text)\nprint(colored_text)\n\n#or\n\nprint(colored(255, 0, 0, 'Hello, World!'))\n</code></pre>\n<p>Multi-colored text</p>\n<pre class=\"lang-py prettyprint-override\"><code>text = colored(255, 0, 0, 'Hello, ') + colored(0, 255, 0, 'World')\nprint(text)\n</code></pre>\n"
},
{
"answer_id": 62530462,
"author": "Carson",
"author_id": 9935654,
"author_profile": "https://Stackoverflow.com/users/9935654",
"pm_score": 3,
"selected": false,
"text": "<p>I created a project (<code>console-color</code>) and already published it to <a href=\"https://pypi.org/project/console-color/\" rel=\"nofollow noreferrer\">PyPI</a>.</p>\n<p>You can throw <code>pip install console-color</code> to install it.</p>\n<p>And I write the document with Sphinx-read-the-doc, see <a href=\"https://carsonslovoka.github.io/console-color/en/source/introduction.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n<p>You can get more example from <a href=\"https://colab.research.google.com/drive/1cAYcC6DyiMCyD0RDcEo25LDFCh527TUQ?usp=sharing\" rel=\"nofollow noreferrer\">google-colab</a>.</p>\n<p>I still post some example to attract the user to click the above link:</p>\n<pre class=\"lang-py prettyprint-override\"><code># cprint is something like below\n# cprint(text: str, fore: T_RGB = None, bg: T_RGB = None, style: Style = '')\n# where T_RGB = Union[Tuple[int, int, int], str] for example. You can input (255, 0, 0) or '#ff0000' or 'ff0000'. They are OK.\n# The Style you can input the ``Style.`` (the IDE will help you to choose what you wanted)\n\n# from console_color import RGB, Fore, Style, cprint, create_print\nfrom console_color import *\n\ncprint("Hello, World!", RGB.RED, RGB.YELLOW, Style.BOLD+Style.URL+Style.STRIKE)\ncprint("Hello, World!", fore=(255, 0, 0), bg="ffff00", style=Style.BOLD+Style.URL+Style.STRIKE)\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/ZzWF9.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ZzWF9.png\" alt=\"Enter image description here\" /></a></p>\n<p><em>Of course, you donβt have to enter all the parameters. You can just add the attributes you want.</em></p>\n<hr />\n<p>To be honest, this project is not special. It just uses the <code>f"\\033[{target};2;{r};{g};{b}m{text}{style}"</code>\nwhere target is 38 or 48, text is your input string, and style is '\\33[0m', '\\33[1m' ... '\\033[9m'. Some kind of stuff.</p>\n<p>And I just make it easy to use (at least for me).</p>\n"
},
{
"answer_id": 63551578,
"author": "ijoseph",
"author_id": 588437,
"author_profile": "https://Stackoverflow.com/users/588437",
"pm_score": 4,
"selected": false,
"text": "<pre class=\"lang-py prettyprint-override\"><code>import click\n\nclick.secho('Hello, World!', fg='green')\nclick.secho('Some more text', bg='blue', fg='white')\nclick.secho('ATTENTION', blink=True, bold=True)\n</code></pre>\n<p><a href=\"https://click.palletsprojects.com/en/7.x/utils/\" rel=\"nofollow noreferrer\"><code>click</code> (CLI library)</a> has a very convenient way of doing this, and is worth considering if you're writing a command-line tool, anyway.</p>\n"
},
{
"answer_id": 64099955,
"author": "Mojtaba Hosseini",
"author_id": 5623035,
"author_profile": "https://Stackoverflow.com/users/5623035",
"pm_score": 4,
"selected": false,
"text": "<h1>Emoji</h1>\n<p>You can use colors for text as others mentioned in their answers to have colorful text with a background or foreground color.</p>\n<p>But you can use <strong>emojis</strong> instead! for example, you can use<code>β οΈ</code> for warning messages and <code></code> for error messages.</p>\n<p>Or simply use these notebooks as a color:</p>\n<pre><code>: error message\n: warning message\n: ok status message\n: action message\n: canceled status message\n: Or anything you like and want to recognize immediately by color\n\n</code></pre>\n<h3> Bonus:</h3>\n<p>This method also helps you to quickly scan and find logs <strong>directly in the source code</strong>.</p>\n<p><sub>But some operating systems (including some Linux distributions in some version with some window managers) default emoji font is not colorful by default and you may want to make them colorful, first.</sub></p>\n<hr />\n<h3>How to open emoji picker?</h3>\n<p><a href=\"https://support.apple.com/guide/mac-help/use-emoji-and-symbols-on-mac-mchlp1560/mac\" rel=\"noreferrer\"><strong>mac os</strong>:</a> <kbd>control</kbd> + <kbd>command</kbd> + <kbd>space</kbd></p>\n<p><a href=\"https://support.microsoft.com/en-us/windows/windows-10-keyboard-tips-and-tricks-588e0b72-0fff-6d3f-aeee-6e5116097942\" rel=\"noreferrer\"><strong>windows</strong>:</a> <kbd>win</kbd> + <kbd>.</kbd></p>\n<p><a href=\"https://www.omgubuntu.co.uk/2018/06/use-emoji-linux-ubuntu-apps\" rel=\"noreferrer\"><strong>linux</strong>:</a> <kbd>control</kbd> + <kbd>.</kbd> or <kbd>control</kbd> + <kbd>;</kbd></p>\n"
},
{
"answer_id": 65088582,
"author": "Will McGugan",
"author_id": 673463,
"author_profile": "https://Stackoverflow.com/users/673463",
"pm_score": 6,
"selected": false,
"text": "<p><a href=\"https://github.com/willmcgugan/rich\" rel=\"noreferrer\">Rich</a> is a relatively new Python library for working with color in the terminal.</p>\n<p>There are a few ways of working with color in Rich. The quickest way to get started would be the rich print method which renders a <a href=\"https://en.wikipedia.org/wiki/BBCode\" rel=\"noreferrer\">BBCode</a>-like syntax in to ANSI control codes:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from rich import print\nprint("[red]Color[/] in the [bold magenta]Terminal[/]!")\n</code></pre>\n<p>There are other ways of applying color with Rich (regex, syntax) and related formatting features.</p>\n<p><a href=\"https://i.stack.imgur.com/4jJaD.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/4jJaD.png\" alt=\"Screenshot of Rich\" /></a></p>\n"
},
{
"answer_id": 65238905,
"author": "prerakl123",
"author_id": 13458018,
"author_profile": "https://Stackoverflow.com/users/13458018",
"pm_score": 2,
"selected": false,
"text": "<p>Some of the solutions like:</p>\n<pre class=\"lang-py prettyprint-override\"><code>fg = lambda text, color: "\\33[38;5;" + str(color) + "m" + text + "\\33[0m"\nbg = lambda text, color: "\\33[48;5;" + str(color) + "m" + text + "\\33[0m"\n\ndef print_six(row, format, end="\\n"):\n for col in range(6):\n color = row*6 + col - 2\n if color>=0:\n text = "{:3d}".format(color)\n print (format(text,color), end=" ")\n else:\n print(end=" ") # Four spaces\n print(end=end)\n\nfor row in range(0, 43):\n print_six(row, fg, " ")\n print_six(row, bg)\n\nprint(fg("text", 160))\n\n</code></pre>\n<p><strong>OR</strong></p>\n<pre class=\"lang-py prettyprint-override\"><code>def colored(r, g, b, text):\n return "\\033[38;2;{};{};{}m{} \\033[38;2;255;255;255m".format(r, g, b, text)\n\n\ntext = 'Hello, World!'\ncolored_text = colored(255, 0, 0, text)\nprint(colored_text)\n\n</code></pre>\n<p><strong>OR</strong></p>\n<pre class=\"lang-py prettyprint-override\"><code>class Color:\n COLOR = [f"\\33[{i}m" for i in range(44)]\n\nfor i in range(44):\n print(Color.COLOR[i] + 'text')\n\n</code></pre>\n<p><strong>might not work</strong> on Windows 10 terminals or PowerShell windows or their might be other cases where these might not work directly.</p>\n<p>But on inserting, these two small lines at the beginning of the program might help:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import os\nos.system('')\n</code></pre>\n<p><code>os.system('')</code> allows you to print ANSI codes in the Terminal which colors your output according to your choice (but there can be other system specific functions that you might need to call, to be able to print colored text in terminal).</p>\n"
},
{
"answer_id": 65475628,
"author": "Proud",
"author_id": 13877426,
"author_profile": "https://Stackoverflow.com/users/13877426",
"pm_score": 2,
"selected": false,
"text": "<pre class=\"lang-py prettyprint-override\"><code>print("\\033[1;32;40m Bright Green \\n")\n</code></pre>\n<p><img src=\"https://i.stack.imgur.com/esbQu.png\" alt=\"1\" /></p>\n"
},
{
"answer_id": 66780271,
"author": "Benyamin Jafari - aGn",
"author_id": 3702377,
"author_profile": "https://Stackoverflow.com/users/3702377",
"pm_score": 3,
"selected": false,
"text": "<p>If you want to use just built-in packages, follow this structure:</p>\n<p>Actually, I enhanced the <a href=\"https://stackoverflow.com/a/17064509/3702377\">Mohamed Samy</a> answer which is now responsible for multiple inputs as well as numbers. Also, it supports other <code>print()</code> arguments such as <code>end=</code>. Additionally, I added a <code>.store()</code> method in order to write down logs into a file as well.</p>\n<p>You can create a utility to use that anywhere into your codes:</p>\n<pre class=\"lang-py prettyprint-override\"><code># utility.py\n\nfrom datetime import datetime\n\nclass ColoredPrint:\n def __init__(self):\n self.PINK = '\\033[95m'\n self.OKBLUE = '\\033[94m'\n self.OKGREEN = '\\033[92m'\n self.WARNING = '\\033[93m'\n self.FAIL = '\\033[91m'\n self.ENDC = '\\033[0m'\n\n def disable(self):\n self.PINK = ''\n self.OKBLUE = ''\n self.OKGREEN = ''\n self.WARNING = ''\n self.FAIL = ''\n self.ENDC = ''\n\n def store(self):\n date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")\n with open('logfile.log', mode='a') as file_:\n file_.write(f"{self.msg} -- {date}")\n file_.write("\\n")\n\n def success(self, *args, **kwargs):\n self.msg = ' '.join(map(str, args))\n print(self.OKGREEN + self.msg + self.ENDC, **kwargs)\n return self\n\n def info(self, *args, **kwargs):\n self.msg = ' '.join(map(str, args))\n print(self.OKBLUE + self.msg + self.ENDC, **kwargs)\n return self\n\n def warn(self, *args, **kwargs):\n self.msg = ' '.join(map(str, args))\n print(self.WARNING + self.msg + self.ENDC, **kwargs)\n return self\n\n def err(self, *args, **kwargs):\n self.msg = ' '.join(map(str, args))\n print(self.FAIL + self.msg + self.ENDC, **kwargs)\n return self\n\n def pink(self, *args, **kwargs):\n self.msg = ' '.join(map(str, args))\n print(self.PINK + self.msg + self.ENDC, **kwargs)\n return self\n</code></pre>\n<p>e.g.</p>\n<pre class=\"lang-py prettyprint-override\"><code>from utility import ColoredPrint\n\nlog = ColoredPrint()\n\nlog.success("Hello" , 123, "Bye").store()\nlog.info("Hello" , 123, "Bye")\nlog.warn("Hello" , 123, "Bye")\nlog.err("Hello" , 123, "Bye").store()\nlog.pink("Hello" , 123, "Bye")\n</code></pre>\n<p>Out:</p>\n<p><a href=\"https://i.stack.imgur.com/HMVP6.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/HMVP6.png\" alt=\"enter image description here\" /></a></p>\n<hr />\n<p>[UPDATE]:</p>\n<p>Now, its PyPI <a href=\"https://github.com/agn-7/colored-print\" rel=\"noreferrer\">package</a> is available:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>pip install python-colored-print\n</code></pre>\n"
},
{
"answer_id": 68132906,
"author": "Life is complex",
"author_id": 6083423,
"author_profile": "https://Stackoverflow.com/users/6083423",
"pm_score": 2,
"selected": false,
"text": "<p>This answer attempts to expand the concept of writing colorized text to the terminal by using a <em>regular expression</em> to colorize keywords in a block of text.</p>\n<p>This answer also use the <em>Python</em> library <a href=\"https://github.com/willmcgugan/rich\" rel=\"nofollow noreferrer\">Rich</a>, which was briefly covered in a previous answer to this question. In this answer I use the function <em>rich.color.ANSI_COLOR_NAMES</em> to obtain a random list of colors that will be used to highlight predefined search terms.</p>\n<pre><code>import random\nimport re as regex\nfrom rich import color\nfrom rich import print\n\n\ndef create_dynamic_regex(search_words):\n """\n This function is used to create a dynamic regular expression\n string and a list of random colors. Both these elements will\n be used in the function colorize_text()\n\n :param search_words: list of search terms\n :return: regular expression search string and a list of colors\n :rtype: string, list\n """\n colors_required = create_list_of_colors(len(search_words))\n number_of_search_words = len(search_words)\n combined_string = ''\n for search_word in search_words:\n number_of_search_words -= 1\n if number_of_search_words != 0:\n current_string = ''.join(r'(\\b' + search_word + r'\\b)|')\n combined_string = (combined_string + current_string)\n elif number_of_search_words == 0:\n current_string = ''.join(r'(\\b' + search_word + r'\\b)')\n combined_string = (combined_string + current_string)\n return combined_string, colors_required\n\n\ndef random_color():\n """\n This function is used to create a random color using the\n Python package rich.\n :return: color name\n :rtype: string\n """\n selected_color = random.choice(list(color.ANSI_COLOR_NAMES.keys()))\n return selected_color\n\n\ndef create_list_of_colors(number_of_colors):\n """\n This function is used to generate a list of colors,\n which will be used in the function colorize_text()\n :param number_of_colors:\n :return: list of colors\n :rtype: list\n """\n list_of_colors = [random_color() for _ in range(number_of_colors)]\n return list_of_colors\n\n\ndef colorize_text(text, regex_string, array_of_colors):\n """\n This function is used to colorize specific words in a text string.\n :param text: text string potentially containing specific words to colorize.\n :param regex_string: regular expression search string\n :param array_of_colors: list of colors\n :return: colorized text\n :rtype: string\n """\n available_colors = array_of_colors\n word_regex = regex.compile(f"{regex_string}", regex.IGNORECASE)\n i = 0\n output = ""\n for word in word_regex.finditer(text):\n get_color = available_colors[word.lastindex - 1]\n output += "".join([text[i:word.start()],\n "[%s]" % available_colors[word.lastindex - 1],\n text[word.start():word.end()], "[/%s]" % available_colors[word.lastindex - 1]])\n i = word.end()\n return ''.join([output, text[word.end():]])\n\n\ndef generate_console_output(text_to_search, words_to_find):\n """\n This function is used generate colorized text that will\n be outputting to the console.\n\n :param text_to_search: text string potentially containing specific words to colorize.\n :param words_to_find: list of search terms.\n :return: A string containing colorized words.\n :rtype: string\n """\n search_terms, colors = create_dynamic_regex(words_to_find)\n colorize_html = colorize_text(text_to_search, search_terms, colors)\n print(colorize_html)\n\n\ntext = "The dog chased the cat that was looking for the mouse that the dog was playing with."\nwords = ['dog', 'cat', 'mouse']\ngenerate_console_output(text, words)\n</code></pre>\n<p>Here is the print output from the code above:</p>\n<p><a href=\"https://i.stack.imgur.com/Z3qX4.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Z3qX4.png\" alt=\"enter image description here\" /></a></p>\n<p>I created two GISTs for colorizing text.</p>\n<ul>\n<li><a href=\"https://gist.github.com/johnbumgarner/035fd1dda6044a03cefca0ea1d66fbec\" rel=\"nofollow noreferrer\">colorized text terminal output</a></li>\n<li><a href=\"https://gist.github.com/johnbumgarner/5f7139b00bff22d9faa6a2badcc824fe#file-colorize_keywords_in_text_html_output-py\" rel=\"nofollow noreferrer\">colorized text HTML output</a></li>\n</ul>\n"
},
{
"answer_id": 68428529,
"author": "bluenote10",
"author_id": 1804173,
"author_profile": "https://Stackoverflow.com/users/1804173",
"pm_score": 5,
"selected": false,
"text": "<p>Here is my modern (2021) solution: <a href=\"https://github.com/bluenote10/yachalk\" rel=\"nofollow noreferrer\">yachalk</a></p>\n<p>It is one of the few libraries that properly supports nested styles:</p>\n<p><a href=\"https://i.stack.imgur.com/piYe5.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/piYe5.png\" alt=\"enter image description here\" /></a></p>\n<p>Apart from that yachalk is auto-complete-friendly, has 256/truecolor support, comes with terminal-capability detection, and is fully typed.</p>\n<p>Here are some design decision you may consider for choosing your solution.</p>\n<h2>High-level libraries vs low-level libraries / manual style handling?</h2>\n<p>Many answers to this question demonstrate how to ANSI escape codes directly, or suggest low-level libraries that require manual style enabling/disabling.</p>\n<p>These approaches have subtle issues: Inserting on/off styles manually is</p>\n<ul>\n<li>more verbose syntactically, because resets have to be specified explicitly,</li>\n<li>more error prone, because you can accidentally forget to reset a style,</li>\n<li>fails to get edge cases right: For instance in some terminals it is necessary to reset styles before newlines, and re-activate them after the line break. Also, some terminal have problems with simply overriding mutually exclusive styles, and require inserting "unnecessary" reset codes. If a developer's local terminal doesn't have these quirks, the developer will not discover these quirks immediately. The issue will only be reported later by others or cause problems e.g. on CI terminals.</li>\n</ul>\n<p>Therefore if compatibility with many terminals is a goal, it's best to use a high-level library that offers automatic handling of style resets. This allows the library to take care of all edge cases by inserting the "spurious" ANSI escape codes where needed.</p>\n<h2>Why yet another library?</h2>\n<p>In JavaScript the de-facto standard library for the task is <a href=\"https://github.com/chalk/chalk\" rel=\"nofollow noreferrer\">chalk</a>, and after using it for a while in JS projects, the solutions available in the Python world were lacking in comparison. Not only is the chalk API more convenient to use (fully auto-complete compatible), it also gets all the edge cases right.</p>\n<p>The idea of <a href=\"https://github.com/bluenote10/yachalk\" rel=\"nofollow noreferrer\">yachalk</a> is to bring the same convenience to the Python ecosystem. If you're interested in a comparison to other libraries I've started <a href=\"https://github.com/bluenote10/yachalk#prior-art-why-yet-another-chalk-clone\" rel=\"nofollow noreferrer\">feature comparison</a> on the projects page. In addition, here is a long (but still incomplete) list of alternatives that came up during my research -- a lot to choose from :)</p>\n<ul>\n<li><a href=\"https://pypi.org/project/colored/\" rel=\"nofollow noreferrer\">colored</a></li>\n<li><a href=\"https://pypi.org/project/ansicolors/\" rel=\"nofollow noreferrer\">ansicolors</a></li>\n<li><a href=\"https://pypi.org/project/termcolor/\" rel=\"nofollow noreferrer\">termcolor</a></li>\n<li><a href=\"https://pypi.org/project/colorama/\" rel=\"nofollow noreferrer\">colorama</a></li>\n<li><a href=\"https://pypi.org/project/sty/\" rel=\"nofollow noreferrer\">sty</a></li>\n<li><a href=\"https://pypi.org/project/blessings/\" rel=\"nofollow noreferrer\">blessings</a></li>\n<li><a href=\"https://pypi.org/project/rich/\" rel=\"nofollow noreferrer\">rich</a></li>\n<li><a href=\"https://pypi.org/project/colorit/\" rel=\"nofollow noreferrer\">colorit</a></li>\n<li><a href=\"https://pypi.org/project/colorprint/\" rel=\"nofollow noreferrer\">colorprint</a></li>\n<li><a href=\"https://pypi.org/project/console-color/\" rel=\"nofollow noreferrer\">console-color</a></li>\n<li><a href=\"https://pypi.org/project/pyfancy/\" rel=\"nofollow noreferrer\">pyfance</a></li>\n<li><a href=\"https://pypi.org/project/couleur/\" rel=\"nofollow noreferrer\">couleur</a></li>\n<li><a href=\"https://github.com/lmittmann/style\" rel=\"nofollow noreferrer\">style</a> (formerly known as clr)</li>\n<li><a href=\"https://github.com/anthonyalmarza/chalk\" rel=\"nofollow noreferrer\">pychalk</a></li>\n<li><a href=\"https://pypi.org/project/simple-chalk/\" rel=\"nofollow noreferrer\">simple-chalk</a></li>\n<li><a href=\"https://pypi.org/project/chlk/\" rel=\"nofollow noreferrer\">chlk</a></li>\n<li><a href=\"https://pypi.org/project/chalky/\" rel=\"nofollow noreferrer\">chalky</a></li>\n<li><a href=\"https://pypi.org/project/constyle\" rel=\"nofollow noreferrer\">constyle</a></li>\n</ul>\n"
},
{
"answer_id": 68748316,
"author": "ToTamire",
"author_id": 15964568,
"author_profile": "https://Stackoverflow.com/users/15964568",
"pm_score": 3,
"selected": false,
"text": "<p>I was moved there by google when I was looking how to color logs so:</p>\n<h1>coloredlogs</h1>\n<h2>Instalation</h2>\n<pre><code>pip install coloredlogs\n</code></pre>\n<h2>Usage</h2>\n<h5>Minimal usage:</h5>\n<pre class=\"lang-python prettyprint-override\"><code>import logging\nimport coloredlogs\n\ncoloredlogs.install() # install a handler on the root logger\n\nlogging.debug('message with level debug')\nlogging.info('message with level info')\nlogging.warning('message with level warning')\nlogging.error('message with level error')\nlogging.critical('message with level critical')\n</code></pre>\n<p>Results with:\n<a href=\"https://i.stack.imgur.com/A1axw.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/A1axw.png\" alt=\"minimal usage\" /></a></p>\n<h5>Start from message level debug:</h5>\n<pre class=\"lang-python prettyprint-override\"><code>import logging\nimport coloredlogs\n\ncoloredlogs.install(level='DEBUG') # install a handler on the root logger with level debug\n\nlogging.debug('message with level debug')\nlogging.info('message with level info')\nlogging.warning('message with level warning')\nlogging.error('message with level error')\nlogging.critical('message with level critical')\n</code></pre>\n<p>Results with:\n<a href=\"https://i.stack.imgur.com/S3AAi.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/S3AAi.png\" alt=\"debug level\" /></a></p>\n<h5>Hide messages from libraries:</h5>\n<pre class=\"lang-python prettyprint-override\"><code>import logging\nimport coloredlogs\n\nlogger = logging.getLogger(__name__) # get a specific logger object\ncoloredlogs.install(level='DEBUG') # install a handler on the root logger with level debug\ncoloredlogs.install(level='DEBUG', logger=logger) # pass a specific logger object\n\nlogging.debug('message with level debug')\nlogging.info('message with level info')\nlogging.warning('message with level warning')\nlogging.error('message with level error')\nlogging.critical('message with level critical')\n</code></pre>\n<p>Results with:\n<a href=\"https://i.stack.imgur.com/S3AAi.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/S3AAi.png\" alt=\"debug level\" /></a></p>\n<h5>Format log messages:</h5>\n<pre class=\"lang-python prettyprint-override\"><code>import logging\nimport coloredlogs\n\nlogger = logging.getLogger(__name__) # get a specific logger object\ncoloredlogs.install(level='DEBUG') # install a handler on the root logger with level debug\ncoloredlogs.install(level='DEBUG', logger=logger) # pass a specific logger object\ncoloredlogs.install(\n level='DEBUG', logger=logger,\n fmt='%(asctime)s.%(msecs)03d %(filename)s:%(lineno)d %(levelname)s %(message)s'\n)\n\nlogging.debug('message with level debug')\nlogging.info('message with level info')\nlogging.warning('message with level warning')\nlogging.error('message with level error')\nlogging.critical('message with level critical')\n</code></pre>\n<p>Results with:\n<a href=\"https://i.stack.imgur.com/0aBWR.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/0aBWR.png\" alt=\"format log messages\" /></a></p>\n<h5>Available format attributes:</h5>\n<ul>\n<li><code>%(asctime)s</code> - Time as human-readable string, when logging call was issued</li>\n<li><code>%(created)f</code> - Time as float when logging call was issued</li>\n<li><code>%(filename)s</code> - File name</li>\n<li><code>%(funcName)s</code> - Name of function containing the logging call</li>\n<li><code>%(hostname)s</code> - System hostname</li>\n<li><code>%(levelname)s</code> - Text logging level</li>\n<li><code>%(levelno)s</code> - Integer logging level</li>\n<li><code>%(lineno)d</code> - Line number where the logging call was issued</li>\n<li><code>%(message)s</code> - Message passed to logging call (same as <code>%(msg)s</code>)</li>\n<li><code>%(module)s</code> - File name without extension where the logging call was issued</li>\n<li><code>%(msecs)d</code> - Millisecond part of the time when logging call was issued</li>\n<li><code>%(msg)s</code> - Message passed to logging call (same as <code>%(message)s</code>)</li>\n<li><code>%(name)s</code> - Logger name</li>\n<li><code>%(pathname)s</code> - Full pathname to file containing the logging call</li>\n<li><code>%(process)d</code> - Process ID</li>\n<li><code>%(processName)s</code> - Process name</li>\n<li><code>%(programname)s</code> - System programname</li>\n<li><code>%(relativeCreated)d</code> - Time as integer in milliseconds when logging call was issued, relative to the time when logging module was loaded</li>\n<li><code>%(thread)d</code> - Thread ID</li>\n<li><code>%(threadName)s</code> - Thread name</li>\n<li><code>%(username)s</code> - System username</li>\n</ul>\n<h2>Sources:</h2>\n<p><a href=\"https://pypi.org/project/coloredlogs/\" rel=\"noreferrer\">Coloredlogs package</a></p>\n<p><a href=\"https://docs.python.org/3/library/logging.html#logrecord-attributes\" rel=\"noreferrer\">Logging library</a></p>\n"
},
{
"answer_id": 69050278,
"author": "Sylvester Kruin",
"author_id": 16775594,
"author_profile": "https://Stackoverflow.com/users/16775594",
"pm_score": 2,
"selected": false,
"text": "<p>You could use the <code>pygments</code> module to do this. For example:</p>\n<pre><code>from pygments import console\nprint(pygments.console.colorize("red", "This text is red."))\n</code></pre>\n<p>This doesn't allow you to provide a hexadecimal color for the terminal, but there are many built-in colors that you can try, like "blue", "darkgreen", "yellow", etc.</p>\n"
},
{
"answer_id": 70599663,
"author": "Vinod Srivastav",
"author_id": 3057246,
"author_profile": "https://Stackoverflow.com/users/3057246",
"pm_score": 3,
"selected": false,
"text": "<p>In <strong>windows 10</strong> you can try this tiny script, which works as a color mixer with values from 0-255 for Red, Green and blue:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import os\n\nos.system('')\n\n\ndef RGB(red=None, green=None, blue=None,bg=False):\n if(bg==False and red!=None and green!=None and blue!=None):\n return f'\\u001b[38;2;{red};{green};{blue}m'\n elif(bg==True and red!=None and green!=None and blue!=None):\n return f'\\u001b[48;2;{red};{green};{blue}m'\n elif(red==None and green==None and blue==None):\n return '\\u001b[0m'\n</code></pre>\n<p>and call the RGB function to make any combination of colors as:</p>\n<pre class=\"lang-py prettyprint-override\"><code>g0 = RGB()\ng1 = RGB(0,255,0)\ng2 = RGB(0,100,0,True)+""+RGB(100,255,100)\ng3 = RGB(0,255,0,True)+""+RGB(0,50,0)\n\nprint(f"{g1}green1{g0}")\nprint(f"{g2}green2{g0}")\nprint(f"{g3}green3{g0}")\n</code></pre>\n<p><code>RGB()</code> with no parameter will cleanup and set the <strong>foreground/background</strong> color to <strong>default</strong>. In case you want <strong>black</strong> you should call it as <code>RGB(0,0,0)</code> and for <strong>white</strong> <code>RGB(255,255,255)</code>. While <code>RGB(0,255,0)</code> creates <strong>absolute green</strong> <code>RGB(150,255,150)</code> will produce <strong>light green</strong>.</p>\n<p>This supports <strong>background</strong> & <strong>foreground</strong> color, to set the color as <strong>background color</strong> you must pass it with <code>bg=True</code> which is <code>False</code> by default.</p>\n<p>For Example: To set <strong>red</strong> as the <strong>background color</strong> it should be called as <code>RGB(255,0,0,True)</code> but to choose <strong>red</strong> as <strong>font color</strong> just call it as <code>RGB(255,0,0,False)</code> since <code>bg</code> is by default <code>False</code> this simplifies to just call it as <code>RGB(255,0,0)</code></p>\n"
},
{
"answer_id": 72752520,
"author": "Abhijeet",
"author_id": 18522747,
"author_profile": "https://Stackoverflow.com/users/18522747",
"pm_score": 3,
"selected": false,
"text": "<p>The <strong>simplest</strong> and <strong>convenient</strong> way of doing this, considering if you're writing a command-line tool.\nThis method will work anywhere on all consoles, without installing any fancy packages.</p>\n<p>To get the ANSI codes working on <strong>Windows</strong>, first, run <code>os.system('color')</code></p>\n<pre><code>import os\nos.system('color')\n\nCOLOR = '\\033[91m' # change it, according to the color need\n\nEND = '\\033[0m'\n\nprint(COLOR + "Hello World" + END) #print a message\n\n\nexit=input() #to avoid closing the terminal windows\n</code></pre>\n<br/>\n<br/>\n<p><strong>For more colours</strong> :<br/></p>\n<p><a href=\"https://i.stack.imgur.com/7xsyK.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/7xsyK.png\" alt=\"enter image description here\" /></a></p>\n<p>Note: \\33[5m and \\33[6m are blinking.</p>\n<p>Thanks to @qubodup</p>\n"
},
{
"answer_id": 72768499,
"author": "catwith",
"author_id": 13651701,
"author_profile": "https://Stackoverflow.com/users/13651701",
"pm_score": 2,
"selected": false,
"text": "<p>Minimal Class:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class log:\n f = lambda color: lambda string: print(color + string + "\\33[0m")\n\n black = f("\\33[30m")\n red = f("\\33[31m")\n green = f("\\33[32m")\n yellow = f("\\33[33m")\n blue = f("\\33[34m")\n magenta = f("\\33[35m")\n cyan = f("\\33[36m")\n white = f("\\33[37m")\n\n# Usage\nlog.blue("Blue World!")\n</code></pre>\n"
},
{
"answer_id": 73036565,
"author": "CPP_is_no_STANDARD",
"author_id": 18032104,
"author_profile": "https://Stackoverflow.com/users/18032104",
"pm_score": 2,
"selected": false,
"text": "<p>There is a more efficient way here.</p>\n<pre><code># Colours\npure_red = "\\033[0;31m"\ndark_green = "\\033[0;32m"\norange = "\\033[0;33m"\ndark_blue = "\\033[0;34m"\nbright_purple = "\\033[0;35m"\ndark_cyan = "\\033[0;36m"\ndull_white = "\\033[0;37m"\npure_black = "\\033[0;30m"\nbright_red = "\\033[0;91m"\nlight_green = "\\033[0;92m"\nyellow = "\\033[0;93m"\nbright_blue = "\\033[0;94m"\nmagenta = "\\033[0;95m"\nlight_cyan = "\\033[0;96m"\nbright_black = "\\033[0;90m"\nbright_white = "\\033[0;97m"\ncyan_back = "\\033[0;46m"\npurple_back = "\\033[0;45m"\nwhite_back = "\\033[0;47m"\nblue_back = "\\033[0;44m"\norange_back = "\\033[0;43m"\ngreen_back = "\\033[0;42m"\npink_back = "\\033[0;41m"\ngrey_back = "\\033[0;40m"\ngrey = '\\033[38;4;236m'\nbold = "\\033[1m"\nunderline = "\\033[4m"\nitalic = "\\033[3m"\ndarken = "\\033[2m"\ninvisible = '\\033[08m'\nreverse_colour = '\\033[07m'\nreset_colour = '\\033[0m'\ngrey = "\\x1b[90m"\n</code></pre>\n<h3>User Manual</h3>\n<ul>\n<li><p><code>reverse_colour</code> means that you reverse the colour that you just chose but in highlight mode (default is white).</p>\n</li>\n<li><p><code>pink_back</code> (<code>green_back</code> etc... those with back) means that it is highlighted in pink (based on the name).</p>\n</li>\n<li><p><code>reset_colour</code> resets the colour (see picture 1 for more details).</p>\n</li>\n</ul>\n<p>I believe I don't need to explain much more as it is listed at the <em>variable name</em>.</p>\n<p>If you wish to try the code, please go to <a href=\"http://www.replit.com\" rel=\"nofollow noreferrer\">replit</a> IDE to test the code. The sample code is <a href=\"https://replit.com/@indexaker/Trial#main.py\" rel=\"nofollow noreferrer\">here</a></p>\n<hr>\n<p>Code (Picture 1):</p>\n<p><a href=\"https://i.stack.imgur.com/7hifz.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/7hifz.png\" alt=\"My coding\" /></a></p>\n<p>Output (Picture 2):</p>\n<p><a href=\"https://i.stack.imgur.com/E652Q.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/E652Q.png\" alt=\"Code output\" /></a></p>\n"
},
{
"answer_id": 73158800,
"author": "Nazime Lakehal",
"author_id": 7730121,
"author_profile": "https://Stackoverflow.com/users/7730121",
"pm_score": 0,
"selected": false,
"text": "<p>I wrote a library which is available on PyPI, with a simple API that follows the standard print function.</p>\n<p>You can install it with <code>pip install coloring</code>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>import coloring\n\n# Directly use print-like functions\ncoloring.print_red('Hello', 12)\ncoloring.print_green('Hey', end="", sep=";")\nprint()\n\n# Get str as return\nprint(coloring.red('hello'))\n\n# Use the generic colorize function\nprint(coloring.colorize("I'm red", "red")) # Using color names\nprint(coloring.colorize("I'm green", (0, 255, 0))) # Using RGB colors\nprint(coloring.colorize("I'm blue", "#0000ff")) # Using hex colors\n\n# Or using styles (underline, bold, italic, ...)\nprint(coloring.colorize('Hello', 'red', s='ub')) # underline and bold\n\n</code></pre>\n<p>Executed code:</p>\n<p><a href=\"https://i.stack.imgur.com/4lCwT.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/4lCwT.png\" alt=\"enter image description here\" /></a></p>\n<p>You can check all the features here: <a href=\"https://github.com/Nazime/coloring\" rel=\"nofollow noreferrer\">https://github.com/Nazime/coloring</a>.</p>\n"
},
{
"answer_id": 73917459,
"author": "stackunderflow",
"author_id": 1436741,
"author_profile": "https://Stackoverflow.com/users/1436741",
"pm_score": 2,
"selected": false,
"text": "<p>as a fan of the RGB standard, I would do it like this:</p>\n<pre><code>def color_text(text, rgb):\n r, g, b = rgb\n return f"\\033[38;2;{r};{g};{b}m{text}\\033[0m"\n\nclass rgb():\n BLACK = (0, 0, 0)\n RED = (255, 0, 0)\n GREEN = (0, 255, 0)\n BLUE = (0, 0, 255)\n YELLOW = (255, 255, 0)\n # and so on ...\n\nprint(color_text("hello colored world", rgb.GREEN))\n</code></pre>\n<p><em>PS: strongly inspired by CircuitSacul's answer</em></p>\n"
},
{
"answer_id": 74238803,
"author": "BML",
"author_id": 5531578,
"author_profile": "https://Stackoverflow.com/users/5531578",
"pm_score": 0,
"selected": false,
"text": "<pre><code>class ColorText:\n """\n Use ANSI escape sequences to print colors +/- bold/underline to bash terminal.\n\n Examples\n --------\n >>> ColorText('HelloWorld').bold()\n >>> ColorText('HelloWorld').blue()\n >>> ColorText('HelloWorld').bold().custom("#bebebe")\n >>> ColorText('HelloWorld').underline().custom('dodgerblue')\n >>> ColorText.demo()\n\n Notes\n -----\n - execute ColorText.demo() for a printout of colors.\n """\n\n @classmethod\n def demo(cls):\n """Prints examples of all colors in normal, bold, underline, bold+underline."""\n for color in dir(ColorText):\n if all([color.startswith("_") is False,\n color not in ["bold", "underline", "demo", "custom"],\n callable(getattr(ColorText, color))]):\n print(getattr(ColorText(color), color)(),\n "\\t",\n getattr(ColorText(f"bold {color}").bold(), color)(),\n "\\t",\n getattr(ColorText(f"underline {color}").underline(), color)(),\n "\\t",\n getattr(ColorText(f"bold underline {color}").underline().bold(), color)())\n print(ColorText("Input can also be color hex or R,G,B with ColorText.custom()").bold())\n pass\n\n def __init__(self, text: str = ""):\n self.text = text\n self.ending = "\\033[0m"\n self.colors = []\n pass\n\n def __repr__(self):\n return self.text\n\n def __str__(self):\n return self.text\n\n def bold(self):\n self.text = "\\033[1m" + self.text + self.ending\n return self\n\n def underline(self):\n self.text = "\\033[4m" + self.text + self.ending\n return self\n\n def green(self):\n self.text = "\\033[92m" + self.text + self.ending\n self.colors.append("green")\n return self\n\n def purple(self):\n self.text = "\\033[95m" + self.text + self.ending\n self.colors.append("purple")\n return self\n\n def blue(self):\n self.text = "\\033[94m" + self.text + self.ending\n self.colors.append("blue")\n return self\n\n def ltblue(self):\n self.text = "\\033[34m" + self.text + self.ending\n self.colors.append("lightblue")\n return self\n\n def pink(self):\n self.text = "\\033[35m" + self.text + self.ending\n self.colors.append("pink")\n return self\n\n def gray(self):\n self.text = "\\033[30m" + self.text + self.ending\n self.colors.append("gray")\n return self\n\n def ltgray(self):\n self.text = "\\033[37m" + self.text + self.ending\n self.colors.append("ltgray")\n return self\n\n def warn(self):\n self.text = "\\033[93m" + self.text + self.ending\n self.colors.append("yellow")\n return self\n\n def fail(self):\n self.text = "\\033[91m" + self.text + self.ending\n self.colors.append("red")\n return self\n\n def ltred(self):\n self.text = "\\033[31m" + self.text + self.ending\n self.colors.append("lightred")\n return self\n\n def cyan(self):\n self.text = "\\033[36m" + self.text + self.ending\n self.colors.append("cyan")\n return self\n\n def custom(self, *color_hex):\n """Print in custom color, `color_hex` - either actual hex, or tuple(r,g,b)"""\n if color_hex != (None, ): # allows printing white on black background, black otherwise\n if len(color_hex) == 1:\n c = rgb2hex(colorConverter.to_rgb(color_hex[0]))\n rgb = ImageColor.getcolor(c, "RGB")\n else:\n assert (\n len(color_hex) == 3\n ), "If not a color hex, ColorText.custom should have R,G,B as input"\n rgb = color_hex\n self.text = "\\033[{};2;{};{};{}m".format(38, *rgb) + self.text + self.ending\n self.colors.append(rgb)\n return self\n\n pass\n</code></pre>\n"
},
{
"answer_id": 74439656,
"author": "Tim",
"author_id": 371122,
"author_profile": "https://Stackoverflow.com/users/371122",
"pm_score": 0,
"selected": false,
"text": "<p>Here's an implementation that you can use like this:</p>\n<pre><code>from stryle import Stryle\n\nprint(Stryle.okgreen.bold@"Hello World" + Stryle.underline@'!' + ' back to normal')\nprint(f"{Stryle.red}Merry {Stryle.underline.okgreen}Christmas!{Stryle.off}")\nprint("Merry "@Stryle.red + "Christmas"@Stryle.okgreen.underline)\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/LWIFA.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/LWIFA.png\" alt=\"enter image description here\" /></a></p>\n<pre><code>_decorations = {\n "header" : '\\033[95m',\n "okblue" : '\\033[94m',\n "okcyan" : '\\033[96m',\n "okgreen" : '\\033[92m',\n "yellow" : '\\033[93m',\n "red" : '\\033[91m',\n "warning" : '\\033[93m',\n "fail" : '\\033[91m',\n "off" : '\\033[0m',\n "bold" : '\\033[1m',\n "underline" : '\\033[4m',\n}\n\nclass _StringStyle(str):\n def __getattribute__(self, decoration: str = _decorations["off"]):\n if decoration in _decorations:\n return _StringStyle(self.decorations + _decorations[decoration])\n return self\n def __matmul__(self, other):\n return self.decorations + str(other) + _decorations["off"]\n def __rmatmul__(self, other):\n return self.decorations + str(other) + _decorations["off"]\n def __str__(self):\n return self.decorations\n\nStryle = _StringStyle()\n</code></pre>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/287871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35062/"
] |
How do I output colored text to the terminal in Python?
|
This somewhat depends on what platform you are on. The most common way to do this is by printing ANSI escape sequences. For a simple example, here's some Python code from the [Blender build scripts](https://svn.blender.org/svnroot/bf-blender/trunk/blender/build_files/scons/tools/bcolors.py):
```
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
```
To use code like this, you can do something like:
```
print(bcolors.WARNING + "Warning: No active frommets remain. Continue?" + bcolors.ENDC)
```
Or, with Python 3.6+:
```
print(f"{bcolors.WARNING}Warning: No active frommets remain. Continue?{bcolors.ENDC}")
```
This will work on unixes including OS X, Linux and Windows (provided you use [ANSICON](https://github.com/adoxa/ansicon), or in Windows 10 provided you enable [VT100 emulation](https://msdn.microsoft.com/en-us/library/mt638032)). There are ANSI codes for setting the color, moving the cursor, and more.
If you are going to get complicated with this (and it sounds like you are if you are writing a game), you should look into the "[curses](https://en.wikipedia.org/wiki/Curses_%28programming_library%29)" module, which handles a lot of the complicated parts of this for you. The [Python Curses HowTO](http://docs.python.org/howto/curses.html "Python Curses howto") is a good introduction.
If you are not using extended ASCII (i.e., not on a PC), you are stuck with the ASCII characters below 127, and '#' or '@' is probably your best bet for a block. If you can ensure your terminal is using a IBM [extended ASCII character set](http://telecom.tbi.net/asc-ibm.html), you have many more options. Characters 176, 177, 178 and 219 are the "block characters".
Some modern text-based programs, such as "Dwarf Fortress", emulate text mode in a graphical mode, and use images of the classic PC font. You can find some of these bitmaps that you can use on the [Dwarf Fortress Wiki](http://dwarffortresswiki.org/DF2014:Tilesets) see ([user-made tilesets](http://dwarffortresswiki.org/Tileset_repository)).
The [Text Mode Demo Contest](http://en.wikipedia.org/wiki/TMDC "text mode demo contest") has more resources for doing graphics in text mode.
|
287,875 |
<p>I'm trying to come up with a reusable JS or jQuery function that would allow me to test if one object is a DOM descendant of another. </p>
<p>I've seen a model of testing for </p>
<pre><code>$b.parents('nodename').length>0
</code></pre>
<p>Which is fantastic when you only need to check if an element is a child of any node by that name.</p>
<p>But what about a specific node? You can't test</p>
<pre><code>$b.parents($a).length>0
</code></pre>
<p>Because jQuery parents takes a nodename expression as an argument to filter.</p>
<p>As a little background, I'm trying to test if a document click event's target is a child of a specific object. For instance, if the event.target is a child of $b, return true, otherwise, return false. But this function could have other implications later on.</p>
<p>Thanks!</p>
|
[
{
"answer_id": 287889,
"author": "picardo",
"author_id": 32816,
"author_profile": "https://Stackoverflow.com/users/32816",
"pm_score": 2,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>$('#foo').filter(function(){\n\n return $(this).parent().is('#foo-parent');\n\n});\n</code></pre>\n\n<p>So here we are selecting all the foo elements and then filtering only the elements that have the foo-parent as their immediate parent. </p>\n\n<p>If you are looking to find if the any of the ancestors of the current object comply to the rule, then I guess it should be:</p>\n\n<pre><code>$('#foo').filter(function(){\n\n return $(this).parents().is('#foo-parent');\n\n});\n</code></pre>\n"
},
{
"answer_id": 287923,
"author": "Gareth",
"author_id": 31582,
"author_profile": "https://Stackoverflow.com/users/31582",
"pm_score": 5,
"selected": true,
"text": "<p>In <a href=\"https://stackoverflow.com/questions/245241/jquery-ancestors-using-jquery-objects#245266\">jQuery ancestors using jQuery objects</a> I suggested</p>\n\n<pre><code>if ($(obj1).parents().index($(obj2)) >= 0) {\n // obj1 is a descendant of obj2\n}\n</code></pre>\n"
},
{
"answer_id": 13588053,
"author": "Alexey Lebedev",
"author_id": 8338,
"author_profile": "https://Stackoverflow.com/users/8338",
"pm_score": 5,
"selected": false,
"text": "<pre><code>a.contains(b)\n</code></pre>\n\n<p>This is a pure JavaScript solution using <a href=\"https://developer.mozilla.org/en-US/docs/DOM/Node.contains\" rel=\"noreferrer\">Node.contains</a>. The function is inclusive, <code>a.contains(a)</code> evaluates to true.</p>\n\n<p>There's an edge case in IE9: if <code>b</code> is a text node, <code>contains</code> will always return false.</p>\n"
},
{
"answer_id": 71885668,
"author": "Rafael AtΓas",
"author_id": 6951887,
"author_profile": "https://Stackoverflow.com/users/6951887",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/a/13588053/6951887\">Alexey Lebedev's answer</a> did not work for me, because <code>Node.contains</code> is inclusive.</p>\n<p>If the <strong>parent element should be distinct from its possible descendant</strong> --that was my use case--, then we need a slightly different solution: we could apply <code>Node.contains</code> to the parent's direct descendants using the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/children\" rel=\"nofollow noreferrer\"><code>Element.children</code></a> property:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const sapiens = document.querySelector(\"#homo-sapiens\")\n\nconst isSapiensAnAustralopithecusDescendant = [\n ...document.querySelector(\"#australopithecus\").children\n].some(child => child?.contains(sapiens))\n\nconsole.log(isSapiensAnAustralopithecusDescendant) // true</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"australopithecus\">\n <div id=\"homo-erectus\">\n <div id=\"homo-neanderthalensis\"></div>\n <div id=\"homo-sapiens\"></div>\n </div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>In this way, <code>Node.contains</code> will compare the possible descendant to the given child and its children.</p>\n<p>Another solution could be the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/closest\" rel=\"nofollow noreferrer\"><code>Element.closest</code></a> method. However, if you use it, keep in mind that you should call it on the possible descendant because <strong><code>Element.closest</code> tells us who the ancestor of an element is</strong>.</p>\n<p>Also, the function is inclusive; hence, if you do <code>document.body.closest("body")</code>, the result will be <code>document.body</code> (<code>Element.closest</code> returns the closest element with the given selector or <code>null</code>).</p>\n<p>If your use case demands that the parent and the possible descendant be different, then we could apply <code>Element.closest</code> to the parent of the possible descendant:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const sapiens = document.querySelector(\"#homo-sapiens\");\n\nconst isAustralopithecusAnAncestorOfSapiens = sapiens.parentElement.closest(\"#australopithecus\")\n\nconsole.log(isAustralopithecusAnAncestorOfSapiens != null) // true</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"australopithecus\">\n <div id=\"homo-erectus\">\n <div id=\"homo-neanderthalensis\"></div>\n <div id=\"homo-sapiens\"></div>\n </div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/287875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37429/"
] |
I'm trying to come up with a reusable JS or jQuery function that would allow me to test if one object is a DOM descendant of another.
I've seen a model of testing for
```
$b.parents('nodename').length>0
```
Which is fantastic when you only need to check if an element is a child of any node by that name.
But what about a specific node? You can't test
```
$b.parents($a).length>0
```
Because jQuery parents takes a nodename expression as an argument to filter.
As a little background, I'm trying to test if a document click event's target is a child of a specific object. For instance, if the event.target is a child of $b, return true, otherwise, return false. But this function could have other implications later on.
Thanks!
|
In [jQuery ancestors using jQuery objects](https://stackoverflow.com/questions/245241/jquery-ancestors-using-jquery-objects#245266) I suggested
```
if ($(obj1).parents().index($(obj2)) >= 0) {
// obj1 is a descendant of obj2
}
```
|
287,899 |
<p>Can anyone think of a good solution for getting IOC into a console application?</p>
<p>At the moment we are just using a static class with the following method:</p>
<pre><code>public static T Resolve<T>()
{
return dependencyResolver.Resolve<T>();
}
</code></pre>
<p>I would like the experience to be seamless but cannot think of a way of achieving this from a console application.</p>
|
[
{
"answer_id": 287902,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 1,
"selected": false,
"text": "<p>I've used Spring.NET from a console app with no problems. You just need to point it at your config file, and it will hook up all the dependencies. What you then <em>do</em> with those objects depends on what your console app is trying to do, of course.</p>\n"
},
{
"answer_id": 287912,
"author": "Bruno Shine",
"author_id": 28294,
"author_profile": "https://Stackoverflow.com/users/28294",
"pm_score": 1,
"selected": false,
"text": "<p>Checkout Microsoft <a href=\"http://www.codeplex.com/unity\" rel=\"nofollow noreferrer\">Unity</a>.</p>\n"
},
{
"answer_id": 287915,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 2,
"selected": false,
"text": "<p>Console applications do not have any limitation over a web or form application for IoC. You can use any of your choice (Spring, Ninject, Unity, etc.). Most of them are configurable with XML file outside your console application and some like Ninjector require a configuration inside your application.</p>\n"
},
{
"answer_id": 433902,
"author": "Matt Hinze",
"author_id": 2676,
"author_profile": "https://Stackoverflow.com/users/2676",
"pm_score": 4,
"selected": true,
"text": "<p>You will have to make a service locater call (<code>Resolve<T>()</code>) somewhere. The trick is to get it as out-of-the-way as possible. For console applications this bootstrapping happens in the <code>Main()</code> method. Do it there and minimize those Resolve calls elsewhere and you'll be great. For most dependencies, use constructor injection.</p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/287899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11755/"
] |
Can anyone think of a good solution for getting IOC into a console application?
At the moment we are just using a static class with the following method:
```
public static T Resolve<T>()
{
return dependencyResolver.Resolve<T>();
}
```
I would like the experience to be seamless but cannot think of a way of achieving this from a console application.
|
You will have to make a service locater call (`Resolve<T>()`) somewhere. The trick is to get it as out-of-the-way as possible. For console applications this bootstrapping happens in the `Main()` method. Do it there and minimize those Resolve calls elsewhere and you'll be great. For most dependencies, use constructor injection.
|
287,903 |
<p>Would the following make the objects fulfil all characteristics that enums have in JavaScript? Something like:</p>
<pre class="lang-js prettyprint-override"><code>my.namespace.ColorEnum = {
RED : 0,
GREEN : 1,
BLUE : 2
}
// later on
if(currentColor == my.namespace.ColorEnum.RED) {
// whatever
}
</code></pre>
<p>Or is there some other way I can do this?</p>
|
[
{
"answer_id": 287917,
"author": "Gareth",
"author_id": 31582,
"author_profile": "https://Stackoverflow.com/users/31582",
"pm_score": 9,
"selected": false,
"text": "<p>This isn't much of an answer, but I'd say that works just fine, personally</p>\n\n<p>Having said that, since it doesn't matter what the values are (you've used 0, 1, 2), I'd use a meaningful string in case you ever wanted to output the current value.</p>\n"
},
{
"answer_id": 1314191,
"author": "Randolpho",
"author_id": 12716,
"author_profile": "https://Stackoverflow.com/users/12716",
"pm_score": 7,
"selected": false,
"text": "<p>Bottom line: You can't. </p>\n\n<p>You can fake it, but you won't get type safety. Typically this is done by creating a simple dictionary of string values mapped to integer values. For example:</p>\n\n<pre><code>var DaysEnum = {\"monday\":1, \"tuesday\":2, \"wednesday\":3, ...}\n\nDocument.Write(\"Enumerant: \" + DaysEnum.tuesday);\n</code></pre>\n\n<p>The problem with this approach? You can accidentally redefine your enumerant, or accidentally have duplicate enumerant values. For example:</p>\n\n<pre><code>DaysEnum.monday = 4; // whoops, monday is now thursday, too\n</code></pre>\n\n<p><strong>Edit</strong> </p>\n\n<blockquote>\n <p>What about Artur Czajka's Object.freeze? Wouldn't that work to prevent you from setting monday to thursday? β Fry Quad </p>\n</blockquote>\n\n<p>Absolutely, <a href=\"http://msdn.microsoft.com/en-us/library/windows/apps/ff806186%28v=vs.94%29.aspx\" rel=\"noreferrer\"><code>Object.freeze</code></a> would totally fix the problem I complained about. I would like to remind everyone that when I wrote the above, <code>Object.freeze</code> didn't really exist. </p>\n\n<p>Now.... now it opens up some <em>very</em> interesting possibilities. </p>\n\n<p><strong>Edit 2</strong><br>\nHere's a very good library for creating enums. </p>\n\n<p><a href=\"http://www.2ality.com/2011/10/enums.html\" rel=\"noreferrer\">http://www.2ality.com/2011/10/enums.html</a></p>\n\n<p>While it probably doesn't fit every valid use of enums, it goes a very long way. </p>\n"
},
{
"answer_id": 2383215,
"author": "Stijn de Witt",
"author_id": 286685,
"author_profile": "https://Stackoverflow.com/users/286685",
"pm_score": 9,
"selected": false,
"text": "<h2>UPDATE</h2>\n<p>I don't think my answer below is the best way to write enums in JavaScript anymore. See my blog post for more details: <a href=\"https://stijndewitt.com/2014/01/26/enums-in-javascript/\" rel=\"nofollow noreferrer\">Enums in JavaScript</a>.</p>\n<hr />\n<p>Alerting the name is already possible:</p>\n<pre><code>if (currentColor == my.namespace.ColorEnum.RED) {\n // alert name of currentColor (RED: 0)\n var col = my.namespace.ColorEnum;\n for (var name in col) {\n if (col[name] == col.RED)\n alert(name);\n }\n}\n</code></pre>\n<p>Alternatively, you could make the values objects, so you can have the cake and eat it too:</p>\n<pre><code>var SIZE = {\n SMALL : {value: 0, name: "Small", code: "S"}, \n MEDIUM: {value: 1, name: "Medium", code: "M"}, \n LARGE : {value: 2, name: "Large", code: "L"}\n};\n\nvar currentSize = SIZE.MEDIUM;\nif (currentSize == SIZE.MEDIUM) {\n // this alerts: "1: Medium"\n alert(currentSize.value + ": " + currentSize.name);\n}\n</code></pre>\n<p>In JavaScript, as it is a dynamic language, it is even possible to add enum values to the set later:</p>\n<pre><code>// Add EXTRALARGE size\nSIZE.EXTRALARGE = {value: 3, name: "Extra Large", code: "XL"};\n</code></pre>\n<p>Remember, the fields of the enum (value, name and code in this example) are not needed for the identity check and are only there for convenience. Also the name of the size property itself does not need to be hard coded, but can also be set dynamically. So supposing you only know the name for your new enum value, you can still add it without problems:</p>\n<pre><code>// Add 'Extra Large' size, only knowing it's name\nvar name = "Extra Large";\nSIZE[name] = {value: -1, name: name, code: "?"};\n</code></pre>\n<p>Of course this means that some assumptions can no longer be made (that value represents the correct order for the size for example).</p>\n<p>Remember, in JavaScript an object is just like a <em>map</em> or <em>hash table</em>. A set of name-value pairs. You can loop through them or otherwise manipulate them without knowing much about them in advance.</p>\n<h2>Example</h2>\n<pre><code>for (var sz in SIZE) {\n // sz will be the names of the objects in SIZE, so\n // 'SMALL', 'MEDIUM', 'LARGE', 'EXTRALARGE'\n var size = SIZE[sz]; // Get the object mapped to the name in sz\n for (var prop in size) {\n // Get all the properties of the size object, iterates over\n // 'value', 'name' and 'code'. You can inspect everything this way. \n }\n} \n</code></pre>\n<p>And by the way, if you are interested in namespaces, you may want to have a look at my solution for simple but powerful namespace and dependency management for JavaScript: <a href=\"http://packagesinjavascript.wordpress.com/\" rel=\"nofollow noreferrer\">Packages JS</a></p>\n"
},
{
"answer_id": 5040502,
"author": "Artur Czajka",
"author_id": 572370,
"author_profile": "https://Stackoverflow.com/users/572370",
"pm_score": 11,
"selected": true,
"text": "<p>Since 1.8.5 it's possible to <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze\" rel=\"noreferrer\">seal and freeze the object</a>, so define the above as:</p>\n<pre><code>const DaysEnum = Object.freeze({"monday":1, "tuesday":2, "wednesday":3, ...})\n</code></pre>\n<p>or</p>\n<pre><code>const DaysEnum = {"monday":1, "tuesday":2, "wednesday":3, ...}\nObject.freeze(DaysEnum)\n</code></pre>\n<p>and voila! JS enums.</p>\n<p>However, this doesn't prevent you from assigning an undesired value to a variable, which is often the main goal of enums:</p>\n<pre><code>let day = DaysEnum.tuesday\nday = 298832342 // goes through without any errors\n</code></pre>\n<p>One way to ensure a stronger degree of type safety (with enums or otherwise) is to use a tool like <a href=\"https://www.typescriptlang.org/\" rel=\"noreferrer\">TypeScript</a> or <a href=\"https://flow.org/\" rel=\"noreferrer\">Flow</a>.</p>\n<p>Quotes aren't needed but I kept them for consistency.</p>\n"
},
{
"answer_id": 6672823,
"author": "Andre 'Fi'",
"author_id": 841793,
"author_profile": "https://Stackoverflow.com/users/841793",
"pm_score": 6,
"selected": false,
"text": "<p>Here's what we all want:</p>\n\n<pre><code>function Enum(constantsList) {\n for (var i in constantsList) {\n this[constantsList[i]] = i;\n }\n}\n</code></pre>\n\n<p>Now you can create your enums:</p>\n\n<pre><code>var YesNo = new Enum(['NO', 'YES']);\nvar Color = new Enum(['RED', 'GREEN', 'BLUE']);\n</code></pre>\n\n<p>By doing this, constants can be acessed in the usual way (YesNo.YES, Color.GREEN) and they get a sequential int value (NO = 0, YES = 1; RED = 0, GREEN = 1, BLUE = 2).</p>\n\n<p>You can also add methods, by using Enum.prototype:</p>\n\n<pre><code>Enum.prototype.values = function() {\n return this.allValues;\n /* for the above to work, you'd need to do\n this.allValues = constantsList at the constructor */\n};\n</code></pre>\n\n<p><br>\nEdit - small improvement - now with varargs: (unfortunately it doesn't work properly on IE :S... should stick with previous version then)</p>\n\n<pre><code>function Enum() {\n for (var i in arguments) {\n this[arguments[i]] = i;\n }\n}\n\nvar YesNo = new Enum('NO', 'YES');\nvar Color = new Enum('RED', 'GREEN', 'BLUE');\n</code></pre>\n"
},
{
"answer_id": 10299613,
"author": "Yaroslav",
"author_id": 1351319,
"author_profile": "https://Stackoverflow.com/users/1351319",
"pm_score": 4,
"selected": false,
"text": "<p>If you're using <a href=\"http://documentcloud.github.com/backbone/\">Backbone</a>, you can get full-blown enum functionality (find by id, name, custom members) for free using <a href=\"http://documentcloud.github.com/backbone/#Collection\">Backbone.Collection</a>.</p>\n\n<pre><code>// enum instance members, optional\nvar Color = Backbone.Model.extend({\n print : function() {\n console.log(\"I am \" + this.get(\"name\"))\n }\n});\n\n// enum creation\nvar Colors = new Backbone.Collection([\n { id : 1, name : \"Red\", rgb : 0xFF0000},\n { id : 2, name : \"Green\" , rgb : 0x00FF00},\n { id : 3, name : \"Blue\" , rgb : 0x0000FF}\n], {\n model : Color\n});\n\n// Expose members through public fields.\nColors.each(function(color) {\n Colors[color.get(\"name\")] = color;\n});\n\n// using\nColors.Red.print()\n</code></pre>\n"
},
{
"answer_id": 10597813,
"author": "Chris",
"author_id": 1395768,
"author_profile": "https://Stackoverflow.com/users/1395768",
"pm_score": 4,
"selected": false,
"text": "<p>This is the solution that I use.</p>\n\n<pre><code>function Enum() {\n this._enums = [];\n this._lookups = {};\n}\n\nEnum.prototype.getEnums = function() {\n return _enums;\n}\n\nEnum.prototype.forEach = function(callback){\n var length = this._enums.length;\n for (var i = 0; i < length; ++i){\n callback(this._enums[i]);\n }\n}\n\nEnum.prototype.addEnum = function(e) {\n this._enums.push(e);\n}\n\nEnum.prototype.getByName = function(name) {\n return this[name];\n}\n\nEnum.prototype.getByValue = function(field, value) {\n var lookup = this._lookups[field];\n if(lookup) {\n return lookup[value];\n } else {\n this._lookups[field] = ( lookup = {});\n var k = this._enums.length - 1;\n for(; k >= 0; --k) {\n var m = this._enums[k];\n var j = m[field];\n lookup[j] = m;\n if(j == value) {\n return m;\n }\n }\n }\n return null;\n}\n\nfunction defineEnum(definition) {\n var k;\n var e = new Enum();\n for(k in definition) {\n var j = definition[k];\n e[k] = j;\n e.addEnum(j)\n }\n return e;\n}\n</code></pre>\n\n<p>And you define your enums like this:</p>\n\n<pre><code>var COLORS = defineEnum({\n RED : {\n value : 1,\n string : 'red'\n },\n GREEN : {\n value : 2,\n string : 'green'\n },\n BLUE : {\n value : 3,\n string : 'blue'\n }\n});\n</code></pre>\n\n<p>And this is how you access your enums:</p>\n\n<pre><code>COLORS.BLUE.string\nCOLORS.BLUE.value\nCOLORS.getByName('BLUE').string\nCOLORS.getByValue('value', 1).string\n\nCOLORS.forEach(function(e){\n // do what you want with e\n});\n</code></pre>\n\n<p>I usually use the last 2 methods for mapping enums from message objects.</p>\n\n<p>Some advantages to this approach:</p>\n\n<ul>\n<li>Easy to declare enums</li>\n<li>Easy to access your enums</li>\n<li>Your enums can be complex types</li>\n<li>The Enum class has some associative caching if you are using getByValue a lot</li>\n</ul>\n\n<p>Some disadvantages:</p>\n\n<ul>\n<li>Some messy memory management going on in there, as I keep the references to the enums</li>\n<li>Still no type safety</li>\n</ul>\n"
},
{
"answer_id": 15948460,
"author": "David MirΓ³",
"author_id": 2270217,
"author_profile": "https://Stackoverflow.com/users/2270217",
"pm_score": 3,
"selected": false,
"text": "<p>I've modified the solution of Andre 'Fi':</p>\n\n<pre><code> function Enum() {\n var that = this;\n for (var i in arguments) {\n that[arguments[i]] = i;\n }\n this.name = function(value) {\n for (var key in that) {\n if (that[key] == value) {\n return key;\n }\n }\n };\n this.exist = function(value) {\n return (typeof that.name(value) !== \"undefined\");\n };\n if (Object.freeze) {\n Object.freeze(that);\n }\n }\n</code></pre>\n\n<p>Test:</p>\n\n<pre><code>var Color = new Enum('RED', 'GREEN', 'BLUE');\nundefined\nColor.name(Color.REDs)\nundefined\nColor.name(Color.RED)\n\"RED\"\nColor.exist(Color.REDs)\nfalse\nColor.exist(Color.RED)\ntrue\n</code></pre>\n"
},
{
"answer_id": 17280078,
"author": "Rob Hardy",
"author_id": 1733091,
"author_profile": "https://Stackoverflow.com/users/1733091",
"pm_score": 4,
"selected": false,
"text": "<p>This is an old one I know, but the way it has since been implemented via the TypeScript interface is:</p>\n\n<pre><code>var MyEnum;\n(function (MyEnum) {\n MyEnum[MyEnum[\"Foo\"] = 0] = \"Foo\";\n MyEnum[MyEnum[\"FooBar\"] = 2] = \"FooBar\";\n MyEnum[MyEnum[\"Bar\"] = 1] = \"Bar\";\n})(MyEnum|| (MyEnum= {}));\n</code></pre>\n\n<p>This enables you to look up on both <code>MyEnum.Bar</code> which returns 1, and <code>MyEnum[1]</code> which returns \"Bar\" regardless of the order of declaration.</p>\n"
},
{
"answer_id": 18355123,
"author": "Duncan",
"author_id": 945011,
"author_profile": "https://Stackoverflow.com/users/945011",
"pm_score": 5,
"selected": false,
"text": "<p>I've been playing around with this, as I love my enums. =)</p>\n\n<p>Using <code>Object.defineProperty</code> I think I came up with a somewhat viable solution.</p>\n\n<p>Here's a jsfiddle: <a href=\"http://jsfiddle.net/ZV4A6/\" rel=\"noreferrer\">http://jsfiddle.net/ZV4A6/</a></p>\n\n<p>Using this method.. you should (in theory) be able to call and define enum values for any object, without affecting other attributes of that object.</p>\n\n<pre><code>Object.defineProperty(Object.prototype,'Enum', {\n value: function() {\n for(i in arguments) {\n Object.defineProperty(this,arguments[i], {\n value:parseInt(i),\n writable:false,\n enumerable:true,\n configurable:true\n });\n }\n return this;\n },\n writable:false,\n enumerable:false,\n configurable:false\n}); \n</code></pre>\n\n<p>Because of the attribute <code>writable:false</code> this <i>should</i> make it type safe.</p>\n\n<p>So you should be able to create a custom object, then call <code>Enum()</code> on it. The values assigned start at 0 and increment per item.</p>\n\n<pre><code>var EnumColors={};\nEnumColors.Enum('RED','BLUE','GREEN','YELLOW');\nEnumColors.RED; // == 0\nEnumColors.BLUE; // == 1\nEnumColors.GREEN; // == 2\nEnumColors.YELLOW; // == 3\n</code></pre>\n"
},
{
"answer_id": 19034005,
"author": "GTF",
"author_id": 907981,
"author_profile": "https://Stackoverflow.com/users/907981",
"pm_score": 2,
"selected": false,
"text": "<p>I had done it a while ago using a mixture of <code>__defineGetter__</code> and <code>__defineSetter__</code> or <code>defineProperty</code> depending on the JS version.</p>\n\n<p>Here's the enum generating function I made: <a href=\"https://gist.github.com/gfarrell/6716853\" rel=\"nofollow\">https://gist.github.com/gfarrell/6716853</a></p>\n\n<p>You'd use it like this:</p>\n\n<pre><code>var Colours = Enum('RED', 'GREEN', 'BLUE');\n</code></pre>\n\n<p>And it would create an immutable string:int dictionary (an enum).</p>\n"
},
{
"answer_id": 19112051,
"author": "user2254487",
"author_id": 2254487,
"author_profile": "https://Stackoverflow.com/users/2254487",
"pm_score": 2,
"selected": false,
"text": "<p>A quick and simple way would be :</p>\n\n<pre><code>var Colors = function(){\nreturn {\n 'WHITE':0,\n 'BLACK':1,\n 'RED':2,\n 'GREEN':3\n }\n}();\n\nconsole.log(Colors.WHITE) //this prints out \"0\"\n</code></pre>\n"
},
{
"answer_id": 23455550,
"author": "arcseldon",
"author_id": 1882064,
"author_profile": "https://Stackoverflow.com/users/1882064",
"pm_score": 2,
"selected": false,
"text": "<p>As of writing, <strong>October 2014</strong> - so here is a contemporary solution. Am writing the solution as a Node Module, and have included a test using Mocha and Chai, as well as underscoreJS. You can easily ignore these, and just take the Enum code if preferred.</p>\n\n<p>Seen a lot of posts with overly convoluted libraries etc. The solution to getting enum support in Javascript is so simple it really isn't needed. Here is the code:</p>\n\n<p>File: enums.js</p>\n\n<pre><code>_ = require('underscore');\n\nvar _Enum = function () {\n\n var keys = _.map(arguments, function (value) {\n return value;\n });\n var self = {\n keys: keys\n };\n for (var i = 0; i < arguments.length; i++) {\n self[keys[i]] = i;\n }\n return self;\n};\n\nvar fileFormatEnum = Object.freeze(_Enum('CSV', 'TSV'));\nvar encodingEnum = Object.freeze(_Enum('UTF8', 'SHIFT_JIS'));\n\nexports.fileFormatEnum = fileFormatEnum;\nexports.encodingEnum = encodingEnum;\n</code></pre>\n\n<p>And a test to illustrate what it gives you:</p>\n\n<p>file: enumsSpec.js</p>\n\n<pre><code>var chai = require(\"chai\"),\n assert = chai.assert,\n expect = chai.expect,\n should = chai.should(),\n enums = require('./enums'),\n _ = require('underscore');\n\n\ndescribe('enums', function () {\n\n describe('fileFormatEnum', function () {\n it('should return expected fileFormat enum declarations', function () {\n var fileFormatEnum = enums.fileFormatEnum;\n should.exist(fileFormatEnum);\n assert('{\"keys\":[\"CSV\",\"TSV\"],\"CSV\":0,\"TSV\":1}' === JSON.stringify(fileFormatEnum), 'Unexpected format');\n assert('[\"CSV\",\"TSV\"]' === JSON.stringify(fileFormatEnum.keys), 'Unexpected keys format');\n });\n });\n\n describe('encodingEnum', function () {\n it('should return expected encoding enum declarations', function () {\n var encodingEnum = enums.encodingEnum;\n should.exist(encodingEnum);\n assert('{\"keys\":[\"UTF8\",\"SHIFT_JIS\"],\"UTF8\":0,\"SHIFT_JIS\":1}' === JSON.stringify(encodingEnum), 'Unexpected format');\n assert('[\"UTF8\",\"SHIFT_JIS\"]' === JSON.stringify(encodingEnum.keys), 'Unexpected keys format');\n });\n });\n\n});\n</code></pre>\n\n<p>As you can see, you get an Enum factory, you can get all the keys simply by calling enum.keys, and you can match the keys themselves to integer constants. And you can reuse the factory with different values, and export those generated Enums using Node's modular approach. </p>\n\n<p>Once again, if you are just a casual user, or in the browser etc, just take the factory part of the code, potentially removing underscore library too if you don't wish to use it in your code.</p>\n"
},
{
"answer_id": 23669178,
"author": "Xeltor",
"author_id": 1330674,
"author_profile": "https://Stackoverflow.com/users/1330674",
"pm_score": 3,
"selected": false,
"text": "<p>your answers are far too complicated</p>\n\n<pre><code>var buildSet = function(array) {\n var set = {};\n for (var i in array) {\n var item = array[i];\n set[item] = item;\n }\n return set;\n}\n\nvar myEnum = buildSet(['RED','GREEN','BLUE']);\n// myEnum.RED == 'RED' ...etc\n</code></pre>\n"
},
{
"answer_id": 25692451,
"author": "Andrew Philips",
"author_id": 314114,
"author_profile": "https://Stackoverflow.com/users/314114",
"pm_score": 1,
"selected": false,
"text": "<p>Really like what @Duncan did above, but I don't like mucking up global Object function space with Enum, so I wrote the following:</p>\n\n<pre><code>function mkenum_1()\n{\n var o = new Object();\n var c = -1;\n var f = function(e, v) { Object.defineProperty(o, e, { value:v, writable:false, enumerable:true, configurable:true })};\n\n for (i in arguments) {\n var e = arguments[i];\n if ((!!e) & (e.constructor == Object))\n for (j in e)\n f(j, (c=e[j]));\n else\n f(e, ++c);\n }\n\n return Object.freeze ? Object.freeze(o) : o;\n}\n\nvar Sizes = mkenum_1('SMALL','MEDIUM',{LARGE: 100},'XLARGE');\n\nconsole.log(\"MED := \" + Sizes.MEDIUM);\nconsole.log(\"LRG := \" + Sizes.LARGE);\n\n// Output is:\n// MED := 1\n// LRG := 100\n</code></pre>\n\n<p>@Stijin also has a neat solution (referring to his blog) which includes properties on these objects. I wrote some code for that, too, which I'm including next.</p>\n\n<pre><code>function mkenum_2(seed)\n{\n var p = {};\n\n console.log(\"Seed := \" + seed);\n\n for (k in seed) {\n var v = seed[k];\n\n if (v instanceof Array)\n p[(seed[k]=v[0])] = { value: v[0], name: v[1], code: v[2] };\n else\n p[v] = { value: v, name: k.toLowerCase(), code: k.substring(0,1) };\n }\n seed.properties = p;\n\n return Object.freeze ? Object.freeze(seed) : seed;\n}\n</code></pre>\n\n<p>This version produces an additional property list allowing friendly name conversion and short codes. I like this version because one need not duplicate data entry in properties as the code does it for you.</p>\n\n<pre><code>var SizeEnum2 = mkenum_2({ SMALL: 1, MEDIUM: 2, LARGE: 3});\nvar SizeEnum3 = mkenum_2({ SMALL: [1, \"small\", \"S\"], MEDIUM: [2, \"medium\", \"M\"], LARGE: [3, \"large\", \"L\"] });\n</code></pre>\n\n<p>These two can be combined into a single processing unit, mkenum, (consume enums, assign values, create and add property list). However, as I've spent far too much time on this today already, I will leave the combination as an exercise for the dear reader.</p>\n"
},
{
"answer_id": 28205581,
"author": "Shivanshu Goyal",
"author_id": 1544818,
"author_profile": "https://Stackoverflow.com/users/1544818",
"pm_score": 3,
"selected": false,
"text": "<pre><code>var ColorEnum = {\n red: {},\n green: {},\n blue: {}\n}\n</code></pre>\n\n<p>You don't need to make sure you don't assign duplicate numbers to different enum values this way. A new object gets instantiated and assigned to all enum values.</p>\n"
},
{
"answer_id": 28526471,
"author": "Gildas.Tambo",
"author_id": 2065597,
"author_profile": "https://Stackoverflow.com/users/2065597",
"pm_score": 1,
"selected": false,
"text": "<p>You can use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty\" rel=\"nofollow\">Object.prototype.hasOwnProperty()</a> </p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var findInEnum,\r\n colorEnum = {\r\n red : 0,\r\n green : 1,\r\n blue : 2\r\n};\r\n\r\n// later on\r\n\r\nfindInEnum = function (enumKey) {\r\n if (colorEnum.hasOwnProperty(enumKey)) {\r\n return enumKey+' Value: ' + colorEnum[enumKey]\r\n }\r\n}\r\n\r\nalert(findInEnum(\"blue\"))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 29074825,
"author": "Blake Bowen",
"author_id": 2760155,
"author_profile": "https://Stackoverflow.com/users/2760155",
"pm_score": 2,
"selected": false,
"text": "<p>Here's a couple different ways to implement <a href=\"http://www.typescriptlang.org/Handbook#basic-types-enum\" rel=\"nofollow\">TypeScript enums</a>.</p>\n\n<p>The easiest way is to just iterate over an object, adding inverted key-value pairs to the object. The only drawback is that you must manually set the value for each member.</p>\n\n<pre><code>function _enum(list) { \n for (var key in list) {\n list[list[key] = list[key]] = key;\n }\n return Object.freeze(list);\n}\n\nvar Color = _enum({\n Red: 0,\n Green: 5,\n Blue: 2\n});\n\n// Color β {0: \"Red\", 2: \"Blue\", 5: \"Green\", \"Red\": 0, \"Green\": 5, \"Blue\": 2}\n// Color.Red β 0\n// Color.Green β 5\n// Color.Blue β 2\n// Color[5] β Green\n// Color.Blue > Color.Green β false\n</code></pre>\n\n<p><br>\nAnd here's a <a href=\"https://lodash.com/docs#mixin\" rel=\"nofollow\">lodash mixin</a> to create an enum using a string. While this version is a little bit more involved, it does the numbering automatically for you. All the lodash methods used in this example have a regular JavaScript equivalent, so you can easily switch them out if you want.</p>\n\n<pre><code>function enum() {\n var key, val = -1, list = {};\n _.reduce(_.toArray(arguments), function(result, kvp) { \n kvp = kvp.split(\"=\");\n key = _.trim(kvp[0]);\n val = _.parseInt(kvp[1]) || ++val; \n result[result[val] = key] = val;\n return result;\n }, list);\n return Object.freeze(list);\n} \n\n// Add enum to lodash \n_.mixin({ \"enum\": enum });\n\nvar Color = _.enum(\n \"Red\",\n \"Green\",\n \"Blue = 5\",\n \"Yellow\",\n \"Purple = 20\",\n \"Gray\"\n);\n\n// Color.Red β 0\n// Color.Green β 1\n// Color.Blue β 5\n// Color.Yellow β 6\n// Color.Purple β 20\n// Color.Gray β 21\n// Color[5] β Blue\n</code></pre>\n"
},
{
"answer_id": 29094597,
"author": "Tschallacka",
"author_id": 1356107,
"author_profile": "https://Stackoverflow.com/users/1356107",
"pm_score": 1,
"selected": false,
"text": "<p>What is an enum in <strong>my</strong> opinion: It's an immutable object that is always accessible and you can compare items with eachother, but the items have common properties/methods, but the objects themselves or the values cannot be changed and they are instantiated only once.</p>\n\n<p>Enums are imho used for comparing datatypes, settings, actions to take/reply things like that. </p>\n\n<p>So for this you need objects with the same instance so you can check if it is a enum type <code>if(something instanceof enum)</code>\nAlso if you get an enum object you want to be able to do stuff with it, regardless of the enum type, it should always respond in the same way.</p>\n\n<p>In my case its comparing values of datatypes, but it could be anything, from modifying blocks in facing direction in a 3d game to passing values on to a specific object type registry.</p>\n\n<p>Keeping in mind it is javascript and doesn't provide fixed enum type, you end up always making your own implementation and as this thread shows there are legions of implementations without one being the absoulte correct.</p>\n\n<hr>\n\n<p>This is what I use for Enums. Since enums are immutable(or should be at least heh) I freeze the objects so they can't be manipulated easely.</p>\n\n<p>The enums can be used by EnumField.STRING and they have their own methods that will work with their types.\nTo test if something passed to an object you can use <code>if(somevar instanceof EnumFieldSegment)</code></p>\n\n<p>It may not be the most elegant solution and i'm open for improvements, but this type of immutable enum(unless you unfreeze it) is exactly the usecase I needed.</p>\n\n<p>I also realise I could have overridden the prototype with a {} but my mind works better with this format ;-) shoot me.</p>\n\n<pre><code>/**\n * simple parameter object instantiator\n * @param name\n * @param value\n * @returns\n */\nfunction p(name,value) {\n this.name = name;\n this.value = value;\n return Object.freeze(this);\n}\n/**\n * EnumFieldSegmentBase\n */\nfunction EnumFieldSegmentBase() {\n this.fieldType = \"STRING\";\n}\nfunction dummyregex() {\n}\ndummyregex.prototype.test = function(str) {\n if(this.fieldType === \"STRING\") {\n maxlength = arguments[1];\n return str.length <= maxlength;\n }\n return true;\n};\n\ndummyregexposer = new dummyregex();\nEnumFieldSegmentBase.prototype.getInputRegex = function() { \n switch(this.fieldType) {\n case \"STRING\" : return dummyregexposer; \n case \"INT\": return /^(\\d+)?$/;\n case \"DECIMAL2\": return /^\\d+(\\.\\d{1,2}|\\d+|\\.)?$/;\n case \"DECIMAL8\": return /^\\d+(\\.\\d{1,8}|\\d+|\\.)?$/;\n // boolean is tricky dicky. if its a boolean false, if its a string if its empty 0 or false its false, otherwise lets see what Boolean produces\n case \"BOOLEAN\": return dummyregexposer;\n }\n};\nEnumFieldSegmentBase.prototype.convertToType = function($input) {\n var val = $input;\n switch(this.fieldType) {\n case \"STRING\" : val = $input;break;\n case \"INT\": val==\"\"? val=0 :val = parseInt($input);break;\n case \"DECIMAL2\": if($input === \"\" || $input === null) {$input = \"0\"}if($input.substr(-1) === \".\"){$input = $input+0};val = new Decimal2($input).toDP(2);break;\n case \"DECIMAL8\": if($input === \"\" || $input === null) {$input = \"0\"}if($input.substr(-1) === \".\"){$input = $input+0};val = new Decimal8($input).toDP(8);break;\n // boolean is tricky dicky. if its a boolean false, if its a string if its empty 0 or false its false, otherwise lets see what Boolean produces\n case \"BOOLEAN\": val = (typeof $input == 'boolean' ? $input : (typeof $input === 'string' ? (($input === \"false\" || $input === \"\" || $input === \"0\") ? false : true) : new Boolean($input).valueOf())) ;break;\n }\n return val;\n};\nEnumFieldSegmentBase.prototype.convertToString = function($input) {\n var val = $input;\n switch(this.fieldType) {\n case \"STRING\": val = $input;break;\n case \"INT\": val = $input+\"\";break;\n case \"DECIMAL2\": val = $input.toPrecision(($input.toString().indexOf('.') === -1 ? $input.toString().length+2 : $input.toString().indexOf('.')+2)) ;break;\n case \"DECIMAL8\": val = $input.toPrecision(($input.toString().indexOf('.') === -1 ? $input.toString().length+8 : $input.toString().indexOf('.')+8)) ;break;\n case \"BOOLEAN\": val = $input ? \"true\" : \"false\" ;break;\n }\n return val;\n};\nEnumFieldSegmentBase.prototype.compareValue = function($val1,$val2) {\n var val = false;\n switch(this.fieldType) {\n case \"STRING\": val = ($val1===$val2);break;\n case \"INT\": val = ($val1===$val2);break;\n case \"DECIMAL2\": val = ($val1.comparedTo($val2)===0);break;\n case \"DECIMAL8\": val = ($val1.comparedTo($val2)===0);break;\n case \"BOOLEAN\": val = ($val1===$val2);break;\n }\n return val;\n};\n\n/**\n * EnumFieldSegment is an individual segment in the \n * EnumField\n * @param $array An array consisting of object p\n */\nfunction EnumFieldSegment() {\n for(c=0;c<arguments.length;c++) {\n if(arguments[c] instanceof p) {\n this[arguments[c].name] = arguments[c].value;\n }\n }\n return Object.freeze(this); \n}\nEnumFieldSegment.prototype = new EnumFieldSegmentBase();\nEnumFieldSegment.prototype.constructor = EnumFieldSegment;\n\n\n/**\n * Simple enum to show what type of variable a Field type is.\n * @param STRING\n * @param INT\n * @param DECIMAL2\n * @param DECIMAL8\n * @param BOOLEAN\n * \n */\nEnumField = Object.freeze({STRING: new EnumFieldSegment(new p(\"fieldType\",\"STRING\")), \n INT: new EnumFieldSegment(new p(\"fieldType\",\"INT\")), \n DECIMAL2: new EnumFieldSegment(new p(\"fieldType\",\"DECIMAL2\")), \n DECIMAL8: new EnumFieldSegment(new p(\"fieldType\",\"DECIMAL8\")), \n BOOLEAN: new EnumFieldSegment(new p(\"fieldType\",\"BOOLEAN\"))});\n</code></pre>\n"
},
{
"answer_id": 29894175,
"author": "Gelin Luo",
"author_id": 391227,
"author_profile": "https://Stackoverflow.com/users/391227",
"pm_score": 2,
"selected": false,
"text": "<p>I've just published an NPM package <a href=\"https://www.npmjs.com/package/gen_enum\" rel=\"nofollow\">gen_enum</a> allows you to create Enum data structure in Javascript quickly:</p>\n\n<pre><code>var genEnum = require('gen_enum');\n\nvar AppMode = genEnum('SIGN_UP, LOG_IN, FORGOT_PASSWORD');\nvar curMode = AppMode.LOG_IN;\nconsole.log(curMode.isLogIn()); // output true \nconsole.log(curMode.isSignUp()); // output false \nconsole.log(curMode.isForgotPassword()); // output false \n</code></pre>\n\n<p>One nice thing about this little tool is in modern environment (including nodejs and IE 9+ browsers) the returned Enum object is immutable.</p>\n\n<p>For more information please checkout <a href=\"https://github.com/greenlaw110/enumjs\" rel=\"nofollow\">https://github.com/greenlaw110/enumjs</a></p>\n\n<p><strong>Updates</strong></p>\n\n<p>I obsolete <code>gen_enum</code> package and merge the function into <a href=\"https://www.npmjs.com/package/constjs\" rel=\"nofollow\">constjs</a> package, which provides more features including immutable objects, JSON string deserialization, string constants and bitmap generation etc. Checkout <a href=\"https://www.npmjs.com/package/constjs\" rel=\"nofollow\">https://www.npmjs.com/package/constjs</a> for more information </p>\n\n<p>To upgrade from <code>gen_enum</code> to <code>constjs</code> just change the statement</p>\n\n<pre><code>var genEnum = require('gen_enum');\n</code></pre>\n\n<p>to</p>\n\n<pre><code>var genEnum = require('constjs').enum;\n</code></pre>\n"
},
{
"answer_id": 30045582,
"author": "Pylinux",
"author_id": 1465640,
"author_profile": "https://Stackoverflow.com/users/1465640",
"pm_score": 0,
"selected": false,
"text": "<pre><code>var DaysEnum = Object.freeze ({ monday: {}, tuesday: {}, ... });\n</code></pre>\n\n<p>You don't need to specify an <em>id</em>, you can just use an empty object to compare enums. </p>\n\n<pre><code>if (incommingEnum === DaysEnum.monday) //incommingEnum is monday\n</code></pre>\n\n<p><strong>EDIT:</strong> If you are going to serialize the object (to JSON for instance) you'll the <em>id</em> again.</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/287903/enums-in-javascript#comment12864576_5040502\">( taken from Gabriel Llamas comment )</a></li>\n<li><a href=\"https://stackoverflow.com/questions/287903/enums-in-javascript/30045582?noredirect=1#comment71130974_30045582\">( edit based on Stijn de Witt's comment )</a></li>\n</ul>\n"
},
{
"answer_id": 30058506,
"author": "Vitalii Fedorenko",
"author_id": 288671,
"author_profile": "https://Stackoverflow.com/users/288671",
"pm_score": 6,
"selected": false,
"text": "<p>In most modern browsers, there is a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol\" rel=\"noreferrer\">symbol</a> primitive data type which can be used to create an enumeration. It will ensure type safety of the enum as each symbol value is guaranteed by JavaScript to be unique, i.e. <code>Symbol() != Symbol()</code>. For example:</p>\n\n<pre><code>const COLOR = Object.freeze({RED: Symbol(), BLUE: Symbol()});\n</code></pre>\n\n<p>To simplify debugging, you can add a description to enum values:</p>\n\n<pre><code>const COLOR = Object.freeze({RED: Symbol(\"RED\"), BLUE: Symbol(\"BLUE\")});\n</code></pre>\n\n<p><a href=\"http://plnkr.co/edit/rGjzZlUF4HPdllaTQ3OW?p=preview\" rel=\"noreferrer\">Plunker demo</a></p>\n\n<p>On <a href=\"https://github.com/zhaber/symbol-enum\" rel=\"noreferrer\">GitHub</a> you can find a wrapper that simplifies the code required to initialize the enum:</p>\n\n<pre><code>const color = new Enum(\"RED\", \"BLUE\")\n\ncolor.RED.toString() // Symbol(RED)\ncolor.getName(color.RED) // RED\ncolor.size // 2\ncolor.values() // Symbol(RED), Symbol(BLUE)\ncolor.toString() // RED,BLUE\n</code></pre>\n"
},
{
"answer_id": 31185447,
"author": "Manohar Reddy Poreddy",
"author_id": 984471,
"author_profile": "https://Stackoverflow.com/users/984471",
"pm_score": 3,
"selected": false,
"text": "<p>IE8 does Not support freeze() method.<br>\nSource: <a href=\"http://kangax.github.io/compat-table/es5/\" rel=\"nofollow\">http://kangax.github.io/compat-table/es5/</a>, Click on \"Show obsolete browsers?\" on top, and check IE8 & freeze row col intersection.</p>\n\n<p>In my current game project, I have used below, since few customers still use IE8:</p>\n\n<pre><code>var CONST_WILD_TYPES = {\n REGULAR: 'REGULAR',\n EXPANDING: 'EXPANDING',\n STICKY: 'STICKY',\n SHIFTING: 'SHIFTING'\n};\n</code></pre>\n\n<p>We could also do: </p>\n\n<pre><code>var CONST_WILD_TYPES = {\n REGULAR: 'RE',\n EXPANDING: 'EX',\n STICKY: 'ST',\n SHIFTING: 'SH'\n};\n</code></pre>\n\n<p>or even this: </p>\n\n<pre><code>var CONST_WILD_TYPES = {\n REGULAR: '1',\n EXPANDING: '2',\n STICKY: '3',\n SHIFTING: '4'\n};\n</code></pre>\n\n<p>The last one, seems most efficient for string, it reduces your total bandwidth if you have server & client exchanging this data.<br>\nOf course, now it's your duty to make sure there are no conflicts in the data (RE, EX, etc. must be unique, also 1, 2, etc. should be unique). Note that you need to maintain these forever for backward compatibility. </p>\n\n<p>Assignment:</p>\n\n<pre><code>var wildType = CONST_WILD_TYPES.REGULAR;\n</code></pre>\n\n<p>Comparision:</p>\n\n<pre><code>if (wildType === CONST_WILD_TYPES.REGULAR) {\n // do something here\n}\n</code></pre>\n"
},
{
"answer_id": 31636748,
"author": "hvdd",
"author_id": 2326407,
"author_profile": "https://Stackoverflow.com/users/2326407",
"pm_score": 4,
"selected": false,
"text": "<p>Create an object literal:</p>\n\n<pre><code>const Modes = {\n DRAGGING: 'drag',\n SCALING: 'scale',\n CLICKED: 'click'\n};\n</code></pre>\n"
},
{
"answer_id": 32245965,
"author": "Sherali Turdiyev",
"author_id": 4365315,
"author_profile": "https://Stackoverflow.com/users/4365315",
"pm_score": 2,
"selected": false,
"text": "<p>It's easy to use, I think. <a href=\"https://stackoverflow.com/a/32245370/4365315\">https://stackoverflow.com/a/32245370/4365315</a></p>\n\n<pre><code>var A = {a:11, b:22}, \nenumA = new TypeHelper(A);\n\nif(enumA.Value === A.b || enumA.Key === \"a\"){ \n... \n}\n\nvar keys = enumA.getAsList();//[object, object]\n\n//set\nenumA.setType(22, false);//setType(val, isKey)\n\nenumA.setType(\"a\", true);\n\nenumA.setTypeByIndex(1);\n</code></pre>\n\n<p>UPDATE:</p>\n\n<p>There is my helper codes(<code>TypeHelper</code>).</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var Helper = {\r\n isEmpty: function (obj) {\r\n return !obj || obj === null || obj === undefined || Array.isArray(obj) && obj.length === 0;\r\n },\r\n\r\n isObject: function (obj) {\r\n return (typeof obj === 'object');\r\n },\r\n\r\n sortObjectKeys: function (object) {\r\n return Object.keys(object)\r\n .sort(function (a, b) {\r\n c = a - b;\r\n return c\r\n });\r\n },\r\n containsItem: function (arr, item) {\r\n if (arr && Array.isArray(arr)) {\r\n return arr.indexOf(item) > -1;\r\n } else {\r\n return arr === item;\r\n }\r\n },\r\n\r\n pushArray: function (arr1, arr2) {\r\n if (arr1 && arr2 && Array.isArray(arr1)) {\r\n arr1.push.apply(arr1, Array.isArray(arr2) ? arr2 : [arr2]);\r\n }\r\n }\r\n};\r\nfunction TypeHelper() {\r\n var _types = arguments[0],\r\n _defTypeIndex = 0,\r\n _currentType,\r\n _value,\r\n _allKeys = Helper.sortObjectKeys(_types);\r\n\r\n if (arguments.length == 2) {\r\n _defTypeIndex = arguments[1];\r\n }\r\n\r\n Object.defineProperties(this, {\r\n Key: {\r\n get: function () {\r\n return _currentType;\r\n },\r\n set: function (val) {\r\n _currentType.setType(val, true);\r\n },\r\n enumerable: true\r\n },\r\n Value: {\r\n get: function () {\r\n return _types[_currentType];\r\n },\r\n set: function (val) {\r\n _value.setType(val, false);\r\n },\r\n enumerable: true\r\n }\r\n });\r\n this.getAsList = function (keys) {\r\n var list = [];\r\n _allKeys.forEach(function (key, idx, array) {\r\n if (key && _types[key]) {\r\n\r\n if (!Helper.isEmpty(keys) && Helper.containsItem(keys, key) || Helper.isEmpty(keys)) {\r\n var json = {};\r\n json.Key = key;\r\n json.Value = _types[key];\r\n Helper.pushArray(list, json);\r\n }\r\n }\r\n });\r\n return list;\r\n };\r\n\r\n this.setType = function (value, isKey) {\r\n if (!Helper.isEmpty(value)) {\r\n Object.keys(_types).forEach(function (key, idx, array) {\r\n if (Helper.isObject(value)) {\r\n if (value && value.Key == key) {\r\n _currentType = key;\r\n }\r\n } else if (isKey) {\r\n if (value && value.toString() == key.toString()) {\r\n _currentType = key;\r\n }\r\n } else if (value && value.toString() == _types[key]) {\r\n _currentType = key;\r\n }\r\n });\r\n } else {\r\n this.setDefaultType();\r\n }\r\n return isKey ? _types[_currentType] : _currentType;\r\n };\r\n\r\n this.setTypeByIndex = function (index) {\r\n for (var i = 0; i < _allKeys.length; i++) {\r\n if (index === i) {\r\n _currentType = _allKeys[index];\r\n break;\r\n }\r\n }\r\n };\r\n\r\n this.setDefaultType = function () {\r\n this.setTypeByIndex(_defTypeIndex);\r\n };\r\n\r\n this.setDefaultType();\r\n}\r\n\r\nvar TypeA = {\r\n \"-1\": \"Any\",\r\n \"2\": \"2L\",\r\n \"100\": \"100L\",\r\n \"200\": \"200L\",\r\n \"1000\": \"1000L\"\r\n};\r\n\r\nvar enumA = new TypeHelper(TypeA, 4);\r\n\r\ndocument.writeln(\"Key = \", enumA.Key,\", Value = \", enumA.Value, \"<br>\");\r\n\r\n\r\nenumA.setType(\"200L\", false);\r\ndocument.writeln(\"Key = \", enumA.Key,\", Value = \", enumA.Value, \"<br>\");\r\n\r\nenumA.setDefaultType();\r\ndocument.writeln(\"Key = \", enumA.Key,\", Value = \", enumA.Value, \"<br>\");\r\n\r\n\r\nenumA.setTypeByIndex(1);\r\ndocument.writeln(\"Key = \", enumA.Key,\", Value = \", enumA.Value, \"<br>\");\r\n\r\ndocument.writeln(\"is equals = \", (enumA.Value == TypeA[\"2\"]));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 32658453,
"author": "Vivin Paliath",
"author_id": 263004,
"author_profile": "https://Stackoverflow.com/users/263004",
"pm_score": 3,
"selected": false,
"text": "<p>I came up with <a href=\"https://github.com/vivin/enumjs\" rel=\"noreferrer\">this</a> approach which is modeled after enums in Java. These are type-safe, and so you can perform <code>instanceof</code> checks as well.</p>\n\n<p>You can define enums like this:</p>\n\n<pre><code>var Days = Enum.define(\"Days\", [\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\", \"Sunday\"]);\n</code></pre>\n\n<p><code>Days</code> now refers to the <code>Days</code> enum:</p>\n\n<pre><code>Days.Monday instanceof Days; // true\n\nDays.Friday.name(); // \"Friday\"\nDays.Friday.ordinal(); // 4\n\nDays.Sunday === Days.Sunday; // true\nDays.Sunday === Days.Friday; // false\n\nDays.Sunday.toString(); // \"Sunday\"\n\nDays.toString() // \"Days { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday } \"\n\nDays.values().map(function(e) { return e.name(); }); //[\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\", \"Sunday\"]\nDays.values()[4].name(); //\"Friday\"\n\nDays.fromName(\"Thursday\") === Days.Thursday // true\nDays.fromName(\"Wednesday\").name() // \"Wednesday\"\nDays.Friday.fromName(\"Saturday\").name() // \"Saturday\"\n</code></pre>\n\n<p>The implementation:</p>\n\n<pre><code>var Enum = (function () {\n /**\n * Function to define an enum\n * @param typeName - The name of the enum.\n * @param constants - The constants on the enum. Can be an array of strings, or an object where each key is an enum\n * constant, and the values are objects that describe attributes that can be attached to the associated constant.\n */\n function define(typeName, constants) {\n\n /** Check Arguments **/\n if (typeof typeName === \"undefined\") {\n throw new TypeError(\"A name is required.\");\n }\n\n if (!(constants instanceof Array) && (Object.getPrototypeOf(constants) !== Object.prototype)) {\n\n throw new TypeError(\"The constants parameter must either be an array or an object.\");\n\n } else if ((constants instanceof Array) && constants.length === 0) {\n\n throw new TypeError(\"Need to provide at least one constant.\");\n\n } else if ((constants instanceof Array) && !constants.reduce(function (isString, element) {\n return isString && (typeof element === \"string\");\n }, true)) {\n\n throw new TypeError(\"One or more elements in the constant array is not a string.\");\n\n } else if (Object.getPrototypeOf(constants) === Object.prototype && !Object.keys(constants).reduce(function (isObject, constant) {\n return Object.getPrototypeOf(constants[constant]) === Object.prototype;\n }, true)) {\n\n throw new TypeError(\"One or more constants do not have an associated object-value.\");\n\n }\n\n var isArray = (constants instanceof Array);\n var isObject = !isArray;\n\n /** Private sentinel-object used to guard enum constructor so that no one else can create enum instances **/\n function __() { };\n\n /** Dynamically define a function with the same name as the enum we want to define. **/\n var __enum = new Function([\"__\"],\n \"return function \" + typeName + \"(sentinel, name, ordinal) {\" +\n \"if(!(sentinel instanceof __)) {\" +\n \"throw new TypeError(\\\"Cannot instantiate an instance of \" + typeName + \".\\\");\" +\n \"}\" +\n\n \"this.__name = name;\" +\n \"this.__ordinal = ordinal;\" +\n \"}\"\n )(__);\n\n /** Private objects used to maintain enum instances for values(), and to look up enum instances for fromName() **/\n var __values = [];\n var __dict = {};\n\n /** Attach values() and fromName() methods to the class itself (kind of like static methods). **/\n Object.defineProperty(__enum, \"values\", {\n value: function () {\n return __values;\n }\n });\n\n Object.defineProperty(__enum, \"fromName\", {\n value: function (name) {\n var __constant = __dict[name]\n if (__constant) {\n return __constant;\n } else {\n throw new TypeError(typeName + \" does not have a constant with name \" + name + \".\");\n }\n }\n });\n\n /**\n * The following methods are available to all instances of the enum. values() and fromName() need to be\n * available to each constant, and so we will attach them on the prototype. But really, they're just\n * aliases to their counterparts on the prototype.\n */\n Object.defineProperty(__enum.prototype, \"values\", {\n value: __enum.values\n });\n\n Object.defineProperty(__enum.prototype, \"fromName\", {\n value: __enum.fromName\n });\n\n Object.defineProperty(__enum.prototype, \"name\", {\n value: function () {\n return this.__name;\n }\n });\n\n Object.defineProperty(__enum.prototype, \"ordinal\", {\n value: function () {\n return this.__ordinal;\n }\n });\n\n Object.defineProperty(__enum.prototype, \"valueOf\", {\n value: function () {\n return this.__name;\n }\n });\n\n Object.defineProperty(__enum.prototype, \"toString\", {\n value: function () {\n return this.__name;\n }\n });\n\n /**\n * If constants was an array, we can the element values directly. Otherwise, we will have to use the keys\n * from the constants object.\n */\n var _constants = constants;\n if (isObject) {\n _constants = Object.keys(constants);\n }\n\n /** Iterate over all constants, create an instance of our enum for each one, and attach it to the enum type **/\n _constants.forEach(function (name, ordinal) {\n // Create an instance of the enum\n var __constant = new __enum(new __(), name, ordinal);\n\n // If constants was an object, we want to attach the provided attributes to the instance.\n if (isObject) {\n Object.keys(constants[name]).forEach(function (attr) {\n Object.defineProperty(__constant, attr, {\n value: constants[name][attr]\n });\n });\n }\n\n // Freeze the instance so that it cannot be modified.\n Object.freeze(__constant);\n\n // Attach the instance using the provided name to the enum type itself.\n Object.defineProperty(__enum, name, {\n value: __constant\n });\n\n // Update our private objects\n __values.push(__constant);\n __dict[name] = __constant;\n });\n\n /** Define a friendly toString method for the enum **/\n var string = typeName + \" { \" + __enum.values().map(function (c) {\n return c.name();\n }).join(\", \") + \" } \";\n\n Object.defineProperty(__enum, \"toString\", {\n value: function () {\n return string;\n }\n });\n\n /** Freeze our private objects **/\n Object.freeze(__values);\n Object.freeze(__dict);\n\n /** Freeze the prototype on the enum and the enum itself **/\n Object.freeze(__enum.prototype);\n Object.freeze(__enum);\n\n /** Return the enum **/\n return __enum;\n }\n\n return {\n define: define\n }\n\n})();\n</code></pre>\n"
},
{
"answer_id": 33326060,
"author": "Jules Sam. Randolph",
"author_id": 2779871,
"author_profile": "https://Stackoverflow.com/users/2779871",
"pm_score": 2,
"selected": false,
"text": "<p>I wrote <strong>enumerationjs</strong> a <a href=\"https://github.com/sveinburne/enumerationjs#top\" rel=\"nofollow\">very tiny library to address the issue</a> which <strong>ensures type safety</strong>, allow enum constants to <strong>inherit from a prototype</strong>, guaranties enum constants and enum types to be immutable + many little features. It allows to refactor a lot of code and move some logic inside the enum definition. Here is an example : </p>\n\n<pre><code>var CloseEventCodes = new Enumeration(\"closeEventCodes\", {\n CLOSE_NORMAL: { _id: 1000, info: \"Connection closed normally\" },\n CLOSE_GOING_AWAY: { _id: 1001, info: \"Connection closed going away\" },\n CLOSE_PROTOCOL_ERROR: { _id: 1002, info: \"Connection closed due to protocol error\" },\n CLOSE_UNSUPPORTED: { _id: 1003, info: \"Connection closed due to unsupported operation\" },\n CLOSE_NO_STATUS: { _id: 1005, info: \"Connection closed with no status\" },\n CLOSE_ABNORMAL: { _id: 1006, info: \"Connection closed abnormally\" },\n CLOSE_TOO_LARGE: { _id: 1009, info: \"Connection closed due to too large packet\" }\n},{ talk: function(){\n console.log(this.info); \n }\n});\n\n\nCloseEventCodes.CLOSE_TOO_LARGE.talk(); //prints \"Connection closed due to too large packet\"\nCloseEventCodes.CLOSE_TOO_LARGE instanceof CloseEventCodes //evaluates to true\n</code></pre>\n\n<p><code>Enumeration</code> is basically a factory. </p>\n\n<p><a href=\"https://github.com/sveinburne/enumerationjs/blob/master/JS.GUIDE.MD#top\" rel=\"nofollow\">Fully documented guide available here.</a> Hope this helps. </p>\n"
},
{
"answer_id": 34636629,
"author": "Oooogi",
"author_id": 4274373,
"author_profile": "https://Stackoverflow.com/users/4274373",
"pm_score": 2,
"selected": false,
"text": "<p>I've made an Enum class that can fetch values AND names at O(1). It can also generate an Object Array containing all Names and Values.</p>\n\n<pre><code>function Enum(obj) {\n // Names must be unique, Values do not.\n // Putting same values for different Names is risky for this implementation\n\n this._reserved = {\n _namesObj: {},\n _objArr: [],\n _namesArr: [],\n _valuesArr: [],\n _selectOptionsHTML: \"\"\n };\n\n for (k in obj) {\n if (obj.hasOwnProperty(k)) {\n this[k] = obj[k];\n this._reserved._namesObj[obj[k]] = k;\n }\n }\n}\n(function () {\n this.GetName = function (val) {\n if (typeof this._reserved._namesObj[val] === \"undefined\")\n return null;\n return this._reserved._namesObj[val];\n };\n\n this.GetValue = function (name) {\n if (typeof this[name] === \"undefined\")\n return null;\n return this[name];\n };\n\n this.GetObjArr = function () {\n if (this._reserved._objArr.length == 0) {\n var arr = [];\n for (k in this) {\n if (this.hasOwnProperty(k))\n if (k != \"_reserved\")\n arr.push({\n Name: k,\n Value: this[k]\n });\n }\n this._reserved._objArr = arr;\n }\n return this._reserved._objArr;\n };\n\n this.GetNamesArr = function () {\n if (this._reserved._namesArr.length == 0) {\n var arr = [];\n for (k in this) {\n if (this.hasOwnProperty(k))\n if (k != \"_reserved\")\n arr.push(k);\n }\n this._reserved._namesArr = arr;\n }\n return this._reserved._namesArr;\n };\n\n this.GetValuesArr = function () {\n if (this._reserved._valuesArr.length == 0) {\n var arr = [];\n for (k in this) {\n if (this.hasOwnProperty(k))\n if (k != \"_reserved\")\n arr.push(this[k]);\n }\n this._reserved._valuesArr = arr;\n }\n return this._reserved._valuesArr;\n };\n\n this.GetSelectOptionsHTML = function () {\n if (this._reserved._selectOptionsHTML.length == 0) {\n var html = \"\";\n for (k in this) {\n if (this.hasOwnProperty(k))\n if (k != \"_reserved\")\n html += \"<option value='\" + this[k] + \"'>\" + k + \"</option>\";\n }\n this._reserved._selectOptionsHTML = html;\n }\n return this._reserved._selectOptionsHTML;\n };\n}).call(Enum.prototype);\n</code></pre>\n\n<p>You can init'd it like this:</p>\n\n<pre><code>var enum1 = new Enum({\n item1: 0,\n item2: 1,\n item3: 2\n});\n</code></pre>\n\n<p>To fetch a value (like Enums in C#):</p>\n\n<pre><code>var val2 = enum1.item2;\n</code></pre>\n\n<p>To fetch a name for a value (can be ambiguous when putting the same value for different names):</p>\n\n<pre><code>var name1 = enum1.GetName(0); // \"item1\"\n</code></pre>\n\n<p>To get an array with each name & value in an object:</p>\n\n<pre><code>var arr = enum1.GetObjArr();\n</code></pre>\n\n<p>Will generate:</p>\n\n<pre><code>[{ Name: \"item1\", Value: 0}, { ... }, ... ]\n</code></pre>\n\n<p>You can also get the html select options readily:</p>\n\n<pre><code>var html = enum1.GetSelectOptionsHTML();\n</code></pre>\n\n<p>Which holds:</p>\n\n<pre><code>\"<option value='0'>item1</option>...\"\n</code></pre>\n"
},
{
"answer_id": 37159989,
"author": "Muhammad Awais",
"author_id": 3901944,
"author_profile": "https://Stackoverflow.com/users/3901944",
"pm_score": 2,
"selected": false,
"text": "<p>You can try this:</p>\n\n<pre><code> var Enum = Object.freeze({\n Role: Object.freeze({ Administrator: 1, Manager: 2, Supervisor: 3 }),\n Color:Object.freeze({RED : 0, GREEN : 1, BLUE : 2 })\n });\n\n alert(Enum.Role.Supervisor);\n alert(Enum.Color.GREEN);\n var currentColor=0;\n if(currentColor == Enum.Color.RED) {\n alert('Its Red');\n }\n</code></pre>\n"
},
{
"answer_id": 37429406,
"author": "LNT",
"author_id": 3335776,
"author_profile": "https://Stackoverflow.com/users/3335776",
"pm_score": 2,
"selected": false,
"text": "<p>You can do something like this</p>\n\n<pre><code> var Enum = (function(foo) {\n\n var EnumItem = function(item){\n if(typeof item == \"string\"){\n this.name = item;\n } else {\n this.name = item.name;\n }\n }\n EnumItem.prototype = new String(\"DEFAULT\");\n EnumItem.prototype.toString = function(){\n return this.name;\n }\n EnumItem.prototype.equals = function(item){\n if(typeof item == \"string\"){\n return this.name == item;\n } else {\n return this == item && this.name == item.name;\n }\n }\n\n function Enum() {\n this.add.apply(this, arguments);\n Object.freeze(this);\n }\n Enum.prototype.add = function() {\n for (var i in arguments) {\n var enumItem = new EnumItem(arguments[i]);\n this[enumItem.name] = enumItem;\n }\n };\n Enum.prototype.toList = function() {\n return Object.keys(this);\n };\n foo.Enum = Enum;\n return Enum;\n})(this);\nvar STATUS = new Enum(\"CLOSED\",\"PENDING\", { name : \"CONFIRMED\", ackd : true });\nvar STATE = new Enum(\"CLOSED\",\"PENDING\",\"CONFIRMED\",{ name : \"STARTED\"},{ name : \"PROCESSING\"});\n</code></pre>\n\n<p>As defined in this library.\n<a href=\"https://github.com/webmodule/foo/blob/master/foo.js#L217\" rel=\"nofollow noreferrer\">https://github.com/webmodule/foo/blob/master/foo.js#L217</a></p>\n\n<p>Complete example\n<a href=\"https://gist.github.com/lnt/bb13a2fd63cdb8bce85fd62965a20026\" rel=\"nofollow noreferrer\">https://gist.github.com/lnt/bb13a2fd63cdb8bce85fd62965a20026</a></p>\n"
},
{
"answer_id": 38996905,
"author": "Ilya Gazman",
"author_id": 1129332,
"author_profile": "https://Stackoverflow.com/users/1129332",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Simplest solution:</strong></p>\n\n<h2>Create</h2>\n\n<pre><code>var Status = Object.freeze({\n \"Connecting\":0,\n \"Ready\":1,\n \"Loading\":2,\n \"Processing\": 3\n});\n</code></pre>\n\n<h2>Get Value</h2>\n\n<pre><code>console.log(Status.Ready) // 1\n</code></pre>\n\n<h2>Get Key</h2>\n\n<pre><code>console.log(Object.keys(Status)[Status.Ready]) // Ready\n</code></pre>\n"
},
{
"answer_id": 39222211,
"author": "Marcus Junius Brutus",
"author_id": 274677,
"author_profile": "https://Stackoverflow.com/users/274677",
"pm_score": 2,
"selected": false,
"text": "<p>Even though <a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes\" rel=\"nofollow noreferrer\">only static methods</a> (and not static properties) are supported in ES2015 (see <a href=\"http://exploringjs.com/es6/ch_classes.html#_inside-the-body-of-a-class-definition\" rel=\"nofollow noreferrer\">here</a> as well, §15.2.2.2), curiously you can use the below with Babel with the <code>es2015</code> preset:</p>\n\n<pre><code>class CellState {\n v: string;\n constructor(v: string) {\n this.v = v;\n Object.freeze(this);\n }\n static EMPTY = new CellState('e');\n static OCCUPIED = new CellState('o');\n static HIGHLIGHTED = new CellState('h');\n static values = function(): Array<CellState> {\n const rv = [];\n rv.push(CellState.EMPTY);\n rv.push(CellState.OCCUPIED);\n rv.push(CellState.HIGHLIGHTED);\n return rv;\n }\n}\nObject.freeze(CellState);\n</code></pre>\n\n<p>I found this to be working as expected even across modules (e.g. importing the <code>CellState</code> enum from another module) and also when I import a module using Webpack.</p>\n\n<p><strong>The advantage this method has over most other answers is that you can use it alongside a static type checker</strong> (e.g. <a href=\"https://flowtype.org/\" rel=\"nofollow noreferrer\">Flow</a>) and you can assert, at development time using static type checking, that your variables, parameters, etc. are of the specific <code>CellState</code> \"enum\" rather than some other enum (which would be impossible to distinguish if you used generic objects or symbols).</p>\n\n<h1>update</h1>\n\n<p>The above code has a deficiency in that it allows one to create additional objects of type <code>CellState</code> (even though one can't assign them to the static fields of <code>CellState</code> since it's frozen). Still, the below more refined code offers the following advantages:</p>\n\n<ol>\n<li>no more objects of type <code>CellState</code> may be created</li>\n<li>you are guaranteed that no two enum instances are assigned the same code</li>\n<li>utility method to get the enum back from a string representation</li>\n<li><p>the <code>values</code> function that returns all instances of the enum does not have to create the return value in the above, manual (and error-prone) way.</p>\n\n<pre><code>'use strict';\n\nclass Status {\n\nconstructor(code, displayName = code) {\n if (Status.INSTANCES.has(code))\n throw new Error(`duplicate code value: [${code}]`);\n if (!Status.canCreateMoreInstances)\n throw new Error(`attempt to call constructor(${code}`+\n `, ${displayName}) after all static instances have been created`);\n this.code = code;\n this.displayName = displayName;\n Object.freeze(this);\n Status.INSTANCES.set(this.code, this);\n}\n\ntoString() {\n return `[code: ${this.code}, displayName: ${this.displayName}]`;\n}\nstatic INSTANCES = new Map();\nstatic canCreateMoreInstances = true;\n\n// the values:\nstatic ARCHIVED = new Status('Archived');\nstatic OBSERVED = new Status('Observed');\nstatic SCHEDULED = new Status('Scheduled');\nstatic UNOBSERVED = new Status('Unobserved');\nstatic UNTRIGGERED = new Status('Untriggered');\n\nstatic values = function() {\n return Array.from(Status.INSTANCES.values());\n}\n\nstatic fromCode(code) {\n if (!Status.INSTANCES.has(code))\n throw new Error(`unknown code: ${code}`);\n else\n return Status.INSTANCES.get(code);\n}\n}\n\nStatus.canCreateMoreInstances = false;\nObject.freeze(Status);\nexports.Status = Status;\n</code></pre></li>\n</ol>\n"
},
{
"answer_id": 40390784,
"author": "Little Alien",
"author_id": 6267925,
"author_profile": "https://Stackoverflow.com/users/6267925",
"pm_score": 1,
"selected": false,
"text": "<p>The Alien solution is to make things as simple as possible:</p>\n\n<ol>\n<li>use enum keyword (reserved in javascript)</li>\n<li><p>If enum keyword is just reserved but not implemented in your javascript, define the following</p>\n\n<pre><code>const enumerate = spec => spec.split(/\\s*,\\s*/)\n .reduce((e, n) => Object.assign(e,{[n]:n}), {}) \n</code></pre></li>\n</ol>\n\n<p>Now, you can easily use it</p>\n\n<pre><code>const kwords = enumerate(\"begin,end, procedure,if\")\nconsole.log(kwords, kwords.if, kwords.if == \"if\", kwords.undef)\n</code></pre>\n\n<p>I see no reason to make the enum values explicit variables. The scripts are morphic anyway and it makes no difference if part of your code is a string or valid code. What really matters is that you do not need to deal with tons of quotation marks whenever use or define them. </p>\n"
},
{
"answer_id": 41500700,
"author": "Abdennour TOUMI",
"author_id": 747579,
"author_profile": "https://Stackoverflow.com/users/747579",
"pm_score": 4,
"selected": false,
"text": "<p>In <a href=\"https://babeljs.io/docs/plugins/transform-class-properties/\" rel=\"noreferrer\">ES7</a> , you can do an elegant ENUM relying on static attributes: </p>\n\n<pre><code>class ColorEnum {\n static RED = 0 ;\n static GREEN = 1;\n static BLUE = 2;\n}\n</code></pre>\n\n<p>then </p>\n\n<pre><code>if (currentColor === ColorEnum.GREEN ) {/*-- coding --*/}\n</code></pre>\n\n<p>The advantage ( of using class instead of literal object) is to have a parent class <code>Enum</code> then all your Enums will <strong>extends</strong> that class. </p>\n\n<pre><code> class ColorEnum extends Enum {/*....*/}\n</code></pre>\n"
},
{
"answer_id": 43363905,
"author": "mika",
"author_id": 4910883,
"author_profile": "https://Stackoverflow.com/users/4910883",
"pm_score": 0,
"selected": false,
"text": "<p>You could try using <a href=\"https://bitbucket.org/snippets/frostbane/aAjxM\" rel=\"nofollow noreferrer\">https://bitbucket.org/snippets/frostbane/aAjxM</a>.</p>\n\n<pre><code>my.namespace.ColorEnum = new Enum(\n \"RED = 0\",\n \"GREEN\",\n \"BLUE\"\n)\n</code></pre>\n\n<p>It should work up to ie8.</p>\n"
},
{
"answer_id": 45325303,
"author": "David Lemon",
"author_id": 2739274,
"author_profile": "https://Stackoverflow.com/users/2739274",
"pm_score": 0,
"selected": false,
"text": "<p>You can use a simple funcion to invert keys and values, it will work with arrays also as it converts numerical integer strings to numbers. The code is small, simple and reusable for this and other use cases.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var objInvert = function (obj) {\r\n var invert = {}\r\n for (var i in obj) {\r\n if (i.match(/^\\d+$/)) i = parseInt(i,10)\r\n invert[obj[i]] = i\r\n }\r\n return invert\r\n}\r\n \r\nvar musicStyles = Object.freeze(objInvert(['ROCK', 'SURF', 'METAL',\r\n'BOSSA-NOVA','POP','INDIE']))\r\n\r\nconsole.log(musicStyles)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 48798027,
"author": "Joseph Merdrignac",
"author_id": 4696005,
"author_profile": "https://Stackoverflow.com/users/4696005",
"pm_score": 3,
"selected": false,
"text": "<p>es7 way, (iterator, freeze), usage:</p>\n\n<pre><code>const ThreeWiseMen = new Enum('Melchior', 'Caspar', 'Balthazar')\n\nfor (let name of ThreeWiseMen)\n console.log(name)\n\n\n// with a given key\nlet key = ThreeWiseMen.Melchior\n\nconsole.log(key in ThreeWiseMen) // true (string conversion, also true: 'Melchior' in ThreeWiseMen)\n\nfor (let entry from key.enum)\n console.log(entry)\n\n\n// prevent alteration (throws TypeError in strict mode)\nThreeWiseMen.Me = 'Me too!'\nThreeWiseMen.Melchior.name = 'Foo'\n</code></pre>\n\n<p>code:</p>\n\n<pre><code>class EnumKey {\n\n constructor(props) { Object.freeze(Object.assign(this, props)) }\n\n toString() { return this.name }\n\n}\n\nexport class Enum {\n\n constructor(...keys) {\n\n for (let [index, key] of keys.entries()) {\n\n Object.defineProperty(this, key, {\n\n value: new EnumKey({ name:key, index, enum:this }),\n enumerable: true,\n\n })\n\n }\n\n Object.freeze(this)\n\n }\n\n *[Symbol.iterator]() {\n\n for (let key of Object.keys(this))\n yield this[key]\n\n }\n\n toString() { return [...this].join(', ') }\n\n}\n</code></pre>\n"
},
{
"answer_id": 49309248,
"author": "Govind Rai",
"author_id": 2757916,
"author_profile": "https://Stackoverflow.com/users/2757916",
"pm_score": 5,
"selected": false,
"text": "<h2>Use Javascript <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy\" rel=\"noreferrer\">Proxies</a></h2>\n\n<p><strong>TLDR:</strong> Add this class to your utility methods and use it throughout your code, it mocks Enum behavior from traditional programming languages, and actually throws errors when you try to either access an enumerator that does not exist or add/update an enumerator. No need to rely on <code>Object.freeze()</code>.</p>\n\n<pre><code>class Enum {\n constructor(enumObj) {\n const handler = {\n get(target, name) {\n if (typeof target[name] != 'undefined') {\n return target[name];\n }\n throw new Error(`No such enumerator: ${name}`);\n },\n set() {\n throw new Error('Cannot add/update properties on an Enum instance after it is defined')\n }\n };\n\n return new Proxy(enumObj, handler);\n }\n}\n</code></pre>\n\n<p>Then create enums by instantiating the class:</p>\n\n<pre><code>const roles = new Enum({\n ADMIN: 'Admin',\n USER: 'User',\n});\n</code></pre>\n\n<hr>\n\n<p><strong>Full Explanation:</strong> </p>\n\n<p>One very beneficial feature of Enums that you get from traditional languages is that they blow up (throw a compile-time error) if you try to access an enumerator which does not exist. </p>\n\n<p>Besides freezing the mocked enum structure to prevent additional values from accidentally/maliciously being added, none of the other answers address that intrinsic feature of Enums.</p>\n\n<p>As you are probably aware, accessing non-existing members in JavaScript simply returns <code>undefined</code> and does not blow up your code. Since enumerators are predefined constants (i.e. days of the week), there should never be a case when an enumerator should be undefined.</p>\n\n<p>Don't get me wrong, JavaScript's behavior of returning <code>undefined</code> when accessing undefined properties is actually a very powerful feature of language, but it's not a feature you want when you are trying to mock traditional Enum structures. </p>\n\n<p>This is where Proxy objects shine. Proxies were standardized in the language with the introduction of ES6 (ES2015). Here's the description from MDN: </p>\n\n<blockquote>\n <p>The Proxy object is used to define custom behavior for fundamental operations (e.g. property lookup, assignment, enumeration, function\n invocation, etc).</p>\n</blockquote>\n\n<p>Similar to a web server proxy, JavaScript proxies are able to intercept operations on objects (with the use of \"traps\", call them hooks if you like) and allow you to perform various checks, actions and/or manipulations before they complete (or in some cases stopping the operations altogether which is exactly what we want to do if and when we try to reference an enumerator which does not exist).</p>\n\n<p>Here's a contrived example that uses the Proxy object to mimic Enums. The enumerators in this example are standard HTTP Methods (i.e. \"GET\", \"POST\", etc.):</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"true\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// Class for creating enums (13 lines)\r\n// Feel free to add this to your utility library in \r\n// your codebase and profit! Note: As Proxies are an ES6 \r\n// feature, some browsers/clients may not support it and \r\n// you may need to transpile using a service like babel\r\n\r\nclass Enum {\r\n // The Enum class instantiates a JavaScript Proxy object.\r\n // Instantiating a `Proxy` object requires two parameters, \r\n // a `target` object and a `handler`. We first define the handler,\r\n // then use the handler to instantiate a Proxy.\r\n\r\n // A proxy handler is simply an object whose properties\r\n // are functions which define the behavior of the proxy \r\n // when an operation is performed on it. \r\n \r\n // For enums, we need to define behavior that lets us check what enumerator\r\n // is being accessed and what enumerator is being set. This can be done by \r\n // defining \"get\" and \"set\" traps.\r\n constructor(enumObj) {\r\n const handler = {\r\n get(target, name) {\r\n if (typeof target[name] != 'undefined') {\r\n return target[name]\r\n }\r\n throw new Error(`No such enumerator: ${name}`)\r\n },\r\n set() {\r\n throw new Error('Cannot add/update properties on an Enum instance after it is defined')\r\n }\r\n }\r\n\r\n\r\n // Freeze the target object to prevent modifications\r\n return new Proxy(enumObj, handler)\r\n }\r\n}\r\n\r\n\r\n// Now that we have a generic way of creating Enums, lets create our first Enum!\r\nconst httpMethods = new Enum({\r\n DELETE: \"DELETE\",\r\n GET: \"GET\",\r\n OPTIONS: \"OPTIONS\",\r\n PATCH: \"PATCH\",\r\n POST: \"POST\",\r\n PUT: \"PUT\"\r\n})\r\n\r\n// Sanity checks\r\nconsole.log(httpMethods.DELETE)\r\n// logs \"DELETE\"\r\n\r\ntry {\r\n httpMethods.delete = \"delete\"\r\n} catch (e) {\r\nconsole.log(\"Error: \", e.message)\r\n}\r\n// throws \"Cannot add/update properties on an Enum instance after it is defined\"\r\n\r\ntry {\r\n console.log(httpMethods.delete)\r\n} catch (e) {\r\n console.log(\"Error: \", e.message)\r\n}\r\n// throws \"No such enumerator: delete\"</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<hr>\n\n<p><strong>ASIDE: What the heck is a proxy?</strong></p>\n\n<p>I remember when I first started seeing the word proxy everywhere, it definitely didn't make sense to me for a long time. If that's you right now, I think an easy way to generalize proxies is to think of them as software, institutions, or even people that act as intermediaries or middlemen between two servers, companies, or people. </p>\n"
},
{
"answer_id": 50115744,
"author": "Julius DzidzeviΔius",
"author_id": 4554116,
"author_profile": "https://Stackoverflow.com/users/4554116",
"pm_score": 2,
"selected": false,
"text": "<p>This is how Typescript translates it's <code>enum</code> into Javascript:</p>\n\n<pre><code>var makeEnum = function(obj) {\n obj[ obj['Active'] = 1 ] = 'Active';\n obj[ obj['Closed'] = 2 ] = 'Closed';\n obj[ obj['Deleted'] = 3 ] = 'Deleted';\n}\n</code></pre>\n\n<p>Now:</p>\n\n<pre><code>makeEnum( NewObj = {} )\n// => {1: \"Active\", 2: \"Closed\", 3: \"Deleted\", Active: 1, Closed: 2, Deleted: 3}\n</code></pre>\n\n<p>At first I was confused why <code>obj[1]</code> returns <code>'Active'</code>, but then realised that its dead simple - <strong>Assignment operator</strong> assigns value and then returns it:</p>\n\n<pre><code>obj['foo'] = 1\n// => 1\n</code></pre>\n"
},
{
"answer_id": 50355530,
"author": "Jack G",
"author_id": 5601591,
"author_profile": "https://Stackoverflow.com/users/5601591",
"pm_score": 5,
"selected": false,
"text": "<h1>- </h1>\n<p>Let's cut straight to the problem: file size. Every other answer listed here bloats your minified code to the extreme. I present to you that for the best possible reduction in code size by minification, performance, readability of code, large scale project management, and syntax hinting in many code editors, this is the correct way to do enumerations: underscore-notation variables.</p>\n<hr />\n<h1><img src=\"https://i.stack.imgur.com/vUCWq.png\" alt=\"Underscore-Notation Variables\" /></h1>\n<p>As demonstrated in the chart above and example below, here are five easy steps to get started:</p>\n<ol>\n<li>Determine a name for the enumeration group. Think of a noun that can describe the purpose of the enumeration or at least the entries in the enumeration. For example, a group of enumerations representing colors choosable by the user might be better named COLORCHOICES than COLORS.</li>\n<li>Decide whether enumerations in the group are mutually-exclusive or independent. If mutually-exclusive, start each enumerated variable name with <code>ENUM_</code>. If independent or side-by-side, use <code>INDEX_</code>.</li>\n<li>For each entry, create a new local variable whose name starts with <code>ENUM_</code> or <code>INDEX_</code>, then the name of the group, then an underscore, then a unique friendly name for the property</li>\n<li>Add a <code>ENUMLENGTH_</code>, <code>ENUMLEN_</code>, <code>INDEXLENGTH_</code>, or <code>INDEXLEN_</code> (whether <code>LEN_</code> or <code>LENGTH_</code> is personal preference) enumerated variable at the very end. You should use this variable wherever possible in your code to ensure that adding an extra entry to the enumeration and incrementing this value won't break your code.</li>\n<li>Give each successive enumerated variable a value one more than the last, starting at 0. There are comments on this page that say <code>0</code> should not be used as an enumerated value because <code>0 == null</code>, <code>0 == false</code>, <code>0 == \"\"</code>, and other JS craziness. I submit to you that, to avoid this problem and boost performance at the same time, always use <code>===</code> and never let <code>==</code> appear in your code except with <code>typeof</code> (e.x. <code>typeof X == \"string\"</code>). In all my years of using <code>===</code>, I have never once had a problem with using 0 as an enumeration value. If you are still squeamish, then <code>1</code> could be used as the starting value in <code>ENUM_</code> enumerations (but not in <code>INDEX_</code> enumerations) without performance penalty in many cases.</li>\n</ol>\n<pre><code>const ENUM_COLORENUM_RED = 0;\nconst ENUM_COLORENUM_GREEN = 1;\nconst ENUM_COLORENUM_BLUE = 2;\nconst ENUMLEN_COLORENUM = 3;\n\n// later on\n\nif(currentColor === ENUM_COLORENUM_RED) {\n // whatever\n}\n</code></pre>\n<p>Here is how I remember when to use <code>INDEX_</code> and when to use <code>ENUM_</code>:</p>\n<pre><code>// Precondition: var arr = []; //\narr[INDEX_] = ENUM_;\n</code></pre>\n<p>However, <code>ENUM_</code> can, in certain circumstances, be appropriate as an index such as when counting the occurrences of each item.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const ENUM_PET_CAT = 0,\n ENUM_PET_DOG = 1,\n ENUM_PET_RAT = 2,\n ENUMLEN_PET = 3;\n\nvar favoritePets = [ENUM_PET_CAT, ENUM_PET_DOG, ENUM_PET_RAT,\n ENUM_PET_DOG, ENUM_PET_DOG, ENUM_PET_CAT,\n ENUM_PET_RAT, ENUM_PET_CAT, ENUM_PET_DOG];\n\nvar petsFrequency = [];\n\nfor (var i=0; i<ENUMLEN_PET; i=i+1|0)\n petsFrequency[i] = 0;\n\nfor (var i=0, len=favoritePets.length|0, petId=0; i<len; i=i+1|0)\n petsFrequency[petId = favoritePets[i]|0] = (petsFrequency[petId]|0) + 1|0;\n\nconsole.log({\n \"cat\": petsFrequency[ENUM_PET_CAT],\n \"dog\": petsFrequency[ENUM_PET_DOG],\n \"rat\": petsFrequency[ENUM_PET_RAT]\n});</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Observe that, in the code above, it's really easy to add in a new kind of pet: you would just have to append a new entry after <code>ENUM_PET_RAT</code> and update <code>ENUMLEN_PET</code> accordingly. It might be more difficult and buggy to add a new entry in other systems of enumeration.</p>\n<hr />\n<h1> </h1>\n<p>Additionally, this syntax of enumerations allows for clear and concise class extending as seen below. To extend a class, add an incrementing number to the <code>LEN_</code> entry of the parent class. Then, finish out the subclass with its own <code>LEN_</code> entry so that the subclass may be extended further in the future.</p>\n<p><img src=\"https://i.stack.imgur.com/xIHxl.png\" alt=\"Addition extension diagram\" /></p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>(function(window){\n \"use strict\";\n var parseInt = window.parseInt;\n\n // use INDEX_ when representing the index in an array instance\n const INDEX_PIXELCOLOR_TYPE = 0, // is a ENUM_PIXELTYPE\n INDEXLEN_PIXELCOLOR = 1,\n INDEX_SOLIDCOLOR_R = INDEXLEN_PIXELCOLOR+0,\n INDEX_SOLIDCOLOR_G = INDEXLEN_PIXELCOLOR+1,\n INDEX_SOLIDCOLOR_B = INDEXLEN_PIXELCOLOR+2,\n INDEXLEN_SOLIDCOLOR = INDEXLEN_PIXELCOLOR+3,\n INDEX_ALPHACOLOR_R = INDEXLEN_PIXELCOLOR+0,\n INDEX_ALPHACOLOR_G = INDEXLEN_PIXELCOLOR+1,\n INDEX_ALPHACOLOR_B = INDEXLEN_PIXELCOLOR+2,\n INDEX_ALPHACOLOR_A = INDEXLEN_PIXELCOLOR+3,\n INDEXLEN_ALPHACOLOR = INDEXLEN_PIXELCOLOR+4,\n // use ENUM_ when representing a mutually-exclusive species or type\n ENUM_PIXELTYPE_SOLID = 0,\n ENUM_PIXELTYPE_ALPHA = 1,\n ENUM_PIXELTYPE_UNKNOWN = 2,\n ENUMLEN_PIXELTYPE = 2;\n\n function parseHexColor(inputString) {\n var rawstr = inputString.trim().substring(1);\n var result = [];\n if (rawstr.length === 8) {\n result[INDEX_PIXELCOLOR_TYPE] = ENUM_PIXELTYPE_ALPHA;\n result[INDEX_ALPHACOLOR_R] = parseInt(rawstr.substring(0,2), 16);\n result[INDEX_ALPHACOLOR_G] = parseInt(rawstr.substring(2,4), 16);\n result[INDEX_ALPHACOLOR_B] = parseInt(rawstr.substring(4,6), 16);\n result[INDEX_ALPHACOLOR_A] = parseInt(rawstr.substring(4,6), 16);\n } else if (rawstr.length === 4) {\n result[INDEX_PIXELCOLOR_TYPE] = ENUM_PIXELTYPE_ALPHA;\n result[INDEX_ALPHACOLOR_R] = parseInt(rawstr[0], 16) * 0x11;\n result[INDEX_ALPHACOLOR_G] = parseInt(rawstr[1], 16) * 0x11;\n result[INDEX_ALPHACOLOR_B] = parseInt(rawstr[2], 16) * 0x11;\n result[INDEX_ALPHACOLOR_A] = parseInt(rawstr[3], 16) * 0x11;\n } else if (rawstr.length === 6) {\n result[INDEX_PIXELCOLOR_TYPE] = ENUM_PIXELTYPE_SOLID;\n result[INDEX_SOLIDCOLOR_R] = parseInt(rawstr.substring(0,2), 16);\n result[INDEX_SOLIDCOLOR_G] = parseInt(rawstr.substring(2,4), 16);\n result[INDEX_SOLIDCOLOR_B] = parseInt(rawstr.substring(4,6), 16);\n } else if (rawstr.length === 3) {\n result[INDEX_PIXELCOLOR_TYPE] = ENUM_PIXELTYPE_SOLID;\n result[INDEX_SOLIDCOLOR_R] = parseInt(rawstr[0], 16) * 0x11;\n result[INDEX_SOLIDCOLOR_G] = parseInt(rawstr[1], 16) * 0x11;\n result[INDEX_SOLIDCOLOR_B] = parseInt(rawstr[2], 16) * 0x11;\n } else {\n result[INDEX_PIXELCOLOR_TYPE] = ENUM_PIXELTYPE_UNKNOWN;\n }\n return result;\n }\n\n // the red component of green\n console.log(parseHexColor(\"#0f0\")[INDEX_SOLIDCOLOR_R]);\n // the alpha of transparent purple\n console.log(parseHexColor(\"#f0f7\")[INDEX_ALPHACOLOR_A]); \n // the enumerated array for turquoise\n console.log(parseHexColor(\"#40E0D0\"));\n})(self);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>(Length: 2,450 bytes)</p>\n<p>Some may say that this is less practical than other solutions: it wastes tons of space, it takes a long time to write, and it is not coated with sugar syntax. Those people would be right if they do not minify their code. However, no reasonable person would leave unminified code in the end product. For this minification, Closure Compiler is the best I have yet to find. Online access can be found <a href=\"https://closure-compiler.appspot.com/\" rel=\"noreferrer\">here</a>. Closure compiler is able to take all of this enumeration data and inline it, making your Javascript be super duper small and run super duper fast. Thus, Minify with Closure Compiler. Observe.</p>\n<hr />\n<h1> <a href=\"https://closure-compiler.appspot.com/\" rel=\"noreferrer\"> </a></h1>\n<p>Closure compiler is able to perform some pretty incredible optimizations via inferences that are way beyond the capacities of any other Javascript minifier. Closure Compiler is able to inline primitive variables set to a fixed value. Closure Compiler is also able to make inferences based upon these inlined values and eliminate unused blocks in if-statements and loops.</p>\n<p><img src=\"https://i.stack.imgur.com/2cadt.jpg\" alt=\"Wringing code via Closure Compiler\" /></p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>'use strict';(function(e){function d(a){a=a.trim().substring(1);var b=[];8===a.length?(b[0]=1,b[1]=c(a.substring(0,2),16),b[2]=c(a.substring(2,4),16),b[3]=c(a.substring(4,6),16),b[4]=c(a.substring(4,6),16)):4===a.length?(b[1]=17*c(a[0],16),b[2]=17*c(a[1],16),b[3]=17*c(a[2],16),b[4]=17*c(a[3],16)):6===a.length?(b[0]=0,b[1]=c(a.substring(0,2),16),b[2]=c(a.substring(2,4),16),b[3]=c(a.substring(4,6),16)):3===a.length?(b[0]=0,b[1]=17*c(a[0],16),b[2]=17*c(a[1],16),b[3]=17*c(a[2],16)):b[0]=2;return b}var c=\ne.parseInt;console.log(d(\"#0f0\")[1]);console.log(d(\"#f0f7\")[4]);console.log(d(\"#40E0D0\"))})(self);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>(Length: 605 bytes)</p>\n<p>Closure Compiler rewards you for coding smarter and organizing your code well because, whereas many minifiers punish organized code with a bigger minified file size, Closure Compiler is able to sift through all your cleanliness and sanity to output an even smaller file size if you use tricks like variable name enumerations. That, in this one mind, is the holy grail of coding: a tool that both assists your code with a smaller minified size and assists your mind by training better programming habits.</p>\n<hr />\n<h1> </h1>\n<p>Now, let us see how big the equivalent file would be without any of these enumerations.\n<br /><br /></p>\n<p><a href=\"https://pastebin.com/embed_iframe/fcX5fN2V\" rel=\"noreferrer\">Source Without Using Enumerations</a> (length: 1,973 bytes (477 bytes shorter than enumerated code!))<br />\n<a href=\"https://pastebin.com/embed_iframe/97K6XLdU\" rel=\"noreferrer\">Minified Without Using Enumerations</a> (length: 843 bytes (238 bytes <strong>longer than enumerated code</strong>))</p>\n<p><img src=\"https://i.stack.imgur.com/DX0nA.png\" alt=\"Chart of code sizes\" /></p>\n<p><br /><br /></p>\n<p>As seen, without enumerations, the source code is shorter at the cost of a larger minified code. I do not know about you; but I know for sure that I do not incorporate source code into the end product. Thus, this form of enumerations is far superior insomuch that it results in smaller minified file sizes.</p>\n<hr />\n<h1> </h1>\n<p>Another advantage about this form of enumeration is that it can be used to easily manage large scale projects without sacrificing minified code size. When working on a large project with lots of other people, it might be beneficial to explicitly mark and label the variable names with who created the code so that the original creator of the code can be quickly identified for collaborative bug fixing.</p>\n<pre class=\"lang-js prettyprint-override\"><code>// JG = Jack Giffin\nconst ENUM_JG_COLORENUM_RED = 0,\n ENUM_JG_COLORENUM_GREEN = 1,\n ENUM_JG_COLORENUM_BLUE = 2,\n ENUMLEN_JG_COLORENUM = 3;\n\n// later on\n\nif(currentColor === ENUM_JG_COLORENUM_RED) {\n // whatever\n}\n\n// PL = Pepper Loftus\n// BK = Bob Knight\nconst ENUM_PL_ARRAYTYPE_UNSORTED = 0,\n ENUM_PL_ARRAYTYPE_ISSORTED = 1,\n ENUM_BK_ARRAYTYPE_CHUNKED = 2, // added by Bob Knight\n ENUM_JG_ARRAYTYPE_INCOMPLETE = 3, // added by jack giffin\n ENUMLEN_PL_COLORENUM = 4;\n\n// later on\n\nif(\n randomArray === ENUM_PL_ARRAYTYPE_UNSORTED ||\n randomArray === ENUM_BK_ARRAYTYPE_CHUNKED\n) {\n // whatever\n}\n</code></pre>\n\n<hr />\n<h1> <sub><sub><sub><sub><img src=\"https://i.stack.imgur.com/OoOrv.png\" /></sub></sub></sub></sub></h1>\n<p>Further, this form of enumeration is also much faster after minification. In normal named properties, the browser has to use hashmaps to look up where the property is on the object. Although JIT compilers intelligently cache this location on the object, there is still tremendous overhead due to special cases such as deleting a lower property from the object.</p>\n<img src=\"https://v8.dev/_img/elements-kinds/lattice.svg\" />\n<p>But, with continuous non-sparse integer-indexed <a href=\"https://v8.dev/blog/elements-kinds#the-elements-kind-lattice\" rel=\"noreferrer\">PACKED_ELEMENTS</a> arrays, the browser is able to skip much of that overhead because the index of the value in the internal array is already specified. Yes, according to the ECMAScript standard, all properties are supposed to be treated as strings. Nevertheless, this aspect of the ECMAScript standard is very misleading about performance because all browsers have special optimizations for numeric indexes in arrays.</p>\n<pre><code>/// Hashmaps are slow, even with JIT juice\nvar ref = {};\nref.count = 10;\nref.value = "foobar";\n</code></pre>\n<p>Compare the code above to the code below.</p>\n<pre><code>/// Arrays, however, are always lightning fast\nconst INDEX_REFERENCE_COUNT = 0;\nconst INDEX_REFERENCE_VALUE = 1;\nconst INDEXLENGTH_REFERENCE = 2;\n\nvar ref = [];\nref[INDEX_REFERENCE_COUNT] = 10;\nref[INDEX_REFERENCE_VALUE] = "foobar";\n</code></pre>\n<p>One might object to the code with enumerations seeming to be much longer than the code with ordinary objects, but looks can be deceiving. It is important to remember that source code size is not proportional to output size when using the epic Closure Compiler. Observe.</p>\n<pre><code>/// Hashmaps are slow, even with JIT juice\nvar a={count:10,value:"foobar"};\n</code></pre>\n<p>The minified code without enumerations is above and the minified code with enumerations is below.</p>\n<pre><code>/// Arrays, however, are always lightning fast\nvar a=[10,"foobar"];\n</code></pre>\n<p>The example above demonstrates that, in addition to having superior performance, the enumerated code also results in a smaller minified file size.</p>\n<hr />\n<h1> </h1>\n<p>Furthermore, this one's personal <em>cherry on the top</em> is using this form of enumerations along with the <a href=\"https://codemirror.net/\" rel=\"noreferrer\">CodeMirror</a> text editor in Javascript mode. CodeMirror's Javascript syntax highlighting mode highlights local variables in the current scope. That way, you know instantly when you type in a variable name correctly because if the variable name was previously declared with the <code>var</code> keyword, then the variable name turns a special color (cyan by default). Even if you do not use CodeMirror, then at least the browser throws a helpful <code><em>[variable name]</em> is not defined</code> exception when executing code with mistyped enumeration names. Also, JavaScript tools such as JSLint and Closure Compiler are very loud about telling you when you mistype in an enumeration variable name. CodeMirror, the browser, and various Javascript tools put together make debugging this form of enumeration very simple and really easy.</p>\n<p><img src=\"https://i.stack.imgur.com/sSyEB.png\" alt=\"CodeMirror highlighting demonstration\" /></p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const ENUM_COLORENUM_RED = 0,\n ENUM_COLORENUM_GREEN = 1,\n ENUM_COLORENUM_BLUE = 2,\n ENUMLEN_COLORENUM = 3;\nvar currentColor = ENUM_COLORENUM_GREEN;\n\nif(currentColor === ENUM_COLORENUM_RED) {\n // whatever\n}\n\nif(currentColor === ENUM_COLORENUM_DNE) {\n // whatever\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>In the above snippet, you were alerted with an error because <code>ENUM_COLORENUM_DNE</code> does not exist.</p>\n<hr />\n<h1></h1>\n<p>I think its safe to say that this methodology of enumeration is indeed the best way to go not just for minified code size, but also for performance, debugging, and collaboration.</p>\n"
},
{
"answer_id": 52019639,
"author": "jamess",
"author_id": 4941356,
"author_profile": "https://Stackoverflow.com/users/4941356",
"pm_score": 0,
"selected": false,
"text": "<p>This answer is an alternative approach for specific circumstances. I needed a set of bitmask constants based on attribute sub-values (cases where an attribute value is an array or list of values). It encompasses the equivalent of several overlapping enums. </p>\n\n<p>I created a class to both store and generate the bitmask values. I can then use the pseudo-constant bitmask values this way to test, for example, if green is present in an RGB value: </p>\n\n<pre><code>if (value & Ez.G) {...}\n</code></pre>\n\n<p>In my code I create only one instance of this class. There doesn't seem to be a clean way to do this without instantiating at least one instance of the class. Here is the class declaration and bitmask value generation code:</p>\n\n<pre><code>class Ez {\nconstructor() {\n let rgba = [\"R\", \"G\", \"B\", \"A\"];\n let rgbm = rgba.slice();\n rgbm.push(\"M\"); // for feColorMatrix values attribute\n this.createValues(rgba);\n this.createValues([\"H\", \"S\", \"L\"]);\n this.createValues([rgba, rgbm]);\n this.createValues([attX, attY, attW, attH]);\n}\ncreateValues(a) { // a for array\n let i, j;\n if (isA(a[0])) { // max 2 dimensions\n let k = 1;\n for (i of a[0]) {\n for (j of a[1]) {\n this[i + j] = k;\n k *= 2;\n }\n }\n }\n else { // 1D array is simple loop\n for (i = 0, j = 1; i < a.length; i++, j *= 2)\n this[a[i]] = j;\n }\n}\n</code></pre>\n\n<p>The 2D array is for the SVG feColorMatrix values attribute, which is a 4x5 matrix of RGBA by RGBAM, where M is a multiplier. The resulting Ez properties are Ez.RR, Ez.RG, etc.</p>\n"
},
{
"answer_id": 52409064,
"author": "papiro",
"author_id": 3878933,
"author_profile": "https://Stackoverflow.com/users/3878933",
"pm_score": 2,
"selected": false,
"text": "<pre><code>class Enum {\n constructor (...vals) {\n vals.forEach( val => {\n const CONSTANT = Symbol(val);\n Object.defineProperty(this, val.toUpperCase(), {\n get () {\n return CONSTANT;\n },\n set (val) {\n const enum_val = \"CONSTANT\";\n // generate TypeError associated with attempting to change the value of a constant\n enum_val = val;\n }\n });\n });\n }\n}\n</code></pre>\n\n<p>Example of usage:</p>\n\n<pre><code>const COLORS = new Enum(\"red\", \"blue\", \"green\");\n</code></pre>\n"
},
{
"answer_id": 55695903,
"author": "oluckyman",
"author_id": 823778,
"author_profile": "https://Stackoverflow.com/users/823778",
"pm_score": 1,
"selected": false,
"text": "<p>Read all the answers and didn't found any non-verbose and DRY solution.\nI use this one-liner:</p>\n\n<pre><code>const modes = ['DRAW', 'SCALE', 'DRAG'].reduce((o, v) => ({ ...o, [v]: v }), {});\n</code></pre>\n\n<p>it generates an object with human-readable values:</p>\n\n<pre><code>{\n DRAW: 'DRAW',\n SCALE: 'SCALE',\n DRAG: 'DRAG'\n}\n</code></pre>\n"
},
{
"answer_id": 60309416,
"author": "Andrew",
"author_id": 1599699,
"author_profile": "https://Stackoverflow.com/users/1599699",
"pm_score": 3,
"selected": false,
"text": "<p>I wasn't satisfied with any of the answers, so I made <em>Yet Another Enum (YEA!)</em>.</p>\n\n<p>This implementation:</p>\n\n<ul>\n<li>uses more up-to-date JS</li>\n<li>requires just the declaration of this one class to easily create enums</li>\n<li>has mapping by name (<code>colors.RED</code>), string (<code>colors[\"RED\"]</code>), and index (<code>colors[0]</code>), but you only need to pass in the strings as an array</li>\n<li>binds equivalent <code>toString()</code> and <code>valueOf()</code> functions to each enum object (if this is somehow not desired, one can simply remove it - small overhead for JS though)</li>\n<li>has optional global naming/storage by name string</li>\n<li>freezes the enum object once created so that it can't be modified</li>\n</ul>\n\n<p>Special thanks to <a href=\"https://stackoverflow.com/a/6672823/1599699\">Andre 'Fi''s answer</a> for some inspiration.</p>\n\n<hr>\n\n<p><strong>The codes:</strong></p>\n\n<pre class=\"lang-js prettyprint-override\"><code>class Enums {\n static create({ name = undefined, items = [] }) {\n let newEnum = {};\n newEnum.length = items.length;\n newEnum.items = items;\n for (let itemIndex in items) {\n //Map by name.\n newEnum[items[itemIndex]] = parseInt(itemIndex, 10);\n //Map by index.\n newEnum[parseInt(itemIndex, 10)] = items[itemIndex];\n }\n newEnum.toString = Enums.enumToString.bind(newEnum);\n newEnum.valueOf = newEnum.toString;\n //Optional naming and global registration.\n if (name != undefined) {\n newEnum.name = name;\n Enums[name] = newEnum;\n }\n //Prevent modification of the enum object.\n Object.freeze(newEnum);\n return newEnum;\n }\n static enumToString() {\n return \"Enum \" +\n (this.name != undefined ? this.name + \" \" : \"\") +\n \"[\" + this.items.toString() + \"]\";\n }\n}\n</code></pre>\n\n<hr>\n\n<p><strong>Usage:</strong></p>\n\n<pre class=\"lang-js prettyprint-override\"><code>let colors = Enums.create({\n name: \"COLORS\",\n items: [ \"RED\", \"GREEN\", \"BLUE\", \"PORPLE\" ]\n});\n\n//Global access, if named.\nEnums.COLORS;\n\ncolors.items; //Array(4) [ \"RED\", \"GREEN\", \"BLUE\", \"PORPLE\" ]\ncolors.length; //4\n\ncolors.RED; //0\ncolors.GREEN; //1\ncolors.BLUE; //2\ncolors.PORPLE; //3\ncolors[0]; //\"RED\"\ncolors[1]; //\"GREEN\"\ncolors[2]; //\"BLUE\"\ncolors[3]; //\"PORPLE\"\n\ncolors.toString(); //\"Enum COLORS [RED,GREEN,BLUE,PORPLE]\"\n\n//Enum frozen, makes it a real enum.\ncolors.RED = 9001;\ncolors.RED; //0\n</code></pre>\n"
},
{
"answer_id": 62358238,
"author": "Aral Roca",
"author_id": 4467741,
"author_profile": "https://Stackoverflow.com/users/4467741",
"pm_score": 3,
"selected": false,
"text": "<p>This can be useful:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const [CATS, DOGS, BIRDS] = ENUM();\n</code></pre>\n<p>The implementation is simple and efficient:</p>\n<pre class=\"lang-js prettyprint-override\"><code>function * ENUM(count=1) { while(true) yield count++ }\n</code></pre>\n<p>A generator can yield the exact sequence of integers required, without knowing how many constants there are. It can also support an optional argument that specifies which (possibly negative) number to start from (defaulting to <code>1</code>).</p>\n"
},
{
"answer_id": 62929829,
"author": "Idan",
"author_id": 6591688,
"author_profile": "https://Stackoverflow.com/users/6591688",
"pm_score": 0,
"selected": false,
"text": "<pre><code>export const ButtonType = Object.freeze({ \n DEFAULT: 'default', \n BIG: 'big', \n SMALL: 'small'\n})\n</code></pre>\n<p>source: <a href=\"https://medium.com/@idanlevi2/enum-in-javascript-5f2ff500f149\" rel=\"nofollow noreferrer\">https://medium.com/@idanlevi2/enum-in-javascript-5f2ff500f149</a></p>\n"
},
{
"answer_id": 64416419,
"author": "dsanchez",
"author_id": 1514122,
"author_profile": "https://Stackoverflow.com/users/1514122",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Update 05.11.2020:</strong><br>\nModified to include static fields and methods to closer replicate "true" enum behavior.</p>\n<p>Has anyone tried doing this with a class that contains private fields and "get" accessors?\nI realize private class fields are still experimental at this point but it seems to work for the purposes of creating a class with immutable fields/properties. Browser support is decent as well. The only "major" browsers that don't support it are Firefox (which I'm sure they will soon) and IE (who cares).</p>\n<p><em>DISCLAIMER</em>:<br>\nI am not a developer. I was just looking for an answer to this question and started thinking about how I sometimes create "enhanced" enums in C# by creating classes with private fields and restricted property accessors.</p>\n<p><em><strong>Sample Class</strong></em></p>\n<pre><code>class Sizes {\n // Private Fields\n static #_SMALL = 0;\n static #_MEDIUM = 1;\n static #_LARGE = 2;\n\n // Accessors for "get" functions only (no "set" functions)\n static get SMALL() { return this.#_SMALL; }\n static get MEDIUM() { return this.#_MEDIUM; }\n static get LARGE() { return this.#_LARGE; }\n}\n</code></pre>\n<p>You should now be able to call your enums directly.</p>\n<pre><code>Sizes.SMALL; // 0\nSizes.MEDIUM; // 1\nSizes.LARGE; // 2\n</code></pre>\n<p>The combination of using private fields and limited accessors means that the enum values are well protected.</p>\n<pre><code>Sizes.SMALL = 10 // Sizes.SMALL is still 0\nSizes._SMALL = 10 // Sizes.SMALL is still 0\nSizes.#_SMALL = 10 // Sizes.SMALL is still 0\n</code></pre>\n"
},
{
"answer_id": 64631389,
"author": "KooiInc",
"author_id": 58186,
"author_profile": "https://Stackoverflow.com/users/58186",
"pm_score": 0,
"selected": false,
"text": "<p>Here's my take on a (flagged) <code>Enum</code> factory. Here's a <a href=\"https://jsfiddle.net/KooiInc/1527adxq/\" rel=\"nofollow noreferrer\">working demo</a>.</p>\n<pre><code>/*\n * Notes: \n * The proxy handler enables case insensitive property queries\n * BigInt is used to enable bitflag strings /w length > 52\n*/\nfunction EnumFactory() {\n const proxyfy = {\n construct(target, args) { \n const caseInsensitiveHandler = { \n get(target, key) {\n return target[key.toUpperCase()] || target[key]; \n } \n };\n const proxified = new Proxy(new target(...args), caseInsensitiveHandler ); \n return Object.freeze(proxified);\n },\n }\n const ProxiedEnumCtor = new Proxy(EnumCtor, proxyfy);\n const throwIf = (\n assertion = false, \n message = `Unspecified error`, \n ErrorType = Error ) => \n assertion && (() => { throw new ErrorType(message); })();\n const hasFlag = (val, sub) => {\n throwIf(!val || !sub, "valueIn: missing parameters", RangeError);\n const andVal = (sub & val);\n return andVal !== BigInt(0) && andVal === val;\n };\n\n function EnumCtor(values) {\n throwIf(values.constructor !== Array || \n values.length < 2 || \n values.filter( v => v.constructor !== String ).length > 0,\n `EnumFactory: expected Array of at least 2 strings`, TypeError);\n const base = BigInt(1);\n this.NONE = BigInt(0);\n values.forEach( (v, i) => this[v.toUpperCase()] = base<<BigInt(i) );\n }\n\n EnumCtor.prototype = {\n get keys() { return Object.keys(this).slice(1); },\n subset(sub) {\n const arrayValues = this.keys;\n return new ProxiedEnumCtor(\n [...sub.toString(2)].reverse()\n .reduce( (acc, v, i) => ( +v < 1 ? acc : [...acc, arrayValues[i]] ), [] )\n );\n },\n getLabel(enumValue) {\n const tryLabel = Object.entries(this).find( value => value[1] === enumValue );\n return !enumValue || !tryLabel.length ? \n "getLabel: no value parameter or value not in enum" :\n tryLabel.shift();\n },\n hasFlag(val, sub = this) { return hasFlag(val, sub); },\n };\n \n return arr => new ProxiedEnumCtor(arr);\n}\n</code></pre>\n"
},
{
"answer_id": 71026153,
"author": "Sebastian Norr",
"author_id": 7880517,
"author_profile": "https://Stackoverflow.com/users/7880517",
"pm_score": 0,
"selected": false,
"text": "<p>I was searching for an answer to this question too & found this page with an answer that I think seams to be different from most answers here:\n<a href=\"https://www.sohamkamani.com/javascript/enums/\" rel=\"nofollow noreferrer\">https://www.sohamkamani.com/javascript/enums/</a></p>\n<p>I will copy over the answer part of the article to here, just in case the link gets invalid in the future or something:</p>\n<blockquote>\n<p><strong>Enums with Symbols:</strong></p>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol\" rel=\"nofollow noreferrer\">Symbols</a> let us define values that are guaranteed not to collide\nwith one another.</p>\n<p>For example:</p>\n</blockquote>\n<pre><code>const Summer1 = Symbol("summer")\nconst Summer2 = Symbol("summer")\n\n// Even though they have the same apparent value\n// Summer1 and Summer2 don't equate\nconsole.log(Summer1 === Summer2)\n// false\n\nconsole.log(Summer1)\n</code></pre>\n<blockquote>\n<p>We can define our enums using Symbols to ensure that they are not\nduplicated:</p>\n</blockquote>\n<pre><code>const Summer = Symbol("summer")\nconst Autumn = Symbol("autumn")\nconst Winter = Symbol("winter")\nconst Spring = Symbol("spring")\n\nlet season = Spring\n\nswitch (season) {\n case Summer:\n console.log('the season is summer')\n break;\n case Winter:\n console.log('the season is winter')\n break;\n case Spring:\n console.log('the season is spring')\n break;\n case Autumn:\n console.log('the season is autumn')\n break;\n default:\n console.log('season not defined')\n}\n</code></pre>\n<blockquote>\n<p>Using Symbols ensures that the only way we can assign an enum value is by using the constants that we defined initially.</p>\n</blockquote>\n<blockquote>\n<p><strong>Enums with Classes:</strong></p>\n</blockquote>\n<blockquote>\n<p>To make our code more semantically correct, we can create a class to\nhold groups of enums.</p>\n<p>For example, our seasons should have a way for us to identify that\nthey all belong to a similar classification.</p>\n<p>Letβs see how we can use classes and objects to create distinct enum\ngroups:</p>\n</blockquote>\n<pre><code>// Season enums can be grouped as static members of a class\nclass Season {\n // Create new instances of the same class as static attributes\n static Summer = new Season("summer")\n static Autumn = new Season("autumn")\n static Winter = new Season("winter")\n static Spring = new Season("spring")\n\n constructor(name) {\n this.name = name\n }\n}\n\n// Now we can access enums using namespaced assignments\n// this makes it semantically clear that "Summer" is a "Season"\nlet season = Season.Summer\n\n// We can verify whether a particular variable is a Season enum\nconsole.log(season instanceof Season)\n// true\nconsole.log(Symbol('something') instanceof Season)\n//false\n\n// We can explicitly check the type based on each enums class\nconsole.log(season.constructor.name)\n// 'Season'\n</code></pre>\n<p><em>personal note: I would have used this constructor instead: (Note: sets: <code>this.name</code>, to a string instead of an object, looses some of the verifications below. Optionally remove the: <code>.description</code>. I would also like to find a way to not have to type <code>Seasons.summer.name</code> but instead only need: <code>Seasons.summer</code> to make it return a string)</em></p>\n<pre><code> constructor(name) {\n this.name = Symbol(name).description\n }\n</code></pre>\n<blockquote>\n<p><strong>Listing All Possible Enum Values:</strong></p>\n</blockquote>\n<blockquote>\n<p>If we used the class-based approach above, we can loop through the\nkeys of the Season class to obtain all the enum values under the same\ngroup:</p>\n</blockquote>\n<pre><code>Object.keys(Season).forEach(season => console.log("season:", season))\n// season: Summer\n// season: Autumn\n// season: Winter\n// season: Spring\n</code></pre>\n<blockquote>\n<p><strong>When to Use Enums in Javascript?</strong></p>\n</blockquote>\n<blockquote>\n<p>In general, enums are helpful if there are a definite number of fixed\nvalues for any one variable_</p>\n<p>For example, the <a href=\"https://nodejs.org/api/crypto.html#crypto\" rel=\"nofollow noreferrer\">crypto</a> standard library for Node.js has a <a href=\"https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/create-hmac/index.d.ts#L15\" rel=\"nofollow noreferrer\">list of supported algorithms</a>, that can be considered an enum group.</p>\n<p>Using enums in Javascript correctly will lead to better code that is\nmore stable, easier to read and less error prone.</p>\n</blockquote>\n"
},
{
"answer_id": 71432477,
"author": "LEMUEL ADANE",
"author_id": 1347816,
"author_profile": "https://Stackoverflow.com/users/1347816",
"pm_score": 2,
"selected": false,
"text": "<p>You just need to make an immutable object by using <strong>Object.freeze(</strong><em><your_object></em><strong>)</strong>:</p>\n<pre><code>export const ColorEnum = Object.freeze({\n // you can only change the property values here\n // in the object declaration like in the Java enumaration\n RED: 0,\n GREEN: 1,\n BLUE: 2,\n});\n\nColorEnum.RED = 22 // assigning here will throw an error\nColorEnum.VIOLET = 45 // even adding a new property will throw an error\n</code></pre>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/287903",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5309/"
] |
Would the following make the objects fulfil all characteristics that enums have in JavaScript? Something like:
```js
my.namespace.ColorEnum = {
RED : 0,
GREEN : 1,
BLUE : 2
}
// later on
if(currentColor == my.namespace.ColorEnum.RED) {
// whatever
}
```
Or is there some other way I can do this?
|
Since 1.8.5 it's possible to [seal and freeze the object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze), so define the above as:
```
const DaysEnum = Object.freeze({"monday":1, "tuesday":2, "wednesday":3, ...})
```
or
```
const DaysEnum = {"monday":1, "tuesday":2, "wednesday":3, ...}
Object.freeze(DaysEnum)
```
and voila! JS enums.
However, this doesn't prevent you from assigning an undesired value to a variable, which is often the main goal of enums:
```
let day = DaysEnum.tuesday
day = 298832342 // goes through without any errors
```
One way to ensure a stronger degree of type safety (with enums or otherwise) is to use a tool like [TypeScript](https://www.typescriptlang.org/) or [Flow](https://flow.org/).
Quotes aren't needed but I kept them for consistency.
|
287,907 |
<p>I want to transfer data between a smart phone app and a website. What are the conventional and not-so-conventional ways of doing it? </p>
<p>Here's what I have thought of so far:</p>
<ol>
<li>Simple HTTP GET/POST with data being represented as JSON array string, variations of this being encrypted/compressed string as parameter.</li>
<li>Webservice calls ( I am not sure if this is even possible, just a guess)</li>
<li>Two step communication : Smartphone to/fro Desktop App to/fro Website) (Cumbersome to develop/use)</li>
</ol>
<p>Also, what do I need to consider to avoid spamming/snooping?</p>
|
[
{
"answer_id": 287917,
"author": "Gareth",
"author_id": 31582,
"author_profile": "https://Stackoverflow.com/users/31582",
"pm_score": 9,
"selected": false,
"text": "<p>This isn't much of an answer, but I'd say that works just fine, personally</p>\n\n<p>Having said that, since it doesn't matter what the values are (you've used 0, 1, 2), I'd use a meaningful string in case you ever wanted to output the current value.</p>\n"
},
{
"answer_id": 1314191,
"author": "Randolpho",
"author_id": 12716,
"author_profile": "https://Stackoverflow.com/users/12716",
"pm_score": 7,
"selected": false,
"text": "<p>Bottom line: You can't. </p>\n\n<p>You can fake it, but you won't get type safety. Typically this is done by creating a simple dictionary of string values mapped to integer values. For example:</p>\n\n<pre><code>var DaysEnum = {\"monday\":1, \"tuesday\":2, \"wednesday\":3, ...}\n\nDocument.Write(\"Enumerant: \" + DaysEnum.tuesday);\n</code></pre>\n\n<p>The problem with this approach? You can accidentally redefine your enumerant, or accidentally have duplicate enumerant values. For example:</p>\n\n<pre><code>DaysEnum.monday = 4; // whoops, monday is now thursday, too\n</code></pre>\n\n<p><strong>Edit</strong> </p>\n\n<blockquote>\n <p>What about Artur Czajka's Object.freeze? Wouldn't that work to prevent you from setting monday to thursday? β Fry Quad </p>\n</blockquote>\n\n<p>Absolutely, <a href=\"http://msdn.microsoft.com/en-us/library/windows/apps/ff806186%28v=vs.94%29.aspx\" rel=\"noreferrer\"><code>Object.freeze</code></a> would totally fix the problem I complained about. I would like to remind everyone that when I wrote the above, <code>Object.freeze</code> didn't really exist. </p>\n\n<p>Now.... now it opens up some <em>very</em> interesting possibilities. </p>\n\n<p><strong>Edit 2</strong><br>\nHere's a very good library for creating enums. </p>\n\n<p><a href=\"http://www.2ality.com/2011/10/enums.html\" rel=\"noreferrer\">http://www.2ality.com/2011/10/enums.html</a></p>\n\n<p>While it probably doesn't fit every valid use of enums, it goes a very long way. </p>\n"
},
{
"answer_id": 2383215,
"author": "Stijn de Witt",
"author_id": 286685,
"author_profile": "https://Stackoverflow.com/users/286685",
"pm_score": 9,
"selected": false,
"text": "<h2>UPDATE</h2>\n<p>I don't think my answer below is the best way to write enums in JavaScript anymore. See my blog post for more details: <a href=\"https://stijndewitt.com/2014/01/26/enums-in-javascript/\" rel=\"nofollow noreferrer\">Enums in JavaScript</a>.</p>\n<hr />\n<p>Alerting the name is already possible:</p>\n<pre><code>if (currentColor == my.namespace.ColorEnum.RED) {\n // alert name of currentColor (RED: 0)\n var col = my.namespace.ColorEnum;\n for (var name in col) {\n if (col[name] == col.RED)\n alert(name);\n }\n}\n</code></pre>\n<p>Alternatively, you could make the values objects, so you can have the cake and eat it too:</p>\n<pre><code>var SIZE = {\n SMALL : {value: 0, name: "Small", code: "S"}, \n MEDIUM: {value: 1, name: "Medium", code: "M"}, \n LARGE : {value: 2, name: "Large", code: "L"}\n};\n\nvar currentSize = SIZE.MEDIUM;\nif (currentSize == SIZE.MEDIUM) {\n // this alerts: "1: Medium"\n alert(currentSize.value + ": " + currentSize.name);\n}\n</code></pre>\n<p>In JavaScript, as it is a dynamic language, it is even possible to add enum values to the set later:</p>\n<pre><code>// Add EXTRALARGE size\nSIZE.EXTRALARGE = {value: 3, name: "Extra Large", code: "XL"};\n</code></pre>\n<p>Remember, the fields of the enum (value, name and code in this example) are not needed for the identity check and are only there for convenience. Also the name of the size property itself does not need to be hard coded, but can also be set dynamically. So supposing you only know the name for your new enum value, you can still add it without problems:</p>\n<pre><code>// Add 'Extra Large' size, only knowing it's name\nvar name = "Extra Large";\nSIZE[name] = {value: -1, name: name, code: "?"};\n</code></pre>\n<p>Of course this means that some assumptions can no longer be made (that value represents the correct order for the size for example).</p>\n<p>Remember, in JavaScript an object is just like a <em>map</em> or <em>hash table</em>. A set of name-value pairs. You can loop through them or otherwise manipulate them without knowing much about them in advance.</p>\n<h2>Example</h2>\n<pre><code>for (var sz in SIZE) {\n // sz will be the names of the objects in SIZE, so\n // 'SMALL', 'MEDIUM', 'LARGE', 'EXTRALARGE'\n var size = SIZE[sz]; // Get the object mapped to the name in sz\n for (var prop in size) {\n // Get all the properties of the size object, iterates over\n // 'value', 'name' and 'code'. You can inspect everything this way. \n }\n} \n</code></pre>\n<p>And by the way, if you are interested in namespaces, you may want to have a look at my solution for simple but powerful namespace and dependency management for JavaScript: <a href=\"http://packagesinjavascript.wordpress.com/\" rel=\"nofollow noreferrer\">Packages JS</a></p>\n"
},
{
"answer_id": 5040502,
"author": "Artur Czajka",
"author_id": 572370,
"author_profile": "https://Stackoverflow.com/users/572370",
"pm_score": 11,
"selected": true,
"text": "<p>Since 1.8.5 it's possible to <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze\" rel=\"noreferrer\">seal and freeze the object</a>, so define the above as:</p>\n<pre><code>const DaysEnum = Object.freeze({"monday":1, "tuesday":2, "wednesday":3, ...})\n</code></pre>\n<p>or</p>\n<pre><code>const DaysEnum = {"monday":1, "tuesday":2, "wednesday":3, ...}\nObject.freeze(DaysEnum)\n</code></pre>\n<p>and voila! JS enums.</p>\n<p>However, this doesn't prevent you from assigning an undesired value to a variable, which is often the main goal of enums:</p>\n<pre><code>let day = DaysEnum.tuesday\nday = 298832342 // goes through without any errors\n</code></pre>\n<p>One way to ensure a stronger degree of type safety (with enums or otherwise) is to use a tool like <a href=\"https://www.typescriptlang.org/\" rel=\"noreferrer\">TypeScript</a> or <a href=\"https://flow.org/\" rel=\"noreferrer\">Flow</a>.</p>\n<p>Quotes aren't needed but I kept them for consistency.</p>\n"
},
{
"answer_id": 6672823,
"author": "Andre 'Fi'",
"author_id": 841793,
"author_profile": "https://Stackoverflow.com/users/841793",
"pm_score": 6,
"selected": false,
"text": "<p>Here's what we all want:</p>\n\n<pre><code>function Enum(constantsList) {\n for (var i in constantsList) {\n this[constantsList[i]] = i;\n }\n}\n</code></pre>\n\n<p>Now you can create your enums:</p>\n\n<pre><code>var YesNo = new Enum(['NO', 'YES']);\nvar Color = new Enum(['RED', 'GREEN', 'BLUE']);\n</code></pre>\n\n<p>By doing this, constants can be acessed in the usual way (YesNo.YES, Color.GREEN) and they get a sequential int value (NO = 0, YES = 1; RED = 0, GREEN = 1, BLUE = 2).</p>\n\n<p>You can also add methods, by using Enum.prototype:</p>\n\n<pre><code>Enum.prototype.values = function() {\n return this.allValues;\n /* for the above to work, you'd need to do\n this.allValues = constantsList at the constructor */\n};\n</code></pre>\n\n<p><br>\nEdit - small improvement - now with varargs: (unfortunately it doesn't work properly on IE :S... should stick with previous version then)</p>\n\n<pre><code>function Enum() {\n for (var i in arguments) {\n this[arguments[i]] = i;\n }\n}\n\nvar YesNo = new Enum('NO', 'YES');\nvar Color = new Enum('RED', 'GREEN', 'BLUE');\n</code></pre>\n"
},
{
"answer_id": 10299613,
"author": "Yaroslav",
"author_id": 1351319,
"author_profile": "https://Stackoverflow.com/users/1351319",
"pm_score": 4,
"selected": false,
"text": "<p>If you're using <a href=\"http://documentcloud.github.com/backbone/\">Backbone</a>, you can get full-blown enum functionality (find by id, name, custom members) for free using <a href=\"http://documentcloud.github.com/backbone/#Collection\">Backbone.Collection</a>.</p>\n\n<pre><code>// enum instance members, optional\nvar Color = Backbone.Model.extend({\n print : function() {\n console.log(\"I am \" + this.get(\"name\"))\n }\n});\n\n// enum creation\nvar Colors = new Backbone.Collection([\n { id : 1, name : \"Red\", rgb : 0xFF0000},\n { id : 2, name : \"Green\" , rgb : 0x00FF00},\n { id : 3, name : \"Blue\" , rgb : 0x0000FF}\n], {\n model : Color\n});\n\n// Expose members through public fields.\nColors.each(function(color) {\n Colors[color.get(\"name\")] = color;\n});\n\n// using\nColors.Red.print()\n</code></pre>\n"
},
{
"answer_id": 10597813,
"author": "Chris",
"author_id": 1395768,
"author_profile": "https://Stackoverflow.com/users/1395768",
"pm_score": 4,
"selected": false,
"text": "<p>This is the solution that I use.</p>\n\n<pre><code>function Enum() {\n this._enums = [];\n this._lookups = {};\n}\n\nEnum.prototype.getEnums = function() {\n return _enums;\n}\n\nEnum.prototype.forEach = function(callback){\n var length = this._enums.length;\n for (var i = 0; i < length; ++i){\n callback(this._enums[i]);\n }\n}\n\nEnum.prototype.addEnum = function(e) {\n this._enums.push(e);\n}\n\nEnum.prototype.getByName = function(name) {\n return this[name];\n}\n\nEnum.prototype.getByValue = function(field, value) {\n var lookup = this._lookups[field];\n if(lookup) {\n return lookup[value];\n } else {\n this._lookups[field] = ( lookup = {});\n var k = this._enums.length - 1;\n for(; k >= 0; --k) {\n var m = this._enums[k];\n var j = m[field];\n lookup[j] = m;\n if(j == value) {\n return m;\n }\n }\n }\n return null;\n}\n\nfunction defineEnum(definition) {\n var k;\n var e = new Enum();\n for(k in definition) {\n var j = definition[k];\n e[k] = j;\n e.addEnum(j)\n }\n return e;\n}\n</code></pre>\n\n<p>And you define your enums like this:</p>\n\n<pre><code>var COLORS = defineEnum({\n RED : {\n value : 1,\n string : 'red'\n },\n GREEN : {\n value : 2,\n string : 'green'\n },\n BLUE : {\n value : 3,\n string : 'blue'\n }\n});\n</code></pre>\n\n<p>And this is how you access your enums:</p>\n\n<pre><code>COLORS.BLUE.string\nCOLORS.BLUE.value\nCOLORS.getByName('BLUE').string\nCOLORS.getByValue('value', 1).string\n\nCOLORS.forEach(function(e){\n // do what you want with e\n});\n</code></pre>\n\n<p>I usually use the last 2 methods for mapping enums from message objects.</p>\n\n<p>Some advantages to this approach:</p>\n\n<ul>\n<li>Easy to declare enums</li>\n<li>Easy to access your enums</li>\n<li>Your enums can be complex types</li>\n<li>The Enum class has some associative caching if you are using getByValue a lot</li>\n</ul>\n\n<p>Some disadvantages:</p>\n\n<ul>\n<li>Some messy memory management going on in there, as I keep the references to the enums</li>\n<li>Still no type safety</li>\n</ul>\n"
},
{
"answer_id": 15948460,
"author": "David MirΓ³",
"author_id": 2270217,
"author_profile": "https://Stackoverflow.com/users/2270217",
"pm_score": 3,
"selected": false,
"text": "<p>I've modified the solution of Andre 'Fi':</p>\n\n<pre><code> function Enum() {\n var that = this;\n for (var i in arguments) {\n that[arguments[i]] = i;\n }\n this.name = function(value) {\n for (var key in that) {\n if (that[key] == value) {\n return key;\n }\n }\n };\n this.exist = function(value) {\n return (typeof that.name(value) !== \"undefined\");\n };\n if (Object.freeze) {\n Object.freeze(that);\n }\n }\n</code></pre>\n\n<p>Test:</p>\n\n<pre><code>var Color = new Enum('RED', 'GREEN', 'BLUE');\nundefined\nColor.name(Color.REDs)\nundefined\nColor.name(Color.RED)\n\"RED\"\nColor.exist(Color.REDs)\nfalse\nColor.exist(Color.RED)\ntrue\n</code></pre>\n"
},
{
"answer_id": 17280078,
"author": "Rob Hardy",
"author_id": 1733091,
"author_profile": "https://Stackoverflow.com/users/1733091",
"pm_score": 4,
"selected": false,
"text": "<p>This is an old one I know, but the way it has since been implemented via the TypeScript interface is:</p>\n\n<pre><code>var MyEnum;\n(function (MyEnum) {\n MyEnum[MyEnum[\"Foo\"] = 0] = \"Foo\";\n MyEnum[MyEnum[\"FooBar\"] = 2] = \"FooBar\";\n MyEnum[MyEnum[\"Bar\"] = 1] = \"Bar\";\n})(MyEnum|| (MyEnum= {}));\n</code></pre>\n\n<p>This enables you to look up on both <code>MyEnum.Bar</code> which returns 1, and <code>MyEnum[1]</code> which returns \"Bar\" regardless of the order of declaration.</p>\n"
},
{
"answer_id": 18355123,
"author": "Duncan",
"author_id": 945011,
"author_profile": "https://Stackoverflow.com/users/945011",
"pm_score": 5,
"selected": false,
"text": "<p>I've been playing around with this, as I love my enums. =)</p>\n\n<p>Using <code>Object.defineProperty</code> I think I came up with a somewhat viable solution.</p>\n\n<p>Here's a jsfiddle: <a href=\"http://jsfiddle.net/ZV4A6/\" rel=\"noreferrer\">http://jsfiddle.net/ZV4A6/</a></p>\n\n<p>Using this method.. you should (in theory) be able to call and define enum values for any object, without affecting other attributes of that object.</p>\n\n<pre><code>Object.defineProperty(Object.prototype,'Enum', {\n value: function() {\n for(i in arguments) {\n Object.defineProperty(this,arguments[i], {\n value:parseInt(i),\n writable:false,\n enumerable:true,\n configurable:true\n });\n }\n return this;\n },\n writable:false,\n enumerable:false,\n configurable:false\n}); \n</code></pre>\n\n<p>Because of the attribute <code>writable:false</code> this <i>should</i> make it type safe.</p>\n\n<p>So you should be able to create a custom object, then call <code>Enum()</code> on it. The values assigned start at 0 and increment per item.</p>\n\n<pre><code>var EnumColors={};\nEnumColors.Enum('RED','BLUE','GREEN','YELLOW');\nEnumColors.RED; // == 0\nEnumColors.BLUE; // == 1\nEnumColors.GREEN; // == 2\nEnumColors.YELLOW; // == 3\n</code></pre>\n"
},
{
"answer_id": 19034005,
"author": "GTF",
"author_id": 907981,
"author_profile": "https://Stackoverflow.com/users/907981",
"pm_score": 2,
"selected": false,
"text": "<p>I had done it a while ago using a mixture of <code>__defineGetter__</code> and <code>__defineSetter__</code> or <code>defineProperty</code> depending on the JS version.</p>\n\n<p>Here's the enum generating function I made: <a href=\"https://gist.github.com/gfarrell/6716853\" rel=\"nofollow\">https://gist.github.com/gfarrell/6716853</a></p>\n\n<p>You'd use it like this:</p>\n\n<pre><code>var Colours = Enum('RED', 'GREEN', 'BLUE');\n</code></pre>\n\n<p>And it would create an immutable string:int dictionary (an enum).</p>\n"
},
{
"answer_id": 19112051,
"author": "user2254487",
"author_id": 2254487,
"author_profile": "https://Stackoverflow.com/users/2254487",
"pm_score": 2,
"selected": false,
"text": "<p>A quick and simple way would be :</p>\n\n<pre><code>var Colors = function(){\nreturn {\n 'WHITE':0,\n 'BLACK':1,\n 'RED':2,\n 'GREEN':3\n }\n}();\n\nconsole.log(Colors.WHITE) //this prints out \"0\"\n</code></pre>\n"
},
{
"answer_id": 23455550,
"author": "arcseldon",
"author_id": 1882064,
"author_profile": "https://Stackoverflow.com/users/1882064",
"pm_score": 2,
"selected": false,
"text": "<p>As of writing, <strong>October 2014</strong> - so here is a contemporary solution. Am writing the solution as a Node Module, and have included a test using Mocha and Chai, as well as underscoreJS. You can easily ignore these, and just take the Enum code if preferred.</p>\n\n<p>Seen a lot of posts with overly convoluted libraries etc. The solution to getting enum support in Javascript is so simple it really isn't needed. Here is the code:</p>\n\n<p>File: enums.js</p>\n\n<pre><code>_ = require('underscore');\n\nvar _Enum = function () {\n\n var keys = _.map(arguments, function (value) {\n return value;\n });\n var self = {\n keys: keys\n };\n for (var i = 0; i < arguments.length; i++) {\n self[keys[i]] = i;\n }\n return self;\n};\n\nvar fileFormatEnum = Object.freeze(_Enum('CSV', 'TSV'));\nvar encodingEnum = Object.freeze(_Enum('UTF8', 'SHIFT_JIS'));\n\nexports.fileFormatEnum = fileFormatEnum;\nexports.encodingEnum = encodingEnum;\n</code></pre>\n\n<p>And a test to illustrate what it gives you:</p>\n\n<p>file: enumsSpec.js</p>\n\n<pre><code>var chai = require(\"chai\"),\n assert = chai.assert,\n expect = chai.expect,\n should = chai.should(),\n enums = require('./enums'),\n _ = require('underscore');\n\n\ndescribe('enums', function () {\n\n describe('fileFormatEnum', function () {\n it('should return expected fileFormat enum declarations', function () {\n var fileFormatEnum = enums.fileFormatEnum;\n should.exist(fileFormatEnum);\n assert('{\"keys\":[\"CSV\",\"TSV\"],\"CSV\":0,\"TSV\":1}' === JSON.stringify(fileFormatEnum), 'Unexpected format');\n assert('[\"CSV\",\"TSV\"]' === JSON.stringify(fileFormatEnum.keys), 'Unexpected keys format');\n });\n });\n\n describe('encodingEnum', function () {\n it('should return expected encoding enum declarations', function () {\n var encodingEnum = enums.encodingEnum;\n should.exist(encodingEnum);\n assert('{\"keys\":[\"UTF8\",\"SHIFT_JIS\"],\"UTF8\":0,\"SHIFT_JIS\":1}' === JSON.stringify(encodingEnum), 'Unexpected format');\n assert('[\"UTF8\",\"SHIFT_JIS\"]' === JSON.stringify(encodingEnum.keys), 'Unexpected keys format');\n });\n });\n\n});\n</code></pre>\n\n<p>As you can see, you get an Enum factory, you can get all the keys simply by calling enum.keys, and you can match the keys themselves to integer constants. And you can reuse the factory with different values, and export those generated Enums using Node's modular approach. </p>\n\n<p>Once again, if you are just a casual user, or in the browser etc, just take the factory part of the code, potentially removing underscore library too if you don't wish to use it in your code.</p>\n"
},
{
"answer_id": 23669178,
"author": "Xeltor",
"author_id": 1330674,
"author_profile": "https://Stackoverflow.com/users/1330674",
"pm_score": 3,
"selected": false,
"text": "<p>your answers are far too complicated</p>\n\n<pre><code>var buildSet = function(array) {\n var set = {};\n for (var i in array) {\n var item = array[i];\n set[item] = item;\n }\n return set;\n}\n\nvar myEnum = buildSet(['RED','GREEN','BLUE']);\n// myEnum.RED == 'RED' ...etc\n</code></pre>\n"
},
{
"answer_id": 25692451,
"author": "Andrew Philips",
"author_id": 314114,
"author_profile": "https://Stackoverflow.com/users/314114",
"pm_score": 1,
"selected": false,
"text": "<p>Really like what @Duncan did above, but I don't like mucking up global Object function space with Enum, so I wrote the following:</p>\n\n<pre><code>function mkenum_1()\n{\n var o = new Object();\n var c = -1;\n var f = function(e, v) { Object.defineProperty(o, e, { value:v, writable:false, enumerable:true, configurable:true })};\n\n for (i in arguments) {\n var e = arguments[i];\n if ((!!e) & (e.constructor == Object))\n for (j in e)\n f(j, (c=e[j]));\n else\n f(e, ++c);\n }\n\n return Object.freeze ? Object.freeze(o) : o;\n}\n\nvar Sizes = mkenum_1('SMALL','MEDIUM',{LARGE: 100},'XLARGE');\n\nconsole.log(\"MED := \" + Sizes.MEDIUM);\nconsole.log(\"LRG := \" + Sizes.LARGE);\n\n// Output is:\n// MED := 1\n// LRG := 100\n</code></pre>\n\n<p>@Stijin also has a neat solution (referring to his blog) which includes properties on these objects. I wrote some code for that, too, which I'm including next.</p>\n\n<pre><code>function mkenum_2(seed)\n{\n var p = {};\n\n console.log(\"Seed := \" + seed);\n\n for (k in seed) {\n var v = seed[k];\n\n if (v instanceof Array)\n p[(seed[k]=v[0])] = { value: v[0], name: v[1], code: v[2] };\n else\n p[v] = { value: v, name: k.toLowerCase(), code: k.substring(0,1) };\n }\n seed.properties = p;\n\n return Object.freeze ? Object.freeze(seed) : seed;\n}\n</code></pre>\n\n<p>This version produces an additional property list allowing friendly name conversion and short codes. I like this version because one need not duplicate data entry in properties as the code does it for you.</p>\n\n<pre><code>var SizeEnum2 = mkenum_2({ SMALL: 1, MEDIUM: 2, LARGE: 3});\nvar SizeEnum3 = mkenum_2({ SMALL: [1, \"small\", \"S\"], MEDIUM: [2, \"medium\", \"M\"], LARGE: [3, \"large\", \"L\"] });\n</code></pre>\n\n<p>These two can be combined into a single processing unit, mkenum, (consume enums, assign values, create and add property list). However, as I've spent far too much time on this today already, I will leave the combination as an exercise for the dear reader.</p>\n"
},
{
"answer_id": 28205581,
"author": "Shivanshu Goyal",
"author_id": 1544818,
"author_profile": "https://Stackoverflow.com/users/1544818",
"pm_score": 3,
"selected": false,
"text": "<pre><code>var ColorEnum = {\n red: {},\n green: {},\n blue: {}\n}\n</code></pre>\n\n<p>You don't need to make sure you don't assign duplicate numbers to different enum values this way. A new object gets instantiated and assigned to all enum values.</p>\n"
},
{
"answer_id": 28526471,
"author": "Gildas.Tambo",
"author_id": 2065597,
"author_profile": "https://Stackoverflow.com/users/2065597",
"pm_score": 1,
"selected": false,
"text": "<p>You can use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty\" rel=\"nofollow\">Object.prototype.hasOwnProperty()</a> </p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var findInEnum,\r\n colorEnum = {\r\n red : 0,\r\n green : 1,\r\n blue : 2\r\n};\r\n\r\n// later on\r\n\r\nfindInEnum = function (enumKey) {\r\n if (colorEnum.hasOwnProperty(enumKey)) {\r\n return enumKey+' Value: ' + colorEnum[enumKey]\r\n }\r\n}\r\n\r\nalert(findInEnum(\"blue\"))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 29074825,
"author": "Blake Bowen",
"author_id": 2760155,
"author_profile": "https://Stackoverflow.com/users/2760155",
"pm_score": 2,
"selected": false,
"text": "<p>Here's a couple different ways to implement <a href=\"http://www.typescriptlang.org/Handbook#basic-types-enum\" rel=\"nofollow\">TypeScript enums</a>.</p>\n\n<p>The easiest way is to just iterate over an object, adding inverted key-value pairs to the object. The only drawback is that you must manually set the value for each member.</p>\n\n<pre><code>function _enum(list) { \n for (var key in list) {\n list[list[key] = list[key]] = key;\n }\n return Object.freeze(list);\n}\n\nvar Color = _enum({\n Red: 0,\n Green: 5,\n Blue: 2\n});\n\n// Color β {0: \"Red\", 2: \"Blue\", 5: \"Green\", \"Red\": 0, \"Green\": 5, \"Blue\": 2}\n// Color.Red β 0\n// Color.Green β 5\n// Color.Blue β 2\n// Color[5] β Green\n// Color.Blue > Color.Green β false\n</code></pre>\n\n<p><br>\nAnd here's a <a href=\"https://lodash.com/docs#mixin\" rel=\"nofollow\">lodash mixin</a> to create an enum using a string. While this version is a little bit more involved, it does the numbering automatically for you. All the lodash methods used in this example have a regular JavaScript equivalent, so you can easily switch them out if you want.</p>\n\n<pre><code>function enum() {\n var key, val = -1, list = {};\n _.reduce(_.toArray(arguments), function(result, kvp) { \n kvp = kvp.split(\"=\");\n key = _.trim(kvp[0]);\n val = _.parseInt(kvp[1]) || ++val; \n result[result[val] = key] = val;\n return result;\n }, list);\n return Object.freeze(list);\n} \n\n// Add enum to lodash \n_.mixin({ \"enum\": enum });\n\nvar Color = _.enum(\n \"Red\",\n \"Green\",\n \"Blue = 5\",\n \"Yellow\",\n \"Purple = 20\",\n \"Gray\"\n);\n\n// Color.Red β 0\n// Color.Green β 1\n// Color.Blue β 5\n// Color.Yellow β 6\n// Color.Purple β 20\n// Color.Gray β 21\n// Color[5] β Blue\n</code></pre>\n"
},
{
"answer_id": 29094597,
"author": "Tschallacka",
"author_id": 1356107,
"author_profile": "https://Stackoverflow.com/users/1356107",
"pm_score": 1,
"selected": false,
"text": "<p>What is an enum in <strong>my</strong> opinion: It's an immutable object that is always accessible and you can compare items with eachother, but the items have common properties/methods, but the objects themselves or the values cannot be changed and they are instantiated only once.</p>\n\n<p>Enums are imho used for comparing datatypes, settings, actions to take/reply things like that. </p>\n\n<p>So for this you need objects with the same instance so you can check if it is a enum type <code>if(something instanceof enum)</code>\nAlso if you get an enum object you want to be able to do stuff with it, regardless of the enum type, it should always respond in the same way.</p>\n\n<p>In my case its comparing values of datatypes, but it could be anything, from modifying blocks in facing direction in a 3d game to passing values on to a specific object type registry.</p>\n\n<p>Keeping in mind it is javascript and doesn't provide fixed enum type, you end up always making your own implementation and as this thread shows there are legions of implementations without one being the absoulte correct.</p>\n\n<hr>\n\n<p>This is what I use for Enums. Since enums are immutable(or should be at least heh) I freeze the objects so they can't be manipulated easely.</p>\n\n<p>The enums can be used by EnumField.STRING and they have their own methods that will work with their types.\nTo test if something passed to an object you can use <code>if(somevar instanceof EnumFieldSegment)</code></p>\n\n<p>It may not be the most elegant solution and i'm open for improvements, but this type of immutable enum(unless you unfreeze it) is exactly the usecase I needed.</p>\n\n<p>I also realise I could have overridden the prototype with a {} but my mind works better with this format ;-) shoot me.</p>\n\n<pre><code>/**\n * simple parameter object instantiator\n * @param name\n * @param value\n * @returns\n */\nfunction p(name,value) {\n this.name = name;\n this.value = value;\n return Object.freeze(this);\n}\n/**\n * EnumFieldSegmentBase\n */\nfunction EnumFieldSegmentBase() {\n this.fieldType = \"STRING\";\n}\nfunction dummyregex() {\n}\ndummyregex.prototype.test = function(str) {\n if(this.fieldType === \"STRING\") {\n maxlength = arguments[1];\n return str.length <= maxlength;\n }\n return true;\n};\n\ndummyregexposer = new dummyregex();\nEnumFieldSegmentBase.prototype.getInputRegex = function() { \n switch(this.fieldType) {\n case \"STRING\" : return dummyregexposer; \n case \"INT\": return /^(\\d+)?$/;\n case \"DECIMAL2\": return /^\\d+(\\.\\d{1,2}|\\d+|\\.)?$/;\n case \"DECIMAL8\": return /^\\d+(\\.\\d{1,8}|\\d+|\\.)?$/;\n // boolean is tricky dicky. if its a boolean false, if its a string if its empty 0 or false its false, otherwise lets see what Boolean produces\n case \"BOOLEAN\": return dummyregexposer;\n }\n};\nEnumFieldSegmentBase.prototype.convertToType = function($input) {\n var val = $input;\n switch(this.fieldType) {\n case \"STRING\" : val = $input;break;\n case \"INT\": val==\"\"? val=0 :val = parseInt($input);break;\n case \"DECIMAL2\": if($input === \"\" || $input === null) {$input = \"0\"}if($input.substr(-1) === \".\"){$input = $input+0};val = new Decimal2($input).toDP(2);break;\n case \"DECIMAL8\": if($input === \"\" || $input === null) {$input = \"0\"}if($input.substr(-1) === \".\"){$input = $input+0};val = new Decimal8($input).toDP(8);break;\n // boolean is tricky dicky. if its a boolean false, if its a string if its empty 0 or false its false, otherwise lets see what Boolean produces\n case \"BOOLEAN\": val = (typeof $input == 'boolean' ? $input : (typeof $input === 'string' ? (($input === \"false\" || $input === \"\" || $input === \"0\") ? false : true) : new Boolean($input).valueOf())) ;break;\n }\n return val;\n};\nEnumFieldSegmentBase.prototype.convertToString = function($input) {\n var val = $input;\n switch(this.fieldType) {\n case \"STRING\": val = $input;break;\n case \"INT\": val = $input+\"\";break;\n case \"DECIMAL2\": val = $input.toPrecision(($input.toString().indexOf('.') === -1 ? $input.toString().length+2 : $input.toString().indexOf('.')+2)) ;break;\n case \"DECIMAL8\": val = $input.toPrecision(($input.toString().indexOf('.') === -1 ? $input.toString().length+8 : $input.toString().indexOf('.')+8)) ;break;\n case \"BOOLEAN\": val = $input ? \"true\" : \"false\" ;break;\n }\n return val;\n};\nEnumFieldSegmentBase.prototype.compareValue = function($val1,$val2) {\n var val = false;\n switch(this.fieldType) {\n case \"STRING\": val = ($val1===$val2);break;\n case \"INT\": val = ($val1===$val2);break;\n case \"DECIMAL2\": val = ($val1.comparedTo($val2)===0);break;\n case \"DECIMAL8\": val = ($val1.comparedTo($val2)===0);break;\n case \"BOOLEAN\": val = ($val1===$val2);break;\n }\n return val;\n};\n\n/**\n * EnumFieldSegment is an individual segment in the \n * EnumField\n * @param $array An array consisting of object p\n */\nfunction EnumFieldSegment() {\n for(c=0;c<arguments.length;c++) {\n if(arguments[c] instanceof p) {\n this[arguments[c].name] = arguments[c].value;\n }\n }\n return Object.freeze(this); \n}\nEnumFieldSegment.prototype = new EnumFieldSegmentBase();\nEnumFieldSegment.prototype.constructor = EnumFieldSegment;\n\n\n/**\n * Simple enum to show what type of variable a Field type is.\n * @param STRING\n * @param INT\n * @param DECIMAL2\n * @param DECIMAL8\n * @param BOOLEAN\n * \n */\nEnumField = Object.freeze({STRING: new EnumFieldSegment(new p(\"fieldType\",\"STRING\")), \n INT: new EnumFieldSegment(new p(\"fieldType\",\"INT\")), \n DECIMAL2: new EnumFieldSegment(new p(\"fieldType\",\"DECIMAL2\")), \n DECIMAL8: new EnumFieldSegment(new p(\"fieldType\",\"DECIMAL8\")), \n BOOLEAN: new EnumFieldSegment(new p(\"fieldType\",\"BOOLEAN\"))});\n</code></pre>\n"
},
{
"answer_id": 29894175,
"author": "Gelin Luo",
"author_id": 391227,
"author_profile": "https://Stackoverflow.com/users/391227",
"pm_score": 2,
"selected": false,
"text": "<p>I've just published an NPM package <a href=\"https://www.npmjs.com/package/gen_enum\" rel=\"nofollow\">gen_enum</a> allows you to create Enum data structure in Javascript quickly:</p>\n\n<pre><code>var genEnum = require('gen_enum');\n\nvar AppMode = genEnum('SIGN_UP, LOG_IN, FORGOT_PASSWORD');\nvar curMode = AppMode.LOG_IN;\nconsole.log(curMode.isLogIn()); // output true \nconsole.log(curMode.isSignUp()); // output false \nconsole.log(curMode.isForgotPassword()); // output false \n</code></pre>\n\n<p>One nice thing about this little tool is in modern environment (including nodejs and IE 9+ browsers) the returned Enum object is immutable.</p>\n\n<p>For more information please checkout <a href=\"https://github.com/greenlaw110/enumjs\" rel=\"nofollow\">https://github.com/greenlaw110/enumjs</a></p>\n\n<p><strong>Updates</strong></p>\n\n<p>I obsolete <code>gen_enum</code> package and merge the function into <a href=\"https://www.npmjs.com/package/constjs\" rel=\"nofollow\">constjs</a> package, which provides more features including immutable objects, JSON string deserialization, string constants and bitmap generation etc. Checkout <a href=\"https://www.npmjs.com/package/constjs\" rel=\"nofollow\">https://www.npmjs.com/package/constjs</a> for more information </p>\n\n<p>To upgrade from <code>gen_enum</code> to <code>constjs</code> just change the statement</p>\n\n<pre><code>var genEnum = require('gen_enum');\n</code></pre>\n\n<p>to</p>\n\n<pre><code>var genEnum = require('constjs').enum;\n</code></pre>\n"
},
{
"answer_id": 30045582,
"author": "Pylinux",
"author_id": 1465640,
"author_profile": "https://Stackoverflow.com/users/1465640",
"pm_score": 0,
"selected": false,
"text": "<pre><code>var DaysEnum = Object.freeze ({ monday: {}, tuesday: {}, ... });\n</code></pre>\n\n<p>You don't need to specify an <em>id</em>, you can just use an empty object to compare enums. </p>\n\n<pre><code>if (incommingEnum === DaysEnum.monday) //incommingEnum is monday\n</code></pre>\n\n<p><strong>EDIT:</strong> If you are going to serialize the object (to JSON for instance) you'll the <em>id</em> again.</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/287903/enums-in-javascript#comment12864576_5040502\">( taken from Gabriel Llamas comment )</a></li>\n<li><a href=\"https://stackoverflow.com/questions/287903/enums-in-javascript/30045582?noredirect=1#comment71130974_30045582\">( edit based on Stijn de Witt's comment )</a></li>\n</ul>\n"
},
{
"answer_id": 30058506,
"author": "Vitalii Fedorenko",
"author_id": 288671,
"author_profile": "https://Stackoverflow.com/users/288671",
"pm_score": 6,
"selected": false,
"text": "<p>In most modern browsers, there is a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol\" rel=\"noreferrer\">symbol</a> primitive data type which can be used to create an enumeration. It will ensure type safety of the enum as each symbol value is guaranteed by JavaScript to be unique, i.e. <code>Symbol() != Symbol()</code>. For example:</p>\n\n<pre><code>const COLOR = Object.freeze({RED: Symbol(), BLUE: Symbol()});\n</code></pre>\n\n<p>To simplify debugging, you can add a description to enum values:</p>\n\n<pre><code>const COLOR = Object.freeze({RED: Symbol(\"RED\"), BLUE: Symbol(\"BLUE\")});\n</code></pre>\n\n<p><a href=\"http://plnkr.co/edit/rGjzZlUF4HPdllaTQ3OW?p=preview\" rel=\"noreferrer\">Plunker demo</a></p>\n\n<p>On <a href=\"https://github.com/zhaber/symbol-enum\" rel=\"noreferrer\">GitHub</a> you can find a wrapper that simplifies the code required to initialize the enum:</p>\n\n<pre><code>const color = new Enum(\"RED\", \"BLUE\")\n\ncolor.RED.toString() // Symbol(RED)\ncolor.getName(color.RED) // RED\ncolor.size // 2\ncolor.values() // Symbol(RED), Symbol(BLUE)\ncolor.toString() // RED,BLUE\n</code></pre>\n"
},
{
"answer_id": 31185447,
"author": "Manohar Reddy Poreddy",
"author_id": 984471,
"author_profile": "https://Stackoverflow.com/users/984471",
"pm_score": 3,
"selected": false,
"text": "<p>IE8 does Not support freeze() method.<br>\nSource: <a href=\"http://kangax.github.io/compat-table/es5/\" rel=\"nofollow\">http://kangax.github.io/compat-table/es5/</a>, Click on \"Show obsolete browsers?\" on top, and check IE8 & freeze row col intersection.</p>\n\n<p>In my current game project, I have used below, since few customers still use IE8:</p>\n\n<pre><code>var CONST_WILD_TYPES = {\n REGULAR: 'REGULAR',\n EXPANDING: 'EXPANDING',\n STICKY: 'STICKY',\n SHIFTING: 'SHIFTING'\n};\n</code></pre>\n\n<p>We could also do: </p>\n\n<pre><code>var CONST_WILD_TYPES = {\n REGULAR: 'RE',\n EXPANDING: 'EX',\n STICKY: 'ST',\n SHIFTING: 'SH'\n};\n</code></pre>\n\n<p>or even this: </p>\n\n<pre><code>var CONST_WILD_TYPES = {\n REGULAR: '1',\n EXPANDING: '2',\n STICKY: '3',\n SHIFTING: '4'\n};\n</code></pre>\n\n<p>The last one, seems most efficient for string, it reduces your total bandwidth if you have server & client exchanging this data.<br>\nOf course, now it's your duty to make sure there are no conflicts in the data (RE, EX, etc. must be unique, also 1, 2, etc. should be unique). Note that you need to maintain these forever for backward compatibility. </p>\n\n<p>Assignment:</p>\n\n<pre><code>var wildType = CONST_WILD_TYPES.REGULAR;\n</code></pre>\n\n<p>Comparision:</p>\n\n<pre><code>if (wildType === CONST_WILD_TYPES.REGULAR) {\n // do something here\n}\n</code></pre>\n"
},
{
"answer_id": 31636748,
"author": "hvdd",
"author_id": 2326407,
"author_profile": "https://Stackoverflow.com/users/2326407",
"pm_score": 4,
"selected": false,
"text": "<p>Create an object literal:</p>\n\n<pre><code>const Modes = {\n DRAGGING: 'drag',\n SCALING: 'scale',\n CLICKED: 'click'\n};\n</code></pre>\n"
},
{
"answer_id": 32245965,
"author": "Sherali Turdiyev",
"author_id": 4365315,
"author_profile": "https://Stackoverflow.com/users/4365315",
"pm_score": 2,
"selected": false,
"text": "<p>It's easy to use, I think. <a href=\"https://stackoverflow.com/a/32245370/4365315\">https://stackoverflow.com/a/32245370/4365315</a></p>\n\n<pre><code>var A = {a:11, b:22}, \nenumA = new TypeHelper(A);\n\nif(enumA.Value === A.b || enumA.Key === \"a\"){ \n... \n}\n\nvar keys = enumA.getAsList();//[object, object]\n\n//set\nenumA.setType(22, false);//setType(val, isKey)\n\nenumA.setType(\"a\", true);\n\nenumA.setTypeByIndex(1);\n</code></pre>\n\n<p>UPDATE:</p>\n\n<p>There is my helper codes(<code>TypeHelper</code>).</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var Helper = {\r\n isEmpty: function (obj) {\r\n return !obj || obj === null || obj === undefined || Array.isArray(obj) && obj.length === 0;\r\n },\r\n\r\n isObject: function (obj) {\r\n return (typeof obj === 'object');\r\n },\r\n\r\n sortObjectKeys: function (object) {\r\n return Object.keys(object)\r\n .sort(function (a, b) {\r\n c = a - b;\r\n return c\r\n });\r\n },\r\n containsItem: function (arr, item) {\r\n if (arr && Array.isArray(arr)) {\r\n return arr.indexOf(item) > -1;\r\n } else {\r\n return arr === item;\r\n }\r\n },\r\n\r\n pushArray: function (arr1, arr2) {\r\n if (arr1 && arr2 && Array.isArray(arr1)) {\r\n arr1.push.apply(arr1, Array.isArray(arr2) ? arr2 : [arr2]);\r\n }\r\n }\r\n};\r\nfunction TypeHelper() {\r\n var _types = arguments[0],\r\n _defTypeIndex = 0,\r\n _currentType,\r\n _value,\r\n _allKeys = Helper.sortObjectKeys(_types);\r\n\r\n if (arguments.length == 2) {\r\n _defTypeIndex = arguments[1];\r\n }\r\n\r\n Object.defineProperties(this, {\r\n Key: {\r\n get: function () {\r\n return _currentType;\r\n },\r\n set: function (val) {\r\n _currentType.setType(val, true);\r\n },\r\n enumerable: true\r\n },\r\n Value: {\r\n get: function () {\r\n return _types[_currentType];\r\n },\r\n set: function (val) {\r\n _value.setType(val, false);\r\n },\r\n enumerable: true\r\n }\r\n });\r\n this.getAsList = function (keys) {\r\n var list = [];\r\n _allKeys.forEach(function (key, idx, array) {\r\n if (key && _types[key]) {\r\n\r\n if (!Helper.isEmpty(keys) && Helper.containsItem(keys, key) || Helper.isEmpty(keys)) {\r\n var json = {};\r\n json.Key = key;\r\n json.Value = _types[key];\r\n Helper.pushArray(list, json);\r\n }\r\n }\r\n });\r\n return list;\r\n };\r\n\r\n this.setType = function (value, isKey) {\r\n if (!Helper.isEmpty(value)) {\r\n Object.keys(_types).forEach(function (key, idx, array) {\r\n if (Helper.isObject(value)) {\r\n if (value && value.Key == key) {\r\n _currentType = key;\r\n }\r\n } else if (isKey) {\r\n if (value && value.toString() == key.toString()) {\r\n _currentType = key;\r\n }\r\n } else if (value && value.toString() == _types[key]) {\r\n _currentType = key;\r\n }\r\n });\r\n } else {\r\n this.setDefaultType();\r\n }\r\n return isKey ? _types[_currentType] : _currentType;\r\n };\r\n\r\n this.setTypeByIndex = function (index) {\r\n for (var i = 0; i < _allKeys.length; i++) {\r\n if (index === i) {\r\n _currentType = _allKeys[index];\r\n break;\r\n }\r\n }\r\n };\r\n\r\n this.setDefaultType = function () {\r\n this.setTypeByIndex(_defTypeIndex);\r\n };\r\n\r\n this.setDefaultType();\r\n}\r\n\r\nvar TypeA = {\r\n \"-1\": \"Any\",\r\n \"2\": \"2L\",\r\n \"100\": \"100L\",\r\n \"200\": \"200L\",\r\n \"1000\": \"1000L\"\r\n};\r\n\r\nvar enumA = new TypeHelper(TypeA, 4);\r\n\r\ndocument.writeln(\"Key = \", enumA.Key,\", Value = \", enumA.Value, \"<br>\");\r\n\r\n\r\nenumA.setType(\"200L\", false);\r\ndocument.writeln(\"Key = \", enumA.Key,\", Value = \", enumA.Value, \"<br>\");\r\n\r\nenumA.setDefaultType();\r\ndocument.writeln(\"Key = \", enumA.Key,\", Value = \", enumA.Value, \"<br>\");\r\n\r\n\r\nenumA.setTypeByIndex(1);\r\ndocument.writeln(\"Key = \", enumA.Key,\", Value = \", enumA.Value, \"<br>\");\r\n\r\ndocument.writeln(\"is equals = \", (enumA.Value == TypeA[\"2\"]));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 32658453,
"author": "Vivin Paliath",
"author_id": 263004,
"author_profile": "https://Stackoverflow.com/users/263004",
"pm_score": 3,
"selected": false,
"text": "<p>I came up with <a href=\"https://github.com/vivin/enumjs\" rel=\"noreferrer\">this</a> approach which is modeled after enums in Java. These are type-safe, and so you can perform <code>instanceof</code> checks as well.</p>\n\n<p>You can define enums like this:</p>\n\n<pre><code>var Days = Enum.define(\"Days\", [\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\", \"Sunday\"]);\n</code></pre>\n\n<p><code>Days</code> now refers to the <code>Days</code> enum:</p>\n\n<pre><code>Days.Monday instanceof Days; // true\n\nDays.Friday.name(); // \"Friday\"\nDays.Friday.ordinal(); // 4\n\nDays.Sunday === Days.Sunday; // true\nDays.Sunday === Days.Friday; // false\n\nDays.Sunday.toString(); // \"Sunday\"\n\nDays.toString() // \"Days { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday } \"\n\nDays.values().map(function(e) { return e.name(); }); //[\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\", \"Sunday\"]\nDays.values()[4].name(); //\"Friday\"\n\nDays.fromName(\"Thursday\") === Days.Thursday // true\nDays.fromName(\"Wednesday\").name() // \"Wednesday\"\nDays.Friday.fromName(\"Saturday\").name() // \"Saturday\"\n</code></pre>\n\n<p>The implementation:</p>\n\n<pre><code>var Enum = (function () {\n /**\n * Function to define an enum\n * @param typeName - The name of the enum.\n * @param constants - The constants on the enum. Can be an array of strings, or an object where each key is an enum\n * constant, and the values are objects that describe attributes that can be attached to the associated constant.\n */\n function define(typeName, constants) {\n\n /** Check Arguments **/\n if (typeof typeName === \"undefined\") {\n throw new TypeError(\"A name is required.\");\n }\n\n if (!(constants instanceof Array) && (Object.getPrototypeOf(constants) !== Object.prototype)) {\n\n throw new TypeError(\"The constants parameter must either be an array or an object.\");\n\n } else if ((constants instanceof Array) && constants.length === 0) {\n\n throw new TypeError(\"Need to provide at least one constant.\");\n\n } else if ((constants instanceof Array) && !constants.reduce(function (isString, element) {\n return isString && (typeof element === \"string\");\n }, true)) {\n\n throw new TypeError(\"One or more elements in the constant array is not a string.\");\n\n } else if (Object.getPrototypeOf(constants) === Object.prototype && !Object.keys(constants).reduce(function (isObject, constant) {\n return Object.getPrototypeOf(constants[constant]) === Object.prototype;\n }, true)) {\n\n throw new TypeError(\"One or more constants do not have an associated object-value.\");\n\n }\n\n var isArray = (constants instanceof Array);\n var isObject = !isArray;\n\n /** Private sentinel-object used to guard enum constructor so that no one else can create enum instances **/\n function __() { };\n\n /** Dynamically define a function with the same name as the enum we want to define. **/\n var __enum = new Function([\"__\"],\n \"return function \" + typeName + \"(sentinel, name, ordinal) {\" +\n \"if(!(sentinel instanceof __)) {\" +\n \"throw new TypeError(\\\"Cannot instantiate an instance of \" + typeName + \".\\\");\" +\n \"}\" +\n\n \"this.__name = name;\" +\n \"this.__ordinal = ordinal;\" +\n \"}\"\n )(__);\n\n /** Private objects used to maintain enum instances for values(), and to look up enum instances for fromName() **/\n var __values = [];\n var __dict = {};\n\n /** Attach values() and fromName() methods to the class itself (kind of like static methods). **/\n Object.defineProperty(__enum, \"values\", {\n value: function () {\n return __values;\n }\n });\n\n Object.defineProperty(__enum, \"fromName\", {\n value: function (name) {\n var __constant = __dict[name]\n if (__constant) {\n return __constant;\n } else {\n throw new TypeError(typeName + \" does not have a constant with name \" + name + \".\");\n }\n }\n });\n\n /**\n * The following methods are available to all instances of the enum. values() and fromName() need to be\n * available to each constant, and so we will attach them on the prototype. But really, they're just\n * aliases to their counterparts on the prototype.\n */\n Object.defineProperty(__enum.prototype, \"values\", {\n value: __enum.values\n });\n\n Object.defineProperty(__enum.prototype, \"fromName\", {\n value: __enum.fromName\n });\n\n Object.defineProperty(__enum.prototype, \"name\", {\n value: function () {\n return this.__name;\n }\n });\n\n Object.defineProperty(__enum.prototype, \"ordinal\", {\n value: function () {\n return this.__ordinal;\n }\n });\n\n Object.defineProperty(__enum.prototype, \"valueOf\", {\n value: function () {\n return this.__name;\n }\n });\n\n Object.defineProperty(__enum.prototype, \"toString\", {\n value: function () {\n return this.__name;\n }\n });\n\n /**\n * If constants was an array, we can the element values directly. Otherwise, we will have to use the keys\n * from the constants object.\n */\n var _constants = constants;\n if (isObject) {\n _constants = Object.keys(constants);\n }\n\n /** Iterate over all constants, create an instance of our enum for each one, and attach it to the enum type **/\n _constants.forEach(function (name, ordinal) {\n // Create an instance of the enum\n var __constant = new __enum(new __(), name, ordinal);\n\n // If constants was an object, we want to attach the provided attributes to the instance.\n if (isObject) {\n Object.keys(constants[name]).forEach(function (attr) {\n Object.defineProperty(__constant, attr, {\n value: constants[name][attr]\n });\n });\n }\n\n // Freeze the instance so that it cannot be modified.\n Object.freeze(__constant);\n\n // Attach the instance using the provided name to the enum type itself.\n Object.defineProperty(__enum, name, {\n value: __constant\n });\n\n // Update our private objects\n __values.push(__constant);\n __dict[name] = __constant;\n });\n\n /** Define a friendly toString method for the enum **/\n var string = typeName + \" { \" + __enum.values().map(function (c) {\n return c.name();\n }).join(\", \") + \" } \";\n\n Object.defineProperty(__enum, \"toString\", {\n value: function () {\n return string;\n }\n });\n\n /** Freeze our private objects **/\n Object.freeze(__values);\n Object.freeze(__dict);\n\n /** Freeze the prototype on the enum and the enum itself **/\n Object.freeze(__enum.prototype);\n Object.freeze(__enum);\n\n /** Return the enum **/\n return __enum;\n }\n\n return {\n define: define\n }\n\n})();\n</code></pre>\n"
},
{
"answer_id": 33326060,
"author": "Jules Sam. Randolph",
"author_id": 2779871,
"author_profile": "https://Stackoverflow.com/users/2779871",
"pm_score": 2,
"selected": false,
"text": "<p>I wrote <strong>enumerationjs</strong> a <a href=\"https://github.com/sveinburne/enumerationjs#top\" rel=\"nofollow\">very tiny library to address the issue</a> which <strong>ensures type safety</strong>, allow enum constants to <strong>inherit from a prototype</strong>, guaranties enum constants and enum types to be immutable + many little features. It allows to refactor a lot of code and move some logic inside the enum definition. Here is an example : </p>\n\n<pre><code>var CloseEventCodes = new Enumeration(\"closeEventCodes\", {\n CLOSE_NORMAL: { _id: 1000, info: \"Connection closed normally\" },\n CLOSE_GOING_AWAY: { _id: 1001, info: \"Connection closed going away\" },\n CLOSE_PROTOCOL_ERROR: { _id: 1002, info: \"Connection closed due to protocol error\" },\n CLOSE_UNSUPPORTED: { _id: 1003, info: \"Connection closed due to unsupported operation\" },\n CLOSE_NO_STATUS: { _id: 1005, info: \"Connection closed with no status\" },\n CLOSE_ABNORMAL: { _id: 1006, info: \"Connection closed abnormally\" },\n CLOSE_TOO_LARGE: { _id: 1009, info: \"Connection closed due to too large packet\" }\n},{ talk: function(){\n console.log(this.info); \n }\n});\n\n\nCloseEventCodes.CLOSE_TOO_LARGE.talk(); //prints \"Connection closed due to too large packet\"\nCloseEventCodes.CLOSE_TOO_LARGE instanceof CloseEventCodes //evaluates to true\n</code></pre>\n\n<p><code>Enumeration</code> is basically a factory. </p>\n\n<p><a href=\"https://github.com/sveinburne/enumerationjs/blob/master/JS.GUIDE.MD#top\" rel=\"nofollow\">Fully documented guide available here.</a> Hope this helps. </p>\n"
},
{
"answer_id": 34636629,
"author": "Oooogi",
"author_id": 4274373,
"author_profile": "https://Stackoverflow.com/users/4274373",
"pm_score": 2,
"selected": false,
"text": "<p>I've made an Enum class that can fetch values AND names at O(1). It can also generate an Object Array containing all Names and Values.</p>\n\n<pre><code>function Enum(obj) {\n // Names must be unique, Values do not.\n // Putting same values for different Names is risky for this implementation\n\n this._reserved = {\n _namesObj: {},\n _objArr: [],\n _namesArr: [],\n _valuesArr: [],\n _selectOptionsHTML: \"\"\n };\n\n for (k in obj) {\n if (obj.hasOwnProperty(k)) {\n this[k] = obj[k];\n this._reserved._namesObj[obj[k]] = k;\n }\n }\n}\n(function () {\n this.GetName = function (val) {\n if (typeof this._reserved._namesObj[val] === \"undefined\")\n return null;\n return this._reserved._namesObj[val];\n };\n\n this.GetValue = function (name) {\n if (typeof this[name] === \"undefined\")\n return null;\n return this[name];\n };\n\n this.GetObjArr = function () {\n if (this._reserved._objArr.length == 0) {\n var arr = [];\n for (k in this) {\n if (this.hasOwnProperty(k))\n if (k != \"_reserved\")\n arr.push({\n Name: k,\n Value: this[k]\n });\n }\n this._reserved._objArr = arr;\n }\n return this._reserved._objArr;\n };\n\n this.GetNamesArr = function () {\n if (this._reserved._namesArr.length == 0) {\n var arr = [];\n for (k in this) {\n if (this.hasOwnProperty(k))\n if (k != \"_reserved\")\n arr.push(k);\n }\n this._reserved._namesArr = arr;\n }\n return this._reserved._namesArr;\n };\n\n this.GetValuesArr = function () {\n if (this._reserved._valuesArr.length == 0) {\n var arr = [];\n for (k in this) {\n if (this.hasOwnProperty(k))\n if (k != \"_reserved\")\n arr.push(this[k]);\n }\n this._reserved._valuesArr = arr;\n }\n return this._reserved._valuesArr;\n };\n\n this.GetSelectOptionsHTML = function () {\n if (this._reserved._selectOptionsHTML.length == 0) {\n var html = \"\";\n for (k in this) {\n if (this.hasOwnProperty(k))\n if (k != \"_reserved\")\n html += \"<option value='\" + this[k] + \"'>\" + k + \"</option>\";\n }\n this._reserved._selectOptionsHTML = html;\n }\n return this._reserved._selectOptionsHTML;\n };\n}).call(Enum.prototype);\n</code></pre>\n\n<p>You can init'd it like this:</p>\n\n<pre><code>var enum1 = new Enum({\n item1: 0,\n item2: 1,\n item3: 2\n});\n</code></pre>\n\n<p>To fetch a value (like Enums in C#):</p>\n\n<pre><code>var val2 = enum1.item2;\n</code></pre>\n\n<p>To fetch a name for a value (can be ambiguous when putting the same value for different names):</p>\n\n<pre><code>var name1 = enum1.GetName(0); // \"item1\"\n</code></pre>\n\n<p>To get an array with each name & value in an object:</p>\n\n<pre><code>var arr = enum1.GetObjArr();\n</code></pre>\n\n<p>Will generate:</p>\n\n<pre><code>[{ Name: \"item1\", Value: 0}, { ... }, ... ]\n</code></pre>\n\n<p>You can also get the html select options readily:</p>\n\n<pre><code>var html = enum1.GetSelectOptionsHTML();\n</code></pre>\n\n<p>Which holds:</p>\n\n<pre><code>\"<option value='0'>item1</option>...\"\n</code></pre>\n"
},
{
"answer_id": 37159989,
"author": "Muhammad Awais",
"author_id": 3901944,
"author_profile": "https://Stackoverflow.com/users/3901944",
"pm_score": 2,
"selected": false,
"text": "<p>You can try this:</p>\n\n<pre><code> var Enum = Object.freeze({\n Role: Object.freeze({ Administrator: 1, Manager: 2, Supervisor: 3 }),\n Color:Object.freeze({RED : 0, GREEN : 1, BLUE : 2 })\n });\n\n alert(Enum.Role.Supervisor);\n alert(Enum.Color.GREEN);\n var currentColor=0;\n if(currentColor == Enum.Color.RED) {\n alert('Its Red');\n }\n</code></pre>\n"
},
{
"answer_id": 37429406,
"author": "LNT",
"author_id": 3335776,
"author_profile": "https://Stackoverflow.com/users/3335776",
"pm_score": 2,
"selected": false,
"text": "<p>You can do something like this</p>\n\n<pre><code> var Enum = (function(foo) {\n\n var EnumItem = function(item){\n if(typeof item == \"string\"){\n this.name = item;\n } else {\n this.name = item.name;\n }\n }\n EnumItem.prototype = new String(\"DEFAULT\");\n EnumItem.prototype.toString = function(){\n return this.name;\n }\n EnumItem.prototype.equals = function(item){\n if(typeof item == \"string\"){\n return this.name == item;\n } else {\n return this == item && this.name == item.name;\n }\n }\n\n function Enum() {\n this.add.apply(this, arguments);\n Object.freeze(this);\n }\n Enum.prototype.add = function() {\n for (var i in arguments) {\n var enumItem = new EnumItem(arguments[i]);\n this[enumItem.name] = enumItem;\n }\n };\n Enum.prototype.toList = function() {\n return Object.keys(this);\n };\n foo.Enum = Enum;\n return Enum;\n})(this);\nvar STATUS = new Enum(\"CLOSED\",\"PENDING\", { name : \"CONFIRMED\", ackd : true });\nvar STATE = new Enum(\"CLOSED\",\"PENDING\",\"CONFIRMED\",{ name : \"STARTED\"},{ name : \"PROCESSING\"});\n</code></pre>\n\n<p>As defined in this library.\n<a href=\"https://github.com/webmodule/foo/blob/master/foo.js#L217\" rel=\"nofollow noreferrer\">https://github.com/webmodule/foo/blob/master/foo.js#L217</a></p>\n\n<p>Complete example\n<a href=\"https://gist.github.com/lnt/bb13a2fd63cdb8bce85fd62965a20026\" rel=\"nofollow noreferrer\">https://gist.github.com/lnt/bb13a2fd63cdb8bce85fd62965a20026</a></p>\n"
},
{
"answer_id": 38996905,
"author": "Ilya Gazman",
"author_id": 1129332,
"author_profile": "https://Stackoverflow.com/users/1129332",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Simplest solution:</strong></p>\n\n<h2>Create</h2>\n\n<pre><code>var Status = Object.freeze({\n \"Connecting\":0,\n \"Ready\":1,\n \"Loading\":2,\n \"Processing\": 3\n});\n</code></pre>\n\n<h2>Get Value</h2>\n\n<pre><code>console.log(Status.Ready) // 1\n</code></pre>\n\n<h2>Get Key</h2>\n\n<pre><code>console.log(Object.keys(Status)[Status.Ready]) // Ready\n</code></pre>\n"
},
{
"answer_id": 39222211,
"author": "Marcus Junius Brutus",
"author_id": 274677,
"author_profile": "https://Stackoverflow.com/users/274677",
"pm_score": 2,
"selected": false,
"text": "<p>Even though <a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes\" rel=\"nofollow noreferrer\">only static methods</a> (and not static properties) are supported in ES2015 (see <a href=\"http://exploringjs.com/es6/ch_classes.html#_inside-the-body-of-a-class-definition\" rel=\"nofollow noreferrer\">here</a> as well, §15.2.2.2), curiously you can use the below with Babel with the <code>es2015</code> preset:</p>\n\n<pre><code>class CellState {\n v: string;\n constructor(v: string) {\n this.v = v;\n Object.freeze(this);\n }\n static EMPTY = new CellState('e');\n static OCCUPIED = new CellState('o');\n static HIGHLIGHTED = new CellState('h');\n static values = function(): Array<CellState> {\n const rv = [];\n rv.push(CellState.EMPTY);\n rv.push(CellState.OCCUPIED);\n rv.push(CellState.HIGHLIGHTED);\n return rv;\n }\n}\nObject.freeze(CellState);\n</code></pre>\n\n<p>I found this to be working as expected even across modules (e.g. importing the <code>CellState</code> enum from another module) and also when I import a module using Webpack.</p>\n\n<p><strong>The advantage this method has over most other answers is that you can use it alongside a static type checker</strong> (e.g. <a href=\"https://flowtype.org/\" rel=\"nofollow noreferrer\">Flow</a>) and you can assert, at development time using static type checking, that your variables, parameters, etc. are of the specific <code>CellState</code> \"enum\" rather than some other enum (which would be impossible to distinguish if you used generic objects or symbols).</p>\n\n<h1>update</h1>\n\n<p>The above code has a deficiency in that it allows one to create additional objects of type <code>CellState</code> (even though one can't assign them to the static fields of <code>CellState</code> since it's frozen). Still, the below more refined code offers the following advantages:</p>\n\n<ol>\n<li>no more objects of type <code>CellState</code> may be created</li>\n<li>you are guaranteed that no two enum instances are assigned the same code</li>\n<li>utility method to get the enum back from a string representation</li>\n<li><p>the <code>values</code> function that returns all instances of the enum does not have to create the return value in the above, manual (and error-prone) way.</p>\n\n<pre><code>'use strict';\n\nclass Status {\n\nconstructor(code, displayName = code) {\n if (Status.INSTANCES.has(code))\n throw new Error(`duplicate code value: [${code}]`);\n if (!Status.canCreateMoreInstances)\n throw new Error(`attempt to call constructor(${code}`+\n `, ${displayName}) after all static instances have been created`);\n this.code = code;\n this.displayName = displayName;\n Object.freeze(this);\n Status.INSTANCES.set(this.code, this);\n}\n\ntoString() {\n return `[code: ${this.code}, displayName: ${this.displayName}]`;\n}\nstatic INSTANCES = new Map();\nstatic canCreateMoreInstances = true;\n\n// the values:\nstatic ARCHIVED = new Status('Archived');\nstatic OBSERVED = new Status('Observed');\nstatic SCHEDULED = new Status('Scheduled');\nstatic UNOBSERVED = new Status('Unobserved');\nstatic UNTRIGGERED = new Status('Untriggered');\n\nstatic values = function() {\n return Array.from(Status.INSTANCES.values());\n}\n\nstatic fromCode(code) {\n if (!Status.INSTANCES.has(code))\n throw new Error(`unknown code: ${code}`);\n else\n return Status.INSTANCES.get(code);\n}\n}\n\nStatus.canCreateMoreInstances = false;\nObject.freeze(Status);\nexports.Status = Status;\n</code></pre></li>\n</ol>\n"
},
{
"answer_id": 40390784,
"author": "Little Alien",
"author_id": 6267925,
"author_profile": "https://Stackoverflow.com/users/6267925",
"pm_score": 1,
"selected": false,
"text": "<p>The Alien solution is to make things as simple as possible:</p>\n\n<ol>\n<li>use enum keyword (reserved in javascript)</li>\n<li><p>If enum keyword is just reserved but not implemented in your javascript, define the following</p>\n\n<pre><code>const enumerate = spec => spec.split(/\\s*,\\s*/)\n .reduce((e, n) => Object.assign(e,{[n]:n}), {}) \n</code></pre></li>\n</ol>\n\n<p>Now, you can easily use it</p>\n\n<pre><code>const kwords = enumerate(\"begin,end, procedure,if\")\nconsole.log(kwords, kwords.if, kwords.if == \"if\", kwords.undef)\n</code></pre>\n\n<p>I see no reason to make the enum values explicit variables. The scripts are morphic anyway and it makes no difference if part of your code is a string or valid code. What really matters is that you do not need to deal with tons of quotation marks whenever use or define them. </p>\n"
},
{
"answer_id": 41500700,
"author": "Abdennour TOUMI",
"author_id": 747579,
"author_profile": "https://Stackoverflow.com/users/747579",
"pm_score": 4,
"selected": false,
"text": "<p>In <a href=\"https://babeljs.io/docs/plugins/transform-class-properties/\" rel=\"noreferrer\">ES7</a> , you can do an elegant ENUM relying on static attributes: </p>\n\n<pre><code>class ColorEnum {\n static RED = 0 ;\n static GREEN = 1;\n static BLUE = 2;\n}\n</code></pre>\n\n<p>then </p>\n\n<pre><code>if (currentColor === ColorEnum.GREEN ) {/*-- coding --*/}\n</code></pre>\n\n<p>The advantage ( of using class instead of literal object) is to have a parent class <code>Enum</code> then all your Enums will <strong>extends</strong> that class. </p>\n\n<pre><code> class ColorEnum extends Enum {/*....*/}\n</code></pre>\n"
},
{
"answer_id": 43363905,
"author": "mika",
"author_id": 4910883,
"author_profile": "https://Stackoverflow.com/users/4910883",
"pm_score": 0,
"selected": false,
"text": "<p>You could try using <a href=\"https://bitbucket.org/snippets/frostbane/aAjxM\" rel=\"nofollow noreferrer\">https://bitbucket.org/snippets/frostbane/aAjxM</a>.</p>\n\n<pre><code>my.namespace.ColorEnum = new Enum(\n \"RED = 0\",\n \"GREEN\",\n \"BLUE\"\n)\n</code></pre>\n\n<p>It should work up to ie8.</p>\n"
},
{
"answer_id": 45325303,
"author": "David Lemon",
"author_id": 2739274,
"author_profile": "https://Stackoverflow.com/users/2739274",
"pm_score": 0,
"selected": false,
"text": "<p>You can use a simple funcion to invert keys and values, it will work with arrays also as it converts numerical integer strings to numbers. The code is small, simple and reusable for this and other use cases.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var objInvert = function (obj) {\r\n var invert = {}\r\n for (var i in obj) {\r\n if (i.match(/^\\d+$/)) i = parseInt(i,10)\r\n invert[obj[i]] = i\r\n }\r\n return invert\r\n}\r\n \r\nvar musicStyles = Object.freeze(objInvert(['ROCK', 'SURF', 'METAL',\r\n'BOSSA-NOVA','POP','INDIE']))\r\n\r\nconsole.log(musicStyles)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 48798027,
"author": "Joseph Merdrignac",
"author_id": 4696005,
"author_profile": "https://Stackoverflow.com/users/4696005",
"pm_score": 3,
"selected": false,
"text": "<p>es7 way, (iterator, freeze), usage:</p>\n\n<pre><code>const ThreeWiseMen = new Enum('Melchior', 'Caspar', 'Balthazar')\n\nfor (let name of ThreeWiseMen)\n console.log(name)\n\n\n// with a given key\nlet key = ThreeWiseMen.Melchior\n\nconsole.log(key in ThreeWiseMen) // true (string conversion, also true: 'Melchior' in ThreeWiseMen)\n\nfor (let entry from key.enum)\n console.log(entry)\n\n\n// prevent alteration (throws TypeError in strict mode)\nThreeWiseMen.Me = 'Me too!'\nThreeWiseMen.Melchior.name = 'Foo'\n</code></pre>\n\n<p>code:</p>\n\n<pre><code>class EnumKey {\n\n constructor(props) { Object.freeze(Object.assign(this, props)) }\n\n toString() { return this.name }\n\n}\n\nexport class Enum {\n\n constructor(...keys) {\n\n for (let [index, key] of keys.entries()) {\n\n Object.defineProperty(this, key, {\n\n value: new EnumKey({ name:key, index, enum:this }),\n enumerable: true,\n\n })\n\n }\n\n Object.freeze(this)\n\n }\n\n *[Symbol.iterator]() {\n\n for (let key of Object.keys(this))\n yield this[key]\n\n }\n\n toString() { return [...this].join(', ') }\n\n}\n</code></pre>\n"
},
{
"answer_id": 49309248,
"author": "Govind Rai",
"author_id": 2757916,
"author_profile": "https://Stackoverflow.com/users/2757916",
"pm_score": 5,
"selected": false,
"text": "<h2>Use Javascript <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy\" rel=\"noreferrer\">Proxies</a></h2>\n\n<p><strong>TLDR:</strong> Add this class to your utility methods and use it throughout your code, it mocks Enum behavior from traditional programming languages, and actually throws errors when you try to either access an enumerator that does not exist or add/update an enumerator. No need to rely on <code>Object.freeze()</code>.</p>\n\n<pre><code>class Enum {\n constructor(enumObj) {\n const handler = {\n get(target, name) {\n if (typeof target[name] != 'undefined') {\n return target[name];\n }\n throw new Error(`No such enumerator: ${name}`);\n },\n set() {\n throw new Error('Cannot add/update properties on an Enum instance after it is defined')\n }\n };\n\n return new Proxy(enumObj, handler);\n }\n}\n</code></pre>\n\n<p>Then create enums by instantiating the class:</p>\n\n<pre><code>const roles = new Enum({\n ADMIN: 'Admin',\n USER: 'User',\n});\n</code></pre>\n\n<hr>\n\n<p><strong>Full Explanation:</strong> </p>\n\n<p>One very beneficial feature of Enums that you get from traditional languages is that they blow up (throw a compile-time error) if you try to access an enumerator which does not exist. </p>\n\n<p>Besides freezing the mocked enum structure to prevent additional values from accidentally/maliciously being added, none of the other answers address that intrinsic feature of Enums.</p>\n\n<p>As you are probably aware, accessing non-existing members in JavaScript simply returns <code>undefined</code> and does not blow up your code. Since enumerators are predefined constants (i.e. days of the week), there should never be a case when an enumerator should be undefined.</p>\n\n<p>Don't get me wrong, JavaScript's behavior of returning <code>undefined</code> when accessing undefined properties is actually a very powerful feature of language, but it's not a feature you want when you are trying to mock traditional Enum structures. </p>\n\n<p>This is where Proxy objects shine. Proxies were standardized in the language with the introduction of ES6 (ES2015). Here's the description from MDN: </p>\n\n<blockquote>\n <p>The Proxy object is used to define custom behavior for fundamental operations (e.g. property lookup, assignment, enumeration, function\n invocation, etc).</p>\n</blockquote>\n\n<p>Similar to a web server proxy, JavaScript proxies are able to intercept operations on objects (with the use of \"traps\", call them hooks if you like) and allow you to perform various checks, actions and/or manipulations before they complete (or in some cases stopping the operations altogether which is exactly what we want to do if and when we try to reference an enumerator which does not exist).</p>\n\n<p>Here's a contrived example that uses the Proxy object to mimic Enums. The enumerators in this example are standard HTTP Methods (i.e. \"GET\", \"POST\", etc.):</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"true\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// Class for creating enums (13 lines)\r\n// Feel free to add this to your utility library in \r\n// your codebase and profit! Note: As Proxies are an ES6 \r\n// feature, some browsers/clients may not support it and \r\n// you may need to transpile using a service like babel\r\n\r\nclass Enum {\r\n // The Enum class instantiates a JavaScript Proxy object.\r\n // Instantiating a `Proxy` object requires two parameters, \r\n // a `target` object and a `handler`. We first define the handler,\r\n // then use the handler to instantiate a Proxy.\r\n\r\n // A proxy handler is simply an object whose properties\r\n // are functions which define the behavior of the proxy \r\n // when an operation is performed on it. \r\n \r\n // For enums, we need to define behavior that lets us check what enumerator\r\n // is being accessed and what enumerator is being set. This can be done by \r\n // defining \"get\" and \"set\" traps.\r\n constructor(enumObj) {\r\n const handler = {\r\n get(target, name) {\r\n if (typeof target[name] != 'undefined') {\r\n return target[name]\r\n }\r\n throw new Error(`No such enumerator: ${name}`)\r\n },\r\n set() {\r\n throw new Error('Cannot add/update properties on an Enum instance after it is defined')\r\n }\r\n }\r\n\r\n\r\n // Freeze the target object to prevent modifications\r\n return new Proxy(enumObj, handler)\r\n }\r\n}\r\n\r\n\r\n// Now that we have a generic way of creating Enums, lets create our first Enum!\r\nconst httpMethods = new Enum({\r\n DELETE: \"DELETE\",\r\n GET: \"GET\",\r\n OPTIONS: \"OPTIONS\",\r\n PATCH: \"PATCH\",\r\n POST: \"POST\",\r\n PUT: \"PUT\"\r\n})\r\n\r\n// Sanity checks\r\nconsole.log(httpMethods.DELETE)\r\n// logs \"DELETE\"\r\n\r\ntry {\r\n httpMethods.delete = \"delete\"\r\n} catch (e) {\r\nconsole.log(\"Error: \", e.message)\r\n}\r\n// throws \"Cannot add/update properties on an Enum instance after it is defined\"\r\n\r\ntry {\r\n console.log(httpMethods.delete)\r\n} catch (e) {\r\n console.log(\"Error: \", e.message)\r\n}\r\n// throws \"No such enumerator: delete\"</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<hr>\n\n<p><strong>ASIDE: What the heck is a proxy?</strong></p>\n\n<p>I remember when I first started seeing the word proxy everywhere, it definitely didn't make sense to me for a long time. If that's you right now, I think an easy way to generalize proxies is to think of them as software, institutions, or even people that act as intermediaries or middlemen between two servers, companies, or people. </p>\n"
},
{
"answer_id": 50115744,
"author": "Julius DzidzeviΔius",
"author_id": 4554116,
"author_profile": "https://Stackoverflow.com/users/4554116",
"pm_score": 2,
"selected": false,
"text": "<p>This is how Typescript translates it's <code>enum</code> into Javascript:</p>\n\n<pre><code>var makeEnum = function(obj) {\n obj[ obj['Active'] = 1 ] = 'Active';\n obj[ obj['Closed'] = 2 ] = 'Closed';\n obj[ obj['Deleted'] = 3 ] = 'Deleted';\n}\n</code></pre>\n\n<p>Now:</p>\n\n<pre><code>makeEnum( NewObj = {} )\n// => {1: \"Active\", 2: \"Closed\", 3: \"Deleted\", Active: 1, Closed: 2, Deleted: 3}\n</code></pre>\n\n<p>At first I was confused why <code>obj[1]</code> returns <code>'Active'</code>, but then realised that its dead simple - <strong>Assignment operator</strong> assigns value and then returns it:</p>\n\n<pre><code>obj['foo'] = 1\n// => 1\n</code></pre>\n"
},
{
"answer_id": 50355530,
"author": "Jack G",
"author_id": 5601591,
"author_profile": "https://Stackoverflow.com/users/5601591",
"pm_score": 5,
"selected": false,
"text": "<h1>- </h1>\n<p>Let's cut straight to the problem: file size. Every other answer listed here bloats your minified code to the extreme. I present to you that for the best possible reduction in code size by minification, performance, readability of code, large scale project management, and syntax hinting in many code editors, this is the correct way to do enumerations: underscore-notation variables.</p>\n<hr />\n<h1><img src=\"https://i.stack.imgur.com/vUCWq.png\" alt=\"Underscore-Notation Variables\" /></h1>\n<p>As demonstrated in the chart above and example below, here are five easy steps to get started:</p>\n<ol>\n<li>Determine a name for the enumeration group. Think of a noun that can describe the purpose of the enumeration or at least the entries in the enumeration. For example, a group of enumerations representing colors choosable by the user might be better named COLORCHOICES than COLORS.</li>\n<li>Decide whether enumerations in the group are mutually-exclusive or independent. If mutually-exclusive, start each enumerated variable name with <code>ENUM_</code>. If independent or side-by-side, use <code>INDEX_</code>.</li>\n<li>For each entry, create a new local variable whose name starts with <code>ENUM_</code> or <code>INDEX_</code>, then the name of the group, then an underscore, then a unique friendly name for the property</li>\n<li>Add a <code>ENUMLENGTH_</code>, <code>ENUMLEN_</code>, <code>INDEXLENGTH_</code>, or <code>INDEXLEN_</code> (whether <code>LEN_</code> or <code>LENGTH_</code> is personal preference) enumerated variable at the very end. You should use this variable wherever possible in your code to ensure that adding an extra entry to the enumeration and incrementing this value won't break your code.</li>\n<li>Give each successive enumerated variable a value one more than the last, starting at 0. There are comments on this page that say <code>0</code> should not be used as an enumerated value because <code>0 == null</code>, <code>0 == false</code>, <code>0 == \"\"</code>, and other JS craziness. I submit to you that, to avoid this problem and boost performance at the same time, always use <code>===</code> and never let <code>==</code> appear in your code except with <code>typeof</code> (e.x. <code>typeof X == \"string\"</code>). In all my years of using <code>===</code>, I have never once had a problem with using 0 as an enumeration value. If you are still squeamish, then <code>1</code> could be used as the starting value in <code>ENUM_</code> enumerations (but not in <code>INDEX_</code> enumerations) without performance penalty in many cases.</li>\n</ol>\n<pre><code>const ENUM_COLORENUM_RED = 0;\nconst ENUM_COLORENUM_GREEN = 1;\nconst ENUM_COLORENUM_BLUE = 2;\nconst ENUMLEN_COLORENUM = 3;\n\n// later on\n\nif(currentColor === ENUM_COLORENUM_RED) {\n // whatever\n}\n</code></pre>\n<p>Here is how I remember when to use <code>INDEX_</code> and when to use <code>ENUM_</code>:</p>\n<pre><code>// Precondition: var arr = []; //\narr[INDEX_] = ENUM_;\n</code></pre>\n<p>However, <code>ENUM_</code> can, in certain circumstances, be appropriate as an index such as when counting the occurrences of each item.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const ENUM_PET_CAT = 0,\n ENUM_PET_DOG = 1,\n ENUM_PET_RAT = 2,\n ENUMLEN_PET = 3;\n\nvar favoritePets = [ENUM_PET_CAT, ENUM_PET_DOG, ENUM_PET_RAT,\n ENUM_PET_DOG, ENUM_PET_DOG, ENUM_PET_CAT,\n ENUM_PET_RAT, ENUM_PET_CAT, ENUM_PET_DOG];\n\nvar petsFrequency = [];\n\nfor (var i=0; i<ENUMLEN_PET; i=i+1|0)\n petsFrequency[i] = 0;\n\nfor (var i=0, len=favoritePets.length|0, petId=0; i<len; i=i+1|0)\n petsFrequency[petId = favoritePets[i]|0] = (petsFrequency[petId]|0) + 1|0;\n\nconsole.log({\n \"cat\": petsFrequency[ENUM_PET_CAT],\n \"dog\": petsFrequency[ENUM_PET_DOG],\n \"rat\": petsFrequency[ENUM_PET_RAT]\n});</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Observe that, in the code above, it's really easy to add in a new kind of pet: you would just have to append a new entry after <code>ENUM_PET_RAT</code> and update <code>ENUMLEN_PET</code> accordingly. It might be more difficult and buggy to add a new entry in other systems of enumeration.</p>\n<hr />\n<h1> </h1>\n<p>Additionally, this syntax of enumerations allows for clear and concise class extending as seen below. To extend a class, add an incrementing number to the <code>LEN_</code> entry of the parent class. Then, finish out the subclass with its own <code>LEN_</code> entry so that the subclass may be extended further in the future.</p>\n<p><img src=\"https://i.stack.imgur.com/xIHxl.png\" alt=\"Addition extension diagram\" /></p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>(function(window){\n \"use strict\";\n var parseInt = window.parseInt;\n\n // use INDEX_ when representing the index in an array instance\n const INDEX_PIXELCOLOR_TYPE = 0, // is a ENUM_PIXELTYPE\n INDEXLEN_PIXELCOLOR = 1,\n INDEX_SOLIDCOLOR_R = INDEXLEN_PIXELCOLOR+0,\n INDEX_SOLIDCOLOR_G = INDEXLEN_PIXELCOLOR+1,\n INDEX_SOLIDCOLOR_B = INDEXLEN_PIXELCOLOR+2,\n INDEXLEN_SOLIDCOLOR = INDEXLEN_PIXELCOLOR+3,\n INDEX_ALPHACOLOR_R = INDEXLEN_PIXELCOLOR+0,\n INDEX_ALPHACOLOR_G = INDEXLEN_PIXELCOLOR+1,\n INDEX_ALPHACOLOR_B = INDEXLEN_PIXELCOLOR+2,\n INDEX_ALPHACOLOR_A = INDEXLEN_PIXELCOLOR+3,\n INDEXLEN_ALPHACOLOR = INDEXLEN_PIXELCOLOR+4,\n // use ENUM_ when representing a mutually-exclusive species or type\n ENUM_PIXELTYPE_SOLID = 0,\n ENUM_PIXELTYPE_ALPHA = 1,\n ENUM_PIXELTYPE_UNKNOWN = 2,\n ENUMLEN_PIXELTYPE = 2;\n\n function parseHexColor(inputString) {\n var rawstr = inputString.trim().substring(1);\n var result = [];\n if (rawstr.length === 8) {\n result[INDEX_PIXELCOLOR_TYPE] = ENUM_PIXELTYPE_ALPHA;\n result[INDEX_ALPHACOLOR_R] = parseInt(rawstr.substring(0,2), 16);\n result[INDEX_ALPHACOLOR_G] = parseInt(rawstr.substring(2,4), 16);\n result[INDEX_ALPHACOLOR_B] = parseInt(rawstr.substring(4,6), 16);\n result[INDEX_ALPHACOLOR_A] = parseInt(rawstr.substring(4,6), 16);\n } else if (rawstr.length === 4) {\n result[INDEX_PIXELCOLOR_TYPE] = ENUM_PIXELTYPE_ALPHA;\n result[INDEX_ALPHACOLOR_R] = parseInt(rawstr[0], 16) * 0x11;\n result[INDEX_ALPHACOLOR_G] = parseInt(rawstr[1], 16) * 0x11;\n result[INDEX_ALPHACOLOR_B] = parseInt(rawstr[2], 16) * 0x11;\n result[INDEX_ALPHACOLOR_A] = parseInt(rawstr[3], 16) * 0x11;\n } else if (rawstr.length === 6) {\n result[INDEX_PIXELCOLOR_TYPE] = ENUM_PIXELTYPE_SOLID;\n result[INDEX_SOLIDCOLOR_R] = parseInt(rawstr.substring(0,2), 16);\n result[INDEX_SOLIDCOLOR_G] = parseInt(rawstr.substring(2,4), 16);\n result[INDEX_SOLIDCOLOR_B] = parseInt(rawstr.substring(4,6), 16);\n } else if (rawstr.length === 3) {\n result[INDEX_PIXELCOLOR_TYPE] = ENUM_PIXELTYPE_SOLID;\n result[INDEX_SOLIDCOLOR_R] = parseInt(rawstr[0], 16) * 0x11;\n result[INDEX_SOLIDCOLOR_G] = parseInt(rawstr[1], 16) * 0x11;\n result[INDEX_SOLIDCOLOR_B] = parseInt(rawstr[2], 16) * 0x11;\n } else {\n result[INDEX_PIXELCOLOR_TYPE] = ENUM_PIXELTYPE_UNKNOWN;\n }\n return result;\n }\n\n // the red component of green\n console.log(parseHexColor(\"#0f0\")[INDEX_SOLIDCOLOR_R]);\n // the alpha of transparent purple\n console.log(parseHexColor(\"#f0f7\")[INDEX_ALPHACOLOR_A]); \n // the enumerated array for turquoise\n console.log(parseHexColor(\"#40E0D0\"));\n})(self);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>(Length: 2,450 bytes)</p>\n<p>Some may say that this is less practical than other solutions: it wastes tons of space, it takes a long time to write, and it is not coated with sugar syntax. Those people would be right if they do not minify their code. However, no reasonable person would leave unminified code in the end product. For this minification, Closure Compiler is the best I have yet to find. Online access can be found <a href=\"https://closure-compiler.appspot.com/\" rel=\"noreferrer\">here</a>. Closure compiler is able to take all of this enumeration data and inline it, making your Javascript be super duper small and run super duper fast. Thus, Minify with Closure Compiler. Observe.</p>\n<hr />\n<h1> <a href=\"https://closure-compiler.appspot.com/\" rel=\"noreferrer\"> </a></h1>\n<p>Closure compiler is able to perform some pretty incredible optimizations via inferences that are way beyond the capacities of any other Javascript minifier. Closure Compiler is able to inline primitive variables set to a fixed value. Closure Compiler is also able to make inferences based upon these inlined values and eliminate unused blocks in if-statements and loops.</p>\n<p><img src=\"https://i.stack.imgur.com/2cadt.jpg\" alt=\"Wringing code via Closure Compiler\" /></p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>'use strict';(function(e){function d(a){a=a.trim().substring(1);var b=[];8===a.length?(b[0]=1,b[1]=c(a.substring(0,2),16),b[2]=c(a.substring(2,4),16),b[3]=c(a.substring(4,6),16),b[4]=c(a.substring(4,6),16)):4===a.length?(b[1]=17*c(a[0],16),b[2]=17*c(a[1],16),b[3]=17*c(a[2],16),b[4]=17*c(a[3],16)):6===a.length?(b[0]=0,b[1]=c(a.substring(0,2),16),b[2]=c(a.substring(2,4),16),b[3]=c(a.substring(4,6),16)):3===a.length?(b[0]=0,b[1]=17*c(a[0],16),b[2]=17*c(a[1],16),b[3]=17*c(a[2],16)):b[0]=2;return b}var c=\ne.parseInt;console.log(d(\"#0f0\")[1]);console.log(d(\"#f0f7\")[4]);console.log(d(\"#40E0D0\"))})(self);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>(Length: 605 bytes)</p>\n<p>Closure Compiler rewards you for coding smarter and organizing your code well because, whereas many minifiers punish organized code with a bigger minified file size, Closure Compiler is able to sift through all your cleanliness and sanity to output an even smaller file size if you use tricks like variable name enumerations. That, in this one mind, is the holy grail of coding: a tool that both assists your code with a smaller minified size and assists your mind by training better programming habits.</p>\n<hr />\n<h1> </h1>\n<p>Now, let us see how big the equivalent file would be without any of these enumerations.\n<br /><br /></p>\n<p><a href=\"https://pastebin.com/embed_iframe/fcX5fN2V\" rel=\"noreferrer\">Source Without Using Enumerations</a> (length: 1,973 bytes (477 bytes shorter than enumerated code!))<br />\n<a href=\"https://pastebin.com/embed_iframe/97K6XLdU\" rel=\"noreferrer\">Minified Without Using Enumerations</a> (length: 843 bytes (238 bytes <strong>longer than enumerated code</strong>))</p>\n<p><img src=\"https://i.stack.imgur.com/DX0nA.png\" alt=\"Chart of code sizes\" /></p>\n<p><br /><br /></p>\n<p>As seen, without enumerations, the source code is shorter at the cost of a larger minified code. I do not know about you; but I know for sure that I do not incorporate source code into the end product. Thus, this form of enumerations is far superior insomuch that it results in smaller minified file sizes.</p>\n<hr />\n<h1> </h1>\n<p>Another advantage about this form of enumeration is that it can be used to easily manage large scale projects without sacrificing minified code size. When working on a large project with lots of other people, it might be beneficial to explicitly mark and label the variable names with who created the code so that the original creator of the code can be quickly identified for collaborative bug fixing.</p>\n<pre class=\"lang-js prettyprint-override\"><code>// JG = Jack Giffin\nconst ENUM_JG_COLORENUM_RED = 0,\n ENUM_JG_COLORENUM_GREEN = 1,\n ENUM_JG_COLORENUM_BLUE = 2,\n ENUMLEN_JG_COLORENUM = 3;\n\n// later on\n\nif(currentColor === ENUM_JG_COLORENUM_RED) {\n // whatever\n}\n\n// PL = Pepper Loftus\n// BK = Bob Knight\nconst ENUM_PL_ARRAYTYPE_UNSORTED = 0,\n ENUM_PL_ARRAYTYPE_ISSORTED = 1,\n ENUM_BK_ARRAYTYPE_CHUNKED = 2, // added by Bob Knight\n ENUM_JG_ARRAYTYPE_INCOMPLETE = 3, // added by jack giffin\n ENUMLEN_PL_COLORENUM = 4;\n\n// later on\n\nif(\n randomArray === ENUM_PL_ARRAYTYPE_UNSORTED ||\n randomArray === ENUM_BK_ARRAYTYPE_CHUNKED\n) {\n // whatever\n}\n</code></pre>\n\n<hr />\n<h1> <sub><sub><sub><sub><img src=\"https://i.stack.imgur.com/OoOrv.png\" /></sub></sub></sub></sub></h1>\n<p>Further, this form of enumeration is also much faster after minification. In normal named properties, the browser has to use hashmaps to look up where the property is on the object. Although JIT compilers intelligently cache this location on the object, there is still tremendous overhead due to special cases such as deleting a lower property from the object.</p>\n<img src=\"https://v8.dev/_img/elements-kinds/lattice.svg\" />\n<p>But, with continuous non-sparse integer-indexed <a href=\"https://v8.dev/blog/elements-kinds#the-elements-kind-lattice\" rel=\"noreferrer\">PACKED_ELEMENTS</a> arrays, the browser is able to skip much of that overhead because the index of the value in the internal array is already specified. Yes, according to the ECMAScript standard, all properties are supposed to be treated as strings. Nevertheless, this aspect of the ECMAScript standard is very misleading about performance because all browsers have special optimizations for numeric indexes in arrays.</p>\n<pre><code>/// Hashmaps are slow, even with JIT juice\nvar ref = {};\nref.count = 10;\nref.value = "foobar";\n</code></pre>\n<p>Compare the code above to the code below.</p>\n<pre><code>/// Arrays, however, are always lightning fast\nconst INDEX_REFERENCE_COUNT = 0;\nconst INDEX_REFERENCE_VALUE = 1;\nconst INDEXLENGTH_REFERENCE = 2;\n\nvar ref = [];\nref[INDEX_REFERENCE_COUNT] = 10;\nref[INDEX_REFERENCE_VALUE] = "foobar";\n</code></pre>\n<p>One might object to the code with enumerations seeming to be much longer than the code with ordinary objects, but looks can be deceiving. It is important to remember that source code size is not proportional to output size when using the epic Closure Compiler. Observe.</p>\n<pre><code>/// Hashmaps are slow, even with JIT juice\nvar a={count:10,value:"foobar"};\n</code></pre>\n<p>The minified code without enumerations is above and the minified code with enumerations is below.</p>\n<pre><code>/// Arrays, however, are always lightning fast\nvar a=[10,"foobar"];\n</code></pre>\n<p>The example above demonstrates that, in addition to having superior performance, the enumerated code also results in a smaller minified file size.</p>\n<hr />\n<h1> </h1>\n<p>Furthermore, this one's personal <em>cherry on the top</em> is using this form of enumerations along with the <a href=\"https://codemirror.net/\" rel=\"noreferrer\">CodeMirror</a> text editor in Javascript mode. CodeMirror's Javascript syntax highlighting mode highlights local variables in the current scope. That way, you know instantly when you type in a variable name correctly because if the variable name was previously declared with the <code>var</code> keyword, then the variable name turns a special color (cyan by default). Even if you do not use CodeMirror, then at least the browser throws a helpful <code><em>[variable name]</em> is not defined</code> exception when executing code with mistyped enumeration names. Also, JavaScript tools such as JSLint and Closure Compiler are very loud about telling you when you mistype in an enumeration variable name. CodeMirror, the browser, and various Javascript tools put together make debugging this form of enumeration very simple and really easy.</p>\n<p><img src=\"https://i.stack.imgur.com/sSyEB.png\" alt=\"CodeMirror highlighting demonstration\" /></p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const ENUM_COLORENUM_RED = 0,\n ENUM_COLORENUM_GREEN = 1,\n ENUM_COLORENUM_BLUE = 2,\n ENUMLEN_COLORENUM = 3;\nvar currentColor = ENUM_COLORENUM_GREEN;\n\nif(currentColor === ENUM_COLORENUM_RED) {\n // whatever\n}\n\nif(currentColor === ENUM_COLORENUM_DNE) {\n // whatever\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>In the above snippet, you were alerted with an error because <code>ENUM_COLORENUM_DNE</code> does not exist.</p>\n<hr />\n<h1></h1>\n<p>I think its safe to say that this methodology of enumeration is indeed the best way to go not just for minified code size, but also for performance, debugging, and collaboration.</p>\n"
},
{
"answer_id": 52019639,
"author": "jamess",
"author_id": 4941356,
"author_profile": "https://Stackoverflow.com/users/4941356",
"pm_score": 0,
"selected": false,
"text": "<p>This answer is an alternative approach for specific circumstances. I needed a set of bitmask constants based on attribute sub-values (cases where an attribute value is an array or list of values). It encompasses the equivalent of several overlapping enums. </p>\n\n<p>I created a class to both store and generate the bitmask values. I can then use the pseudo-constant bitmask values this way to test, for example, if green is present in an RGB value: </p>\n\n<pre><code>if (value & Ez.G) {...}\n</code></pre>\n\n<p>In my code I create only one instance of this class. There doesn't seem to be a clean way to do this without instantiating at least one instance of the class. Here is the class declaration and bitmask value generation code:</p>\n\n<pre><code>class Ez {\nconstructor() {\n let rgba = [\"R\", \"G\", \"B\", \"A\"];\n let rgbm = rgba.slice();\n rgbm.push(\"M\"); // for feColorMatrix values attribute\n this.createValues(rgba);\n this.createValues([\"H\", \"S\", \"L\"]);\n this.createValues([rgba, rgbm]);\n this.createValues([attX, attY, attW, attH]);\n}\ncreateValues(a) { // a for array\n let i, j;\n if (isA(a[0])) { // max 2 dimensions\n let k = 1;\n for (i of a[0]) {\n for (j of a[1]) {\n this[i + j] = k;\n k *= 2;\n }\n }\n }\n else { // 1D array is simple loop\n for (i = 0, j = 1; i < a.length; i++, j *= 2)\n this[a[i]] = j;\n }\n}\n</code></pre>\n\n<p>The 2D array is for the SVG feColorMatrix values attribute, which is a 4x5 matrix of RGBA by RGBAM, where M is a multiplier. The resulting Ez properties are Ez.RR, Ez.RG, etc.</p>\n"
},
{
"answer_id": 52409064,
"author": "papiro",
"author_id": 3878933,
"author_profile": "https://Stackoverflow.com/users/3878933",
"pm_score": 2,
"selected": false,
"text": "<pre><code>class Enum {\n constructor (...vals) {\n vals.forEach( val => {\n const CONSTANT = Symbol(val);\n Object.defineProperty(this, val.toUpperCase(), {\n get () {\n return CONSTANT;\n },\n set (val) {\n const enum_val = \"CONSTANT\";\n // generate TypeError associated with attempting to change the value of a constant\n enum_val = val;\n }\n });\n });\n }\n}\n</code></pre>\n\n<p>Example of usage:</p>\n\n<pre><code>const COLORS = new Enum(\"red\", \"blue\", \"green\");\n</code></pre>\n"
},
{
"answer_id": 55695903,
"author": "oluckyman",
"author_id": 823778,
"author_profile": "https://Stackoverflow.com/users/823778",
"pm_score": 1,
"selected": false,
"text": "<p>Read all the answers and didn't found any non-verbose and DRY solution.\nI use this one-liner:</p>\n\n<pre><code>const modes = ['DRAW', 'SCALE', 'DRAG'].reduce((o, v) => ({ ...o, [v]: v }), {});\n</code></pre>\n\n<p>it generates an object with human-readable values:</p>\n\n<pre><code>{\n DRAW: 'DRAW',\n SCALE: 'SCALE',\n DRAG: 'DRAG'\n}\n</code></pre>\n"
},
{
"answer_id": 60309416,
"author": "Andrew",
"author_id": 1599699,
"author_profile": "https://Stackoverflow.com/users/1599699",
"pm_score": 3,
"selected": false,
"text": "<p>I wasn't satisfied with any of the answers, so I made <em>Yet Another Enum (YEA!)</em>.</p>\n\n<p>This implementation:</p>\n\n<ul>\n<li>uses more up-to-date JS</li>\n<li>requires just the declaration of this one class to easily create enums</li>\n<li>has mapping by name (<code>colors.RED</code>), string (<code>colors[\"RED\"]</code>), and index (<code>colors[0]</code>), but you only need to pass in the strings as an array</li>\n<li>binds equivalent <code>toString()</code> and <code>valueOf()</code> functions to each enum object (if this is somehow not desired, one can simply remove it - small overhead for JS though)</li>\n<li>has optional global naming/storage by name string</li>\n<li>freezes the enum object once created so that it can't be modified</li>\n</ul>\n\n<p>Special thanks to <a href=\"https://stackoverflow.com/a/6672823/1599699\">Andre 'Fi''s answer</a> for some inspiration.</p>\n\n<hr>\n\n<p><strong>The codes:</strong></p>\n\n<pre class=\"lang-js prettyprint-override\"><code>class Enums {\n static create({ name = undefined, items = [] }) {\n let newEnum = {};\n newEnum.length = items.length;\n newEnum.items = items;\n for (let itemIndex in items) {\n //Map by name.\n newEnum[items[itemIndex]] = parseInt(itemIndex, 10);\n //Map by index.\n newEnum[parseInt(itemIndex, 10)] = items[itemIndex];\n }\n newEnum.toString = Enums.enumToString.bind(newEnum);\n newEnum.valueOf = newEnum.toString;\n //Optional naming and global registration.\n if (name != undefined) {\n newEnum.name = name;\n Enums[name] = newEnum;\n }\n //Prevent modification of the enum object.\n Object.freeze(newEnum);\n return newEnum;\n }\n static enumToString() {\n return \"Enum \" +\n (this.name != undefined ? this.name + \" \" : \"\") +\n \"[\" + this.items.toString() + \"]\";\n }\n}\n</code></pre>\n\n<hr>\n\n<p><strong>Usage:</strong></p>\n\n<pre class=\"lang-js prettyprint-override\"><code>let colors = Enums.create({\n name: \"COLORS\",\n items: [ \"RED\", \"GREEN\", \"BLUE\", \"PORPLE\" ]\n});\n\n//Global access, if named.\nEnums.COLORS;\n\ncolors.items; //Array(4) [ \"RED\", \"GREEN\", \"BLUE\", \"PORPLE\" ]\ncolors.length; //4\n\ncolors.RED; //0\ncolors.GREEN; //1\ncolors.BLUE; //2\ncolors.PORPLE; //3\ncolors[0]; //\"RED\"\ncolors[1]; //\"GREEN\"\ncolors[2]; //\"BLUE\"\ncolors[3]; //\"PORPLE\"\n\ncolors.toString(); //\"Enum COLORS [RED,GREEN,BLUE,PORPLE]\"\n\n//Enum frozen, makes it a real enum.\ncolors.RED = 9001;\ncolors.RED; //0\n</code></pre>\n"
},
{
"answer_id": 62358238,
"author": "Aral Roca",
"author_id": 4467741,
"author_profile": "https://Stackoverflow.com/users/4467741",
"pm_score": 3,
"selected": false,
"text": "<p>This can be useful:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const [CATS, DOGS, BIRDS] = ENUM();\n</code></pre>\n<p>The implementation is simple and efficient:</p>\n<pre class=\"lang-js prettyprint-override\"><code>function * ENUM(count=1) { while(true) yield count++ }\n</code></pre>\n<p>A generator can yield the exact sequence of integers required, without knowing how many constants there are. It can also support an optional argument that specifies which (possibly negative) number to start from (defaulting to <code>1</code>).</p>\n"
},
{
"answer_id": 62929829,
"author": "Idan",
"author_id": 6591688,
"author_profile": "https://Stackoverflow.com/users/6591688",
"pm_score": 0,
"selected": false,
"text": "<pre><code>export const ButtonType = Object.freeze({ \n DEFAULT: 'default', \n BIG: 'big', \n SMALL: 'small'\n})\n</code></pre>\n<p>source: <a href=\"https://medium.com/@idanlevi2/enum-in-javascript-5f2ff500f149\" rel=\"nofollow noreferrer\">https://medium.com/@idanlevi2/enum-in-javascript-5f2ff500f149</a></p>\n"
},
{
"answer_id": 64416419,
"author": "dsanchez",
"author_id": 1514122,
"author_profile": "https://Stackoverflow.com/users/1514122",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Update 05.11.2020:</strong><br>\nModified to include static fields and methods to closer replicate "true" enum behavior.</p>\n<p>Has anyone tried doing this with a class that contains private fields and "get" accessors?\nI realize private class fields are still experimental at this point but it seems to work for the purposes of creating a class with immutable fields/properties. Browser support is decent as well. The only "major" browsers that don't support it are Firefox (which I'm sure they will soon) and IE (who cares).</p>\n<p><em>DISCLAIMER</em>:<br>\nI am not a developer. I was just looking for an answer to this question and started thinking about how I sometimes create "enhanced" enums in C# by creating classes with private fields and restricted property accessors.</p>\n<p><em><strong>Sample Class</strong></em></p>\n<pre><code>class Sizes {\n // Private Fields\n static #_SMALL = 0;\n static #_MEDIUM = 1;\n static #_LARGE = 2;\n\n // Accessors for "get" functions only (no "set" functions)\n static get SMALL() { return this.#_SMALL; }\n static get MEDIUM() { return this.#_MEDIUM; }\n static get LARGE() { return this.#_LARGE; }\n}\n</code></pre>\n<p>You should now be able to call your enums directly.</p>\n<pre><code>Sizes.SMALL; // 0\nSizes.MEDIUM; // 1\nSizes.LARGE; // 2\n</code></pre>\n<p>The combination of using private fields and limited accessors means that the enum values are well protected.</p>\n<pre><code>Sizes.SMALL = 10 // Sizes.SMALL is still 0\nSizes._SMALL = 10 // Sizes.SMALL is still 0\nSizes.#_SMALL = 10 // Sizes.SMALL is still 0\n</code></pre>\n"
},
{
"answer_id": 64631389,
"author": "KooiInc",
"author_id": 58186,
"author_profile": "https://Stackoverflow.com/users/58186",
"pm_score": 0,
"selected": false,
"text": "<p>Here's my take on a (flagged) <code>Enum</code> factory. Here's a <a href=\"https://jsfiddle.net/KooiInc/1527adxq/\" rel=\"nofollow noreferrer\">working demo</a>.</p>\n<pre><code>/*\n * Notes: \n * The proxy handler enables case insensitive property queries\n * BigInt is used to enable bitflag strings /w length > 52\n*/\nfunction EnumFactory() {\n const proxyfy = {\n construct(target, args) { \n const caseInsensitiveHandler = { \n get(target, key) {\n return target[key.toUpperCase()] || target[key]; \n } \n };\n const proxified = new Proxy(new target(...args), caseInsensitiveHandler ); \n return Object.freeze(proxified);\n },\n }\n const ProxiedEnumCtor = new Proxy(EnumCtor, proxyfy);\n const throwIf = (\n assertion = false, \n message = `Unspecified error`, \n ErrorType = Error ) => \n assertion && (() => { throw new ErrorType(message); })();\n const hasFlag = (val, sub) => {\n throwIf(!val || !sub, "valueIn: missing parameters", RangeError);\n const andVal = (sub & val);\n return andVal !== BigInt(0) && andVal === val;\n };\n\n function EnumCtor(values) {\n throwIf(values.constructor !== Array || \n values.length < 2 || \n values.filter( v => v.constructor !== String ).length > 0,\n `EnumFactory: expected Array of at least 2 strings`, TypeError);\n const base = BigInt(1);\n this.NONE = BigInt(0);\n values.forEach( (v, i) => this[v.toUpperCase()] = base<<BigInt(i) );\n }\n\n EnumCtor.prototype = {\n get keys() { return Object.keys(this).slice(1); },\n subset(sub) {\n const arrayValues = this.keys;\n return new ProxiedEnumCtor(\n [...sub.toString(2)].reverse()\n .reduce( (acc, v, i) => ( +v < 1 ? acc : [...acc, arrayValues[i]] ), [] )\n );\n },\n getLabel(enumValue) {\n const tryLabel = Object.entries(this).find( value => value[1] === enumValue );\n return !enumValue || !tryLabel.length ? \n "getLabel: no value parameter or value not in enum" :\n tryLabel.shift();\n },\n hasFlag(val, sub = this) { return hasFlag(val, sub); },\n };\n \n return arr => new ProxiedEnumCtor(arr);\n}\n</code></pre>\n"
},
{
"answer_id": 71026153,
"author": "Sebastian Norr",
"author_id": 7880517,
"author_profile": "https://Stackoverflow.com/users/7880517",
"pm_score": 0,
"selected": false,
"text": "<p>I was searching for an answer to this question too & found this page with an answer that I think seams to be different from most answers here:\n<a href=\"https://www.sohamkamani.com/javascript/enums/\" rel=\"nofollow noreferrer\">https://www.sohamkamani.com/javascript/enums/</a></p>\n<p>I will copy over the answer part of the article to here, just in case the link gets invalid in the future or something:</p>\n<blockquote>\n<p><strong>Enums with Symbols:</strong></p>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol\" rel=\"nofollow noreferrer\">Symbols</a> let us define values that are guaranteed not to collide\nwith one another.</p>\n<p>For example:</p>\n</blockquote>\n<pre><code>const Summer1 = Symbol("summer")\nconst Summer2 = Symbol("summer")\n\n// Even though they have the same apparent value\n// Summer1 and Summer2 don't equate\nconsole.log(Summer1 === Summer2)\n// false\n\nconsole.log(Summer1)\n</code></pre>\n<blockquote>\n<p>We can define our enums using Symbols to ensure that they are not\nduplicated:</p>\n</blockquote>\n<pre><code>const Summer = Symbol("summer")\nconst Autumn = Symbol("autumn")\nconst Winter = Symbol("winter")\nconst Spring = Symbol("spring")\n\nlet season = Spring\n\nswitch (season) {\n case Summer:\n console.log('the season is summer')\n break;\n case Winter:\n console.log('the season is winter')\n break;\n case Spring:\n console.log('the season is spring')\n break;\n case Autumn:\n console.log('the season is autumn')\n break;\n default:\n console.log('season not defined')\n}\n</code></pre>\n<blockquote>\n<p>Using Symbols ensures that the only way we can assign an enum value is by using the constants that we defined initially.</p>\n</blockquote>\n<blockquote>\n<p><strong>Enums with Classes:</strong></p>\n</blockquote>\n<blockquote>\n<p>To make our code more semantically correct, we can create a class to\nhold groups of enums.</p>\n<p>For example, our seasons should have a way for us to identify that\nthey all belong to a similar classification.</p>\n<p>Letβs see how we can use classes and objects to create distinct enum\ngroups:</p>\n</blockquote>\n<pre><code>// Season enums can be grouped as static members of a class\nclass Season {\n // Create new instances of the same class as static attributes\n static Summer = new Season("summer")\n static Autumn = new Season("autumn")\n static Winter = new Season("winter")\n static Spring = new Season("spring")\n\n constructor(name) {\n this.name = name\n }\n}\n\n// Now we can access enums using namespaced assignments\n// this makes it semantically clear that "Summer" is a "Season"\nlet season = Season.Summer\n\n// We can verify whether a particular variable is a Season enum\nconsole.log(season instanceof Season)\n// true\nconsole.log(Symbol('something') instanceof Season)\n//false\n\n// We can explicitly check the type based on each enums class\nconsole.log(season.constructor.name)\n// 'Season'\n</code></pre>\n<p><em>personal note: I would have used this constructor instead: (Note: sets: <code>this.name</code>, to a string instead of an object, looses some of the verifications below. Optionally remove the: <code>.description</code>. I would also like to find a way to not have to type <code>Seasons.summer.name</code> but instead only need: <code>Seasons.summer</code> to make it return a string)</em></p>\n<pre><code> constructor(name) {\n this.name = Symbol(name).description\n }\n</code></pre>\n<blockquote>\n<p><strong>Listing All Possible Enum Values:</strong></p>\n</blockquote>\n<blockquote>\n<p>If we used the class-based approach above, we can loop through the\nkeys of the Season class to obtain all the enum values under the same\ngroup:</p>\n</blockquote>\n<pre><code>Object.keys(Season).forEach(season => console.log("season:", season))\n// season: Summer\n// season: Autumn\n// season: Winter\n// season: Spring\n</code></pre>\n<blockquote>\n<p><strong>When to Use Enums in Javascript?</strong></p>\n</blockquote>\n<blockquote>\n<p>In general, enums are helpful if there are a definite number of fixed\nvalues for any one variable_</p>\n<p>For example, the <a href=\"https://nodejs.org/api/crypto.html#crypto\" rel=\"nofollow noreferrer\">crypto</a> standard library for Node.js has a <a href=\"https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/create-hmac/index.d.ts#L15\" rel=\"nofollow noreferrer\">list of supported algorithms</a>, that can be considered an enum group.</p>\n<p>Using enums in Javascript correctly will lead to better code that is\nmore stable, easier to read and less error prone.</p>\n</blockquote>\n"
},
{
"answer_id": 71432477,
"author": "LEMUEL ADANE",
"author_id": 1347816,
"author_profile": "https://Stackoverflow.com/users/1347816",
"pm_score": 2,
"selected": false,
"text": "<p>You just need to make an immutable object by using <strong>Object.freeze(</strong><em><your_object></em><strong>)</strong>:</p>\n<pre><code>export const ColorEnum = Object.freeze({\n // you can only change the property values here\n // in the object declaration like in the Java enumaration\n RED: 0,\n GREEN: 1,\n BLUE: 2,\n});\n\nColorEnum.RED = 22 // assigning here will throw an error\nColorEnum.VIOLET = 45 // even adding a new property will throw an error\n</code></pre>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/287907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16071/"
] |
I want to transfer data between a smart phone app and a website. What are the conventional and not-so-conventional ways of doing it?
Here's what I have thought of so far:
1. Simple HTTP GET/POST with data being represented as JSON array string, variations of this being encrypted/compressed string as parameter.
2. Webservice calls ( I am not sure if this is even possible, just a guess)
3. Two step communication : Smartphone to/fro Desktop App to/fro Website) (Cumbersome to develop/use)
Also, what do I need to consider to avoid spamming/snooping?
|
Since 1.8.5 it's possible to [seal and freeze the object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze), so define the above as:
```
const DaysEnum = Object.freeze({"monday":1, "tuesday":2, "wednesday":3, ...})
```
or
```
const DaysEnum = {"monday":1, "tuesday":2, "wednesday":3, ...}
Object.freeze(DaysEnum)
```
and voila! JS enums.
However, this doesn't prevent you from assigning an undesired value to a variable, which is often the main goal of enums:
```
let day = DaysEnum.tuesday
day = 298832342 // goes through without any errors
```
One way to ensure a stronger degree of type safety (with enums or otherwise) is to use a tool like [TypeScript](https://www.typescriptlang.org/) or [Flow](https://flow.org/).
Quotes aren't needed but I kept them for consistency.
|
287,928 |
<p>DataGridView, for example, lets you do this:</p>
<pre><code>DataGridView dgv = ...;
DataGridViewCell cell = dgv[1,5];
</code></pre>
<p>but for the life of me I can't find the documentation on the index/square-bracket operator. What do they call it? Where is it implemented? Can it throw? How can I do the same thing in my own classes?</p>
<p>ETA: Thanks for all the quick answers. Briefly: the relevant documentation is under the "Item" property; the way to overload is by declaring a property like <code>public object this[int x, int y]{ get{...}; set{...} }</code>; the indexer for DataGridView does not throw, at least according to the documentation. It doesn't mention what happens if you supply invalid coordinates.</p>
<p>ETA Again: OK, even though the documentation makes no mention of it (naughty Microsoft!), it turns out that the indexer for DataGridView will in fact throw an ArgumentOutOfRangeException if you supply it with invalid coordinates. Fair warning.</p>
|
[
{
"answer_id": 287938,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 5,
"selected": false,
"text": "<pre class=\"lang-none prettyprint-override\"><code>Operators Overloadability\n\n+, -, *, /, %, &, |, <<, >> All C# binary operators can be overloaded.\n\n+, -, !, ~, ++, --, true, false All C# unary operators can be overloaded.\n\n==, !=, <, >, <= , >= All relational operators can be overloaded, \n but only as pairs.\n\n&&, || They can't be overloaded\n\n() (Conversion operator) They can't be overloaded\n\n+=, -=, *=, /=, %= These compound assignment operators can be \n overloaded. But in C#, these operators are\n automatically overloaded when the respective\n binary operator is overloaded.\n\n=, . , ?:, ->, new, is, as, sizeof These operators can't be overloaded\n\n [ ] Can be overloaded but not always!\n</code></pre>\n<p><a href=\"http://www.csharphelp.com/2006/03/c-operator-overloading/\" rel=\"nofollow noreferrer\">Source of the information</a></p>\n<p>For bracket:</p>\n<pre class=\"lang-csharp prettyprint-override\"><code>public Object this[int index]\n{\n \n}\n</code></pre>\n<p>##BUT</p>\n<p>The array indexing operator <strong>cannot be overloaded</strong>; however, types can define indexers, properties that take one or more parameters. Indexer parameters are enclosed in square brackets, just like array indices, but indexer parameters can be declared to be of any type (unlike array indices, which must be integral).</p>\n<p>From <a href=\"http://msdn.microsoft.com/en-us/library/a3hd7ste(VS.71).aspx\" rel=\"nofollow noreferrer\">MSDN</a></p>\n"
},
{
"answer_id": 287945,
"author": "Jason Miesionczek",
"author_id": 18811,
"author_profile": "https://Stackoverflow.com/users/18811",
"pm_score": 3,
"selected": false,
"text": "<pre><code>public class CustomCollection : List<Object>\n{\n public Object this[int index]\n {\n // ...\n }\n}\n</code></pre>\n"
},
{
"answer_id": 287946,
"author": "Ruben",
"author_id": 21733,
"author_profile": "https://Stackoverflow.com/users/21733",
"pm_score": 10,
"selected": true,
"text": "<p>you can find how to do it <a href=\"http://msdn.microsoft.com/en-us/library/6x16t2tx.aspx\" rel=\"noreferrer\">here</a>. \nIn short it is:</p>\n\n<pre><code>public object this[int i]\n{\n get { return InnerList[i]; }\n set { InnerList[i] = value; }\n}\n</code></pre>\n\n<p>If you only need a getter the syntax in <a href=\"https://stackoverflow.com/a/34098286/21733\">answer below</a> can be used as well (starting from C# 6).</p>\n"
},
{
"answer_id": 287948,
"author": "Ricardo Villamil",
"author_id": 19314,
"author_profile": "https://Stackoverflow.com/users/19314",
"pm_score": 5,
"selected": false,
"text": "<p>That would be the item property: <a href=\"http://msdn.microsoft.com/en-us/library/0ebtbkkc.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/0ebtbkkc.aspx</a></p>\n\n<p>Maybe something like this would work:</p>\n\n<pre><code>public T Item[int index, int y]\n{ \n //Then do whatever you need to return/set here.\n get; set; \n}\n</code></pre>\n"
},
{
"answer_id": 287952,
"author": "Rob Prouse",
"author_id": 30827,
"author_profile": "https://Stackoverflow.com/users/30827",
"pm_score": 2,
"selected": false,
"text": "<p>Here is an example returning a value from an internal List object. Should give you the idea.</p>\n\n<pre><code> public object this[int index]\n {\n get { return ( List[index] ); }\n set { List[index] = value; }\n }\n</code></pre>\n"
},
{
"answer_id": 287959,
"author": "Charles Bretana",
"author_id": 32632,
"author_profile": "https://Stackoverflow.com/users/32632",
"pm_score": 1,
"selected": false,
"text": "<p>If you mean the array indexer,, You overload that just by writing an indexer property.. And you can overload, (write as many as you want) indexer properties as long as each one has a different parameter signature</p>\n\n<pre><code>public class EmployeeCollection: List<Employee>\n{\n public Employee this[int employeeId]\n { \n get \n { \n foreach(var emp in this)\n {\n if (emp.EmployeeId == employeeId)\n return emp;\n }\n\n return null;\n }\n }\n\n public Employee this[string employeeName]\n { \n get \n { \n foreach(var emp in this)\n {\n if (emp.Name == employeeName)\n return emp;\n }\n\n return null;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 310114,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>For CLI C++ (compiled with /clr) see <a href=\"http://msdn.microsoft.com/en-us/library/ms235303.aspx\" rel=\"nofollow noreferrer\">this MSDN link</a>.</p>\n\n<p>In short, a property can be given the name \"default\":</p>\n\n<pre><code>ref class Class\n{\n public:\n property System::String^ default[int i]\n {\n System::String^ get(int i) { return \"hello world\"; }\n }\n};\n</code></pre>\n"
},
{
"answer_id": 34098286,
"author": "amoss",
"author_id": 208068,
"author_profile": "https://Stackoverflow.com/users/208068",
"pm_score": 4,
"selected": false,
"text": "<p>If you're using C# 6 or later, you can use expression-bodied syntax for get-only indexer:</p>\n\n<p><code>public object this[int i] => this.InnerList[i];</code></p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/287928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26286/"
] |
DataGridView, for example, lets you do this:
```
DataGridView dgv = ...;
DataGridViewCell cell = dgv[1,5];
```
but for the life of me I can't find the documentation on the index/square-bracket operator. What do they call it? Where is it implemented? Can it throw? How can I do the same thing in my own classes?
ETA: Thanks for all the quick answers. Briefly: the relevant documentation is under the "Item" property; the way to overload is by declaring a property like `public object this[int x, int y]{ get{...}; set{...} }`; the indexer for DataGridView does not throw, at least according to the documentation. It doesn't mention what happens if you supply invalid coordinates.
ETA Again: OK, even though the documentation makes no mention of it (naughty Microsoft!), it turns out that the indexer for DataGridView will in fact throw an ArgumentOutOfRangeException if you supply it with invalid coordinates. Fair warning.
|
you can find how to do it [here](http://msdn.microsoft.com/en-us/library/6x16t2tx.aspx).
In short it is:
```
public object this[int i]
{
get { return InnerList[i]; }
set { InnerList[i] = value; }
}
```
If you only need a getter the syntax in [answer below](https://stackoverflow.com/a/34098286/21733) can be used as well (starting from C# 6).
|
287,954 |
<p>To add a NOT NULL Column to a table with many records, a DEFAULT constraint needs to be applied. This constraint causes the entire ALTER TABLE command to take a long time to run if the table is very large. This is because:</p>
<p>Assumptions:</p>
<ol>
<li>The DEFAULT constraint modifies existing records. This means that the db needs to increase the size of each record, which causes it to shift records on full data-pages to other data-pages and that takes time.</li>
<li>The DEFAULT update executes as an atomic transaction. This means that the transaction log will need to be grown so that a roll-back can be executed if necessary.</li>
<li>The transaction log keeps track of the entire record. Therefore, even though only a single field is modified, the space needed by the log will be based on the size of the entire record multiplied by the # of existing records. This means that adding a column to a table with small records will be faster than adding a column to a table with large records even if the total # of records are the same for both tables.</li>
</ol>
<p>Possible solutions:</p>
<ol>
<li>Suck it up and wait for the process to complete. Just make sure to set the timeout period to be very long. The problem with this is that it may take hours or days to do depending on the # of records.</li>
<li>Add the column but allow NULL. Afterward, run an UPDATE query to set the DEFAULT value for existing rows. Do not do UPDATE *. Update batches of records at a time or you'll end up with the same problem as solution #1. The problem with this approach is that you end up with a column that allows NULL when you know that this is an unnecessary option. I believe that there are some best practice documents out there that says that you should not have columns that allow NULL unless it's necessary.</li>
<li>Create a new table with the same schema. Add the column to that schema. Transfer the data over from the original table. Drop the original table and rename the new table. I'm not certain how this is any better than #1.</li>
</ol>
<p>Questions:</p>
<ol>
<li>Are my assumptions correct? </li>
<li>Are these my only solutions? If so, which one is the best? I f not, what else could I do?</li>
</ol>
|
[
{
"answer_id": 287971,
"author": "Pyrolistical",
"author_id": 21838,
"author_profile": "https://Stackoverflow.com/users/21838",
"pm_score": 0,
"selected": false,
"text": "<p>I think this depends on the SQL flavor you are using, but what if you took option 2, but at the very end alter table table to not null with the default value?</p>\n\n<p>Would it be fast, since it sees all the values are not null?</p>\n"
},
{
"answer_id": 287974,
"author": "Charles Bretana",
"author_id": 32632,
"author_profile": "https://Stackoverflow.com/users/32632",
"pm_score": -1,
"selected": false,
"text": "<p>Vertically segment the table. This means you will have two tables, with the same primary key, and exactly the same number of records... One will be the one you already have, the other will have just the key, and the new Non-Null column (with default value) .\nModify all Insert, Update, and delete code so they keep the two tables in synch... If you want you can create a view that \"joins\" the two tables together to create a single logical combination of the two that appears like a single table for client Select statements...</p>\n"
},
{
"answer_id": 288096,
"author": "HTTP 410",
"author_id": 13118,
"author_profile": "https://Stackoverflow.com/users/13118",
"pm_score": 2,
"selected": false,
"text": "<p>Here's what I would try:</p>\n\n<ul>\n<li>Do a full backup of the database.</li>\n<li>Add the new column, allowing nulls - don't set a default.</li>\n<li>Set SIMPLE recovery, which truncates the tran log as soon as each batch is committed. </li>\n<li>The SQL is: <strong>ALTER DATABASE XXX SET RECOVERY SIMPLE</strong> </li>\n<li>Run the update in batches as you discussed above, committing after each one.</li>\n<li>Reset the new column to no longer allow nulls.</li>\n<li>Go back to the normal FULL recovery. </li>\n<li>The SQL is: <strong>ALTER DATABASE XXX SET RECOVERY FULL</strong></li>\n<li>Backup the database again. </li>\n</ul>\n\n<p>The use of the SIMPLE recovery model doesn't stop logging, but it significantly reduces its impact. This is because the server discards the recovery information after every commit.</p>\n"
},
{
"answer_id": 288717,
"author": "Grzegorz Gierlik",
"author_id": 1483,
"author_profile": "https://Stackoverflow.com/users/1483",
"pm_score": -1,
"selected": false,
"text": "<p>I would use CURSOR instead of UPDATE. Cursor will update all matching records in batch, record by record -- it takes time but not locks table.</p>\n\n<p>If you want to avoid locks use WAIT.</p>\n\n<p>Also I am not sure, that DEFAULT constrain changes existing rows.\nProbably NOT NULL constrain use together with DEFAULT causes case described by author.</p>\n\n<p>If it changes add it in the end\nSo pseudocode will look like:</p>\n\n<pre><code>-- without NOT NULL constrain -- we will add it in the end\nALTER TABLE table ADD new_column INT DEFAULT 0\n\nDECLARE fillNullColumn CURSOR LOCAL FAST_FORWARD\n SELECT \n key\n FROM\n table WITH (NOLOCK)\n WHERE\n new_column IS NULL\n\nOPEN fillNullColumn\n\nDECLARE \n @key INT\n\nFETCH NEXT FROM fillNullColumn INTO @key\n\nWHILE @@FETCH_STATUS = 0 BEGIN\n UPDATE\n table WITH (ROWLOCK)\n SET\n new_column = 0 -- default value\n WHERE\n key = @key\n\n WAIT 00:00:05 --wait 5 seconds, keep in mind it causes updating only 12 rows per minute\n\n FETCH NEXT FROM fillNullColumn INTO @key\nEND\n\nCLOSE fillNullColumn\nDEALLOCATE fillNullColumn\n\nALTER TABLE table ALTER COLUMN new_column ADD CONSTRAIN xxx\n</code></pre>\n\n<p>I am sure that there are some syntax errors, but I hope that this\nhelp to solve your problem.</p>\n\n<p>Good luck!</p>\n"
},
{
"answer_id": 288728,
"author": "Nick DeVore",
"author_id": 1380,
"author_profile": "https://Stackoverflow.com/users/1380",
"pm_score": 0,
"selected": false,
"text": "<p>If you want the column in the same table, you'll just have to do it. Now, option 3 is potentially the best for this because you can still have the database \"live\" while this operation is going on. If you use option 1, the table is locked while the operation happens and then you're really stuck.</p>\n\n<p>If you don't really care if the column is in the table, then I suppose a segmented approach is the next best. Though, I really try to avoid that (to the point that I don't do it) because then like Charles Bretana says, you'll have to make sure and find all the places that update/insert that table and modify those. Ugh!</p>\n"
},
{
"answer_id": 288841,
"author": "Sam Saffron",
"author_id": 17174,
"author_profile": "https://Stackoverflow.com/users/17174",
"pm_score": 2,
"selected": false,
"text": "<p>You could:</p>\n\n<ol>\n<li>Start a transaction.</li>\n<li>Grab a write lock on your original table so no one writes to it. </li>\n<li>Create a shadow table with the new schema. </li>\n<li>Transfer all the data from the original table.</li>\n<li>execute <a href=\"http://msdn.microsoft.com/en-us/library/ms188351.aspx\" rel=\"nofollow noreferrer\">sp_rename</a> to rename the old table out. </li>\n<li>execute <a href=\"http://msdn.microsoft.com/en-us/library/ms188351.aspx\" rel=\"nofollow noreferrer\">sp_rename</a> to rename the new table in. </li>\n<li>Finally, you commit the transaction.</li>\n</ol>\n\n<p>The advantage of this approach is that your readers will be able to access the table during the long process and that you can perform any kind of schema change in the background. </p>\n"
},
{
"answer_id": 649136,
"author": "Chris",
"author_id": 59198,
"author_profile": "https://Stackoverflow.com/users/59198",
"pm_score": 0,
"selected": false,
"text": "<p>I had a similar problem, and went for your option #2.\nIt takes 20 minutes this way, as opposed to 32 hours the other way!!! Huge difference, thanks for the tip.\nI wrote a full blog entry about it, but here's the important sql:</p>\n\n<pre><code>Alter table MyTable\nAdd MyNewColumn char(10) null default '?';\ngo\n\nupdate MyTable set MyNewColumn='?' where MyPrimaryKey between 0 and 1000000\ngo\nupdate MyTable set MyNewColumn='?' where MyPrimaryKey between 1000000 and 2000000\ngo\nupdate MyTable set MyNewColumn='?' where MyPrimaryKey between 2000000 and 3000000\ngo\n..etc..\n\nAlter table MyTable\nAlter column MyNewColumn char(10) not null;\n</code></pre>\n\n<p>And the blog entry if you're interested:\n<a href=\"http://splinter.com.au/adding-a-column-to-a-massive-sql-server-table\" rel=\"nofollow noreferrer\">http://splinter.com.au/adding-a-column-to-a-massive-sql-server-table</a></p>\n"
},
{
"answer_id": 1151157,
"author": "DHornpout",
"author_id": 21268,
"author_profile": "https://Stackoverflow.com/users/21268",
"pm_score": 7,
"selected": true,
"text": "<p>I ran into this problem for my work also. And my solution is along #2.</p>\n\n<p>Here are my steps (I am using SQL Server 2005):</p>\n\n<p>1) Add the column to the table with a default value:</p>\n\n<pre><code>ALTER TABLE MyTable ADD MyColumn varchar(40) DEFAULT('')\n</code></pre>\n\n<p>2) Add a <code>NOT NULL</code> constraint with the <code>NOCHECK</code> option. The <code>NOCHECK</code> does not enforce on existing values:</p>\n\n<pre><code>ALTER TABLE MyTable WITH NOCHECK\nADD CONSTRAINT MyColumn_NOTNULL CHECK (MyColumn IS NOT NULL)\n</code></pre>\n\n<p>3) Update the values incrementally in table:</p>\n\n<pre><code>GO\nUPDATE TOP(3000) MyTable SET MyColumn = '' WHERE MyColumn IS NULL\nGO 1000\n</code></pre>\n\n<ul>\n<li><p>The update statement will only update maximum 3000 records. This allow to save a chunk of data at the time. I have to use \"MyColumn IS NULL\" because my table does not have a sequence primary key.</p></li>\n<li><p><code>GO 1000</code> will execute the previous statement 1000 times. This will update 3 million records, if you need more just increase this number. It will continue to execute until SQL Server returns 0 records for the UPDATE statement.</p></li>\n</ul>\n"
},
{
"answer_id": 14194691,
"author": "Martin Smith",
"author_id": 73226,
"author_profile": "https://Stackoverflow.com/users/73226",
"pm_score": 2,
"selected": false,
"text": "<p>Just to update this with the latest information.</p>\n\n<p>In SQL Server 2012 this can now be carried out as an online operation in the following circumstances</p>\n\n<ol>\n<li>Enterprise Edition only</li>\n<li>The default must be a runtime constant </li>\n</ol>\n\n<p>For the second requirement examples might be a literal constant or a function such as <code>GETDATE()</code> that evaluates to the same value for all rows. A default of <code>NEWID()</code> would <strong>not</strong> qualify and would still end up updating all rows there and then.</p>\n\n<p>For defaults that qualify SQL Server evaluates them and stores the result as the default value in the column metadata so this is independent of the default constraint which is created (which can even be dropped if no longer required). This is viewable in <code>sys.system_internals_partition_columns</code>. The value doesn't get written out to the rows until next time they happen to get updated.</p>\n\n<p>More details about this here: <a href=\"http://rusanu.com/2011/07/13/online-non-null-with-values-column-add-in-sql-server-11/\" rel=\"nofollow\">online non-null with values column add in sql server 2012</a></p>\n"
},
{
"answer_id": 19141346,
"author": "Tanya Kogan",
"author_id": 2576551,
"author_profile": "https://Stackoverflow.com/users/2576551",
"pm_score": 0,
"selected": false,
"text": "<p>I had a similar problem and I went with modified #3 approach. In my case the database was in SIMPLE recovery mode and the table to which column was supposed to be added was not referenced by any FK constraints. </p>\n\n<p>Instead of creating a new table with the same schema and copying contents of original table, I used <strong>SELECTβ¦INTO</strong> syntax. </p>\n\n<p>According to Microsoft (<a href=\"http://technet.microsoft.com/en-us/library/ms188029(v=sql.105).aspx\" rel=\"nofollow\">http://technet.microsoft.com/en-us/library/ms188029(v=sql.105).aspx</a>)</p>\n\n<blockquote>\n <p>The amount of logging for SELECT...INTO depends on the recovery model\n in effect for the database. Under the simple recovery model or\n bulk-logged recovery model, bulk operations are minimally logged. With\n minimal logging, using the SELECTβ¦ INTO statement can be more\n efficient than creating a table and then populating the table with an\n INSERT statement. For more information, see Operations That Can Be\n Minimally Logged.</p>\n</blockquote>\n\n<p>The sequence of steps :</p>\n\n<p>1.Move data from old table to new while adding new column with default</p>\n\n<pre><code> SELECT table.*, cast (βdefaultβ as nvarchar(256)) new_column\n INTO table_copy \n FROM table\n</code></pre>\n\n<p>2.Drop old table</p>\n\n<pre><code> DROP TABLE table\n</code></pre>\n\n<p>3.Rename newly created table</p>\n\n<pre><code> EXEC sp_rename 'table_copy', βtableβ\n</code></pre>\n\n<p>4.Create necessary constraints and indexes on the new table</p>\n\n<p>In my case the table had more than 100 million rows and this approach completed faster than approach #2 and log space growth was minimal.</p>\n"
},
{
"answer_id": 30443744,
"author": "Kenneth Xu",
"author_id": 111877,
"author_profile": "https://Stackoverflow.com/users/111877",
"pm_score": 1,
"selected": false,
"text": "<p>Admitted that this is an old question. My colleague recently told me that he was able to do it in one single alter table statement on a table with 13.6M rows. It finished within a second in SQL Server 2012. I was able to confirm the same on a table with 8M rows. Something changed in later version of SQL Server?</p>\n\n<pre><code>Alter table mytable add mycolumn char(1) not null default('N');\n</code></pre>\n"
},
{
"answer_id": 40552829,
"author": "hobbsenigma",
"author_id": 861894,
"author_profile": "https://Stackoverflow.com/users/861894",
"pm_score": 0,
"selected": false,
"text": "<p>1) Add the column to the table with a default value:</p>\n\n<pre><code>ALTER TABLE MyTable ADD MyColumn int default 0\n</code></pre>\n\n<p>2) Update the values incrementally in the table (same effect as accepted answer). Adjust the number of records being updated to your environment, to avoid blocking other users/processes.</p>\n\n<pre><code>declare @rowcount int = 1\n\nwhile (@rowcount > 0)\nbegin \n\n UPDATE TOP(10000) MyTable SET MyColumn = 0 WHERE MyColumn IS NULL \n set @rowcount = @@ROWCOUNT\n\nend\n</code></pre>\n\n<p>3) Alter the column definition to require not null. Run the following at a moment when the table is not in use (or schedule a few minutes of downtime). I have successfully used this for tables with millions of records.</p>\n\n<pre><code>ALTER TABLE MyTable ALTER COLUMN MyColumn int NOT NULL\n</code></pre>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/287954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13484/"
] |
To add a NOT NULL Column to a table with many records, a DEFAULT constraint needs to be applied. This constraint causes the entire ALTER TABLE command to take a long time to run if the table is very large. This is because:
Assumptions:
1. The DEFAULT constraint modifies existing records. This means that the db needs to increase the size of each record, which causes it to shift records on full data-pages to other data-pages and that takes time.
2. The DEFAULT update executes as an atomic transaction. This means that the transaction log will need to be grown so that a roll-back can be executed if necessary.
3. The transaction log keeps track of the entire record. Therefore, even though only a single field is modified, the space needed by the log will be based on the size of the entire record multiplied by the # of existing records. This means that adding a column to a table with small records will be faster than adding a column to a table with large records even if the total # of records are the same for both tables.
Possible solutions:
1. Suck it up and wait for the process to complete. Just make sure to set the timeout period to be very long. The problem with this is that it may take hours or days to do depending on the # of records.
2. Add the column but allow NULL. Afterward, run an UPDATE query to set the DEFAULT value for existing rows. Do not do UPDATE \*. Update batches of records at a time or you'll end up with the same problem as solution #1. The problem with this approach is that you end up with a column that allows NULL when you know that this is an unnecessary option. I believe that there are some best practice documents out there that says that you should not have columns that allow NULL unless it's necessary.
3. Create a new table with the same schema. Add the column to that schema. Transfer the data over from the original table. Drop the original table and rename the new table. I'm not certain how this is any better than #1.
Questions:
1. Are my assumptions correct?
2. Are these my only solutions? If so, which one is the best? I f not, what else could I do?
|
I ran into this problem for my work also. And my solution is along #2.
Here are my steps (I am using SQL Server 2005):
1) Add the column to the table with a default value:
```
ALTER TABLE MyTable ADD MyColumn varchar(40) DEFAULT('')
```
2) Add a `NOT NULL` constraint with the `NOCHECK` option. The `NOCHECK` does not enforce on existing values:
```
ALTER TABLE MyTable WITH NOCHECK
ADD CONSTRAINT MyColumn_NOTNULL CHECK (MyColumn IS NOT NULL)
```
3) Update the values incrementally in table:
```
GO
UPDATE TOP(3000) MyTable SET MyColumn = '' WHERE MyColumn IS NULL
GO 1000
```
* The update statement will only update maximum 3000 records. This allow to save a chunk of data at the time. I have to use "MyColumn IS NULL" because my table does not have a sequence primary key.
* `GO 1000` will execute the previous statement 1000 times. This will update 3 million records, if you need more just increase this number. It will continue to execute until SQL Server returns 0 records for the UPDATE statement.
|
287,960 |
<p>I know that jQuery and prototype have a $.each() function for iterating over each element in an array. Does YUI offer any help with this?</p>
|
[
{
"answer_id": 288083,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 3,
"selected": false,
"text": "<p>What keeps you from simply <em>iterating</em> the array?</p>\n\n<pre><code>for(var i=0; i<ary.length; i++)\n // assuming that ary[] contains objects with a DoSometing() method\n ary[i].doSomething(); \n</code></pre>\n"
},
{
"answer_id": 288831,
"author": "Benry",
"author_id": 28408,
"author_profile": "https://Stackoverflow.com/users/28408",
"pm_score": 3,
"selected": false,
"text": "<p>YAHOO.util.Dom has the batch function which has the following signature:</p>\n\n<blockquote>\n <p>Any | Array <strong>batch</strong>( el , method , o , override )</p>\n</blockquote>\n\n<p>Where <em>el</em> is a DOM element or an array of DOM elements, <em>method</em> is a function that that will be passed each element in the array as its first argument, <em>o</em> is an optional second argument, and <em>override</em> is a boolean value that determines if the scope should be window (false) or <em>o</em> (true)</p>\n\n<p>So you could call it like this:</p>\n\n<pre><code>function setDisplay(el, display) {\n el.style.display = display;\n}\n\nYAHOO.util.Dom.batch(document.getElementsByTagName('div'), setDisplay, 'none');\n</code></pre>\n\n<p>Perhaps that would serve your needs.</p>\n"
},
{
"answer_id": 4388875,
"author": "Witek",
"author_id": 176336,
"author_profile": "https://Stackoverflow.com/users/176336",
"pm_score": 2,
"selected": false,
"text": "<p>In YUI3:</p>\n\n<pre><code>Y.Array.each(myArray, function(element) {\n Y.log(element);\n});\n</code></pre>\n\n<p>or even:</p>\n\n<pre><code>Y.Array.each(myArray, function(element, index, array) {\n ...\n});\n</code></pre>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/287960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I know that jQuery and prototype have a $.each() function for iterating over each element in an array. Does YUI offer any help with this?
|
What keeps you from simply *iterating* the array?
```
for(var i=0; i<ary.length; i++)
// assuming that ary[] contains objects with a DoSometing() method
ary[i].doSomething();
```
|
287,965 |
<p>I have two tables:
Client(id,name,...)<br>
Purchase(id,item,date,client_id,...)</p>
<p>They have their respective Model, with their validations. What I need is to create a new client with a new purchase, all into the create method of Client controller. Something like this:</p>
<pre><code>def create
@client = Client.new(params[:client])
respond_to do |format|
if @client.save
# Add purchase
@sell = Purchase.new
@sell.client_id = @client.id
@sell.date = params[:date]
# Fill another fields
if @sell.save
# Do another stuff...
else
format.html { render :action => "new" }
format.xml { render :xml => @client.errors, :status => :unprocessable_entity }
end
flash[:notice] = 'You have a new client!'
format.html { redirect_to(:action => :show, :id => @evento.id) }
format.xml { render :xml => @client, :status => :created, :location => @client }
else
format.html { render :action => "new" }
format.xml { render :xml => @evento.client, :status => :unprocessable_entity }
end
end
end
</code></pre>
<p>In Purchase's model I have:</p>
<pre><code>belongs_to :client
validates_format_of :date, :with => /^20[0-9]{2}[-][0-9]{2}[-][0-9]{2}$/, :message => 'not valid'
validates_presence_of :date
</code></pre>
<p>And there is my problem: how can I validate the date input, through validations into the model, from Client controller? And, how can I rollback the new client created when errors?</p>
<p>Yes, I can do the check as the very first instruction in the method, with a regular expression, but I think it's ugly. I feel like might exist a conventional method for doing this validation or even doing all the stuff in another way (i.e. calling create method for Purchase from Client controller).</p>
<p>Can you put me back in the right way?</p>
<p>Thank you in advance.</p>
|
[
{
"answer_id": 288026,
"author": "mwilliams",
"author_id": 23909,
"author_profile": "https://Stackoverflow.com/users/23909",
"pm_score": 3,
"selected": true,
"text": "<p>Take a look at the following page on <a href=\"http://en.wikibooks.org/wiki/Ruby_on_Rails/ActiveRecord/Associations\" rel=\"nofollow noreferrer\">working with associations</a>.</p>\n\n<p>Rails provides you with a bunch of handy methods on your objects.</p>\n\n<p>Like the following:</p>\n\n<pre><code>Client.purchases.empty?\nClient.purchases.size,\nClient.purchases\nClient.purchases<<(purchase)\nClient.purchases.delete(purchase)\nClient.purchases.find(purchases_id)\nClient.purchases.find_all(conditions)\nClient.purchases.build\nClient.purchases.create\n</code></pre>\n\n<p>When using these methods, you're taking advantage of the validations on each of the models.</p>\n\n<p>Hop into your Rails console and create a new client and try any of the above methods. You'll quickly learn how powerful they are and you'll be on your way in no time.</p>\n\n<p><strong>Edit:</strong> <a href=\"http://guides.rubyonrails.org/association_basics.html\" rel=\"nofollow noreferrer\">Here's a much better guide on Rails associations!</a></p>\n"
},
{
"answer_id": 288100,
"author": "Cameron Price",
"author_id": 35526,
"author_profile": "https://Stackoverflow.com/users/35526",
"pm_score": 1,
"selected": false,
"text": "<p>Depends a little on the situation, but you can use validates_associated to run the validations on associated objects. Then you can create the user (but don't save), create the purchase (but don't save) and try to save the user. If you've done it right the user will fail to save with a validation error on the associated object.</p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/287965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36599/"
] |
I have two tables:
Client(id,name,...)
Purchase(id,item,date,client\_id,...)
They have their respective Model, with their validations. What I need is to create a new client with a new purchase, all into the create method of Client controller. Something like this:
```
def create
@client = Client.new(params[:client])
respond_to do |format|
if @client.save
# Add purchase
@sell = Purchase.new
@sell.client_id = @client.id
@sell.date = params[:date]
# Fill another fields
if @sell.save
# Do another stuff...
else
format.html { render :action => "new" }
format.xml { render :xml => @client.errors, :status => :unprocessable_entity }
end
flash[:notice] = 'You have a new client!'
format.html { redirect_to(:action => :show, :id => @evento.id) }
format.xml { render :xml => @client, :status => :created, :location => @client }
else
format.html { render :action => "new" }
format.xml { render :xml => @evento.client, :status => :unprocessable_entity }
end
end
end
```
In Purchase's model I have:
```
belongs_to :client
validates_format_of :date, :with => /^20[0-9]{2}[-][0-9]{2}[-][0-9]{2}$/, :message => 'not valid'
validates_presence_of :date
```
And there is my problem: how can I validate the date input, through validations into the model, from Client controller? And, how can I rollback the new client created when errors?
Yes, I can do the check as the very first instruction in the method, with a regular expression, but I think it's ugly. I feel like might exist a conventional method for doing this validation or even doing all the stuff in another way (i.e. calling create method for Purchase from Client controller).
Can you put me back in the right way?
Thank you in advance.
|
Take a look at the following page on [working with associations](http://en.wikibooks.org/wiki/Ruby_on_Rails/ActiveRecord/Associations).
Rails provides you with a bunch of handy methods on your objects.
Like the following:
```
Client.purchases.empty?
Client.purchases.size,
Client.purchases
Client.purchases<<(purchase)
Client.purchases.delete(purchase)
Client.purchases.find(purchases_id)
Client.purchases.find_all(conditions)
Client.purchases.build
Client.purchases.create
```
When using these methods, you're taking advantage of the validations on each of the models.
Hop into your Rails console and create a new client and try any of the above methods. You'll quickly learn how powerful they are and you'll be on your way in no time.
**Edit:** [Here's a much better guide on Rails associations!](http://guides.rubyonrails.org/association_basics.html)
|
287,976 |
<p>I'd like to make an (MS)SQL query that returns something like this:</p>
<pre><code>Col1 Col2 Col3
---- --------------------- ------
AAA 18.92 18.92
BBB 20.00 40.00
AAA 30.84 30.84
BBB 06.00 12.00
AAA 30.84 30.84
AAA 46.79 46.79
AAA 86.40 86.40
</code></pre>
<p>where Col3 is equal to Col2 when Col1 = AAA and Col3 is twice Col2 when Col1 = BBB.
Can someone point me in the rigth direction please?</p>
|
[
{
"answer_id": 287982,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 6,
"selected": true,
"text": "<p>You didn't mention what kind of database you're using. Here's something that will work in SQL Server:</p>\n\n<pre><code>SELECT Col1, Col2, \n CASE WHEN Col1='AAA' THEN Col2 WHEN Col1='BBB' THEN Col2*2 ELSE NULL END AS Col3\nFROM ...\n</code></pre>\n"
},
{
"answer_id": 287985,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 1,
"selected": false,
"text": "<pre><code>select *\nfrom yourtable\nwhere (Col3 = col2 AND Col1 = 'AAA') OR\n (Col3 = (2*Col2) AND Col1='BBB')\n</code></pre>\n"
},
{
"answer_id": 287989,
"author": "George Mastros",
"author_id": 1408129,
"author_profile": "https://Stackoverflow.com/users/1408129",
"pm_score": 2,
"selected": false,
"text": "<p>It depends on your flavor of SQL. Case/When works with SQL Server (and possibly others).</p>\n\n<pre><code>Select Col1, Col2, \n Case When Col1 = 'AAA' Then Col2 Else Col2 * 2 End As Col3\nFrom YourTable\n</code></pre>\n"
},
{
"answer_id": 6329839,
"author": "Pankaj Awasthi",
"author_id": 522781,
"author_profile": "https://Stackoverflow.com/users/522781",
"pm_score": 0,
"selected": false,
"text": "<p>Sometimes the values are <code>null</code>, so they can be handled like this:</p>\n\n<pre><code>select Address1 + (case when Address2='' then '' else ', '+Address2 end) + \n (case when Address3='' then '' else ', '+ Address3 end) as FullAddress from users\n</code></pre>\n"
},
{
"answer_id": 9335321,
"author": "Draugnar",
"author_id": 1217143,
"author_profile": "https://Stackoverflow.com/users/1217143",
"pm_score": 3,
"selected": false,
"text": "<p>You can also use the <code>ISNULL</code> or <code>COALESCE</code> functions like thus, should the values be null:</p>\n\n<pre><code>SELECT ISNULL(Col1, 'AAA') AS Col1, \n ISNULL(Col2, 0) AS Col2,\n CASE WHEN ISNULL(Col1, 'AAA') = 'BBB' THEN ISNULL(Col2, 0) * 2 \n ELSE ISNULL(Col2) \n END AS Col3\nFROM Tablename\n</code></pre>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/287976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34632/"
] |
I'd like to make an (MS)SQL query that returns something like this:
```
Col1 Col2 Col3
---- --------------------- ------
AAA 18.92 18.92
BBB 20.00 40.00
AAA 30.84 30.84
BBB 06.00 12.00
AAA 30.84 30.84
AAA 46.79 46.79
AAA 86.40 86.40
```
where Col3 is equal to Col2 when Col1 = AAA and Col3 is twice Col2 when Col1 = BBB.
Can someone point me in the rigth direction please?
|
You didn't mention what kind of database you're using. Here's something that will work in SQL Server:
```
SELECT Col1, Col2,
CASE WHEN Col1='AAA' THEN Col2 WHEN Col1='BBB' THEN Col2*2 ELSE NULL END AS Col3
FROM ...
```
|
287,986 |
<p>Ruby on Rails controllers will automatically convert parameters to an array if they have a specific format, like so:</p>
<pre><code>http://foo.com?x[]=1&x[]=5&x[]=bar
</code></pre>
<p>This would get converted into the following array:</p>
<pre><code>['1','5','bar']
</code></pre>
<p>Is there any way I can do this with an ActionScript 3 HTTPService object, by using the request parameter? For example, It would be nice to do something like the following:</p>
<pre><code>var s:HTTPService = new HTTPService();
s.request['x[]'] = 1;
s.request['x[]'] = 5;
s.request['x[]'] = 'bar';
</code></pre>
<p>However, that will simply overwrite each value, resulting in only the last value being sent. Anyone have a better idea? I know I could just append stuff to the query string, but I'd like to do it in the POST body.</p>
|
[
{
"answer_id": 288004,
"author": "mmattax",
"author_id": 1638,
"author_profile": "https://Stackoverflow.com/users/1638",
"pm_score": 1,
"selected": false,
"text": "<p>I usually do something like this...</p>\n\n<pre>\n<code>\nvar s:HTTPService = new HTTPService();\ns.url = \"http://foo.com\";\ns.method = \"post\";\n// add listeners...\ns.addEventListenser(ResultEvent.RESULT,function(event:ResultEvent){\n\n mx.controls.Alert.show(event.result.toString());\n});\n\n// send the data...\ns.send({\n a: 1,\n b: 5,\n c: \"bar\"\n});\n\n</code>\n</pre>\n\n<p>which would result in the HTTP Get / POST of:</p>\n\n<p><a href=\"http://foo.com?a=1&b=5&c=bar\" rel=\"nofollow noreferrer\">http://foo.com?a=1&b=5&c=bar</a></p>\n\n<p>You could also just create an associative array and pass it to the HTTPService send method, that would be something like:</p>\n\n<pre>\n<code>\n\nvar postdata:Object = {};\n\npostdata[\"a\"] = 1;\npostdata[\"b\"] = 5;\npostdata[\"c\"] = \"bar\";\n\n// s is the HTTPService from above...\ns.send(postdata);\n\n</code>\n</pre>\n"
},
{
"answer_id": 410945,
"author": "bartv",
"author_id": 51371,
"author_profile": "https://Stackoverflow.com/users/51371",
"pm_score": 3,
"selected": true,
"text": "<p>I was working on this same problem as well. Fortunatly, Flex supports this out of the box.</p>\n\n<p>Just use an Array for the field value:</p>\n\n<pre><code>var service:HTTPService = new HTTPService();\nservice.useProxy = true;\nservice.destination = \"myservicet\";\nservice.resultFormat = HTTPService.RESULT_FORMAT_XML;\n\nvar fields:Array = [\"categories\", \"organisation\"];\nvar params:Object = new Object();\nparams.q = \"stackoverflow\";\nparams.rows = 0;\nparams.facet = \"true\";\nparams[\"facet.field\"] = fields;\nservice.send(params);\n</code></pre>\n\n<p>The HTTPService will convert this t0 the url parameters:</p>\n\n<pre>facet=true&q=stackoverflow&facet%2Efield=categories&facet%2Efield=organisation&rows=0</pre>\n\n<p>Hope this helps!</p>\n\n<p>Added for more clarity. When there is only 1 argument in the array, do not pass the fields as an array. For some reason, flex will not send this to the http service</p>\n"
},
{
"answer_id": 1392977,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You mentioned that All POST parameters must have the same name.\nElements that have the same name will overwrite each other in an associative array.\nHowever, I have dealt with calendar cells before, and all 31 cells belong to the Date category.</p>\n\n<p>What I did was:</p>\n\n<pre><code>var params:Object = new Object;\nfor (var i:uint=0; i<31; i++){\n params[\"Date\"+(jj.toString())] = date[i];\n}\n\nHTTPService....etc.\nHTTPService.send(params);\n</code></pre>\n\n<p>So, on the POST receiving side, it would be interpreted as <code>Date0...Date31</code>.</p>\n\n<p>Don't know if this was what you wanted, and the post was so long ago.</p>\n"
},
{
"answer_id": 1392993,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Come to think about it.\nWhy don't you do an array push of all of the elements under the same index name?\nHowever, this means you are sending an array to the receiving side.</p>\n\n<p>If you are POST-ing this, how will this be URL-referenced?</p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/287986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19964/"
] |
Ruby on Rails controllers will automatically convert parameters to an array if they have a specific format, like so:
```
http://foo.com?x[]=1&x[]=5&x[]=bar
```
This would get converted into the following array:
```
['1','5','bar']
```
Is there any way I can do this with an ActionScript 3 HTTPService object, by using the request parameter? For example, It would be nice to do something like the following:
```
var s:HTTPService = new HTTPService();
s.request['x[]'] = 1;
s.request['x[]'] = 5;
s.request['x[]'] = 'bar';
```
However, that will simply overwrite each value, resulting in only the last value being sent. Anyone have a better idea? I know I could just append stuff to the query string, but I'd like to do it in the POST body.
|
I was working on this same problem as well. Fortunatly, Flex supports this out of the box.
Just use an Array for the field value:
```
var service:HTTPService = new HTTPService();
service.useProxy = true;
service.destination = "myservicet";
service.resultFormat = HTTPService.RESULT_FORMAT_XML;
var fields:Array = ["categories", "organisation"];
var params:Object = new Object();
params.q = "stackoverflow";
params.rows = 0;
params.facet = "true";
params["facet.field"] = fields;
service.send(params);
```
The HTTPService will convert this t0 the url parameters:
```
facet=true&q=stackoverflow&facet%2Efield=categories&facet%2Efield=organisation&rows=0
```
Hope this helps!
Added for more clarity. When there is only 1 argument in the array, do not pass the fields as an array. For some reason, flex will not send this to the http service
|
287,991 |
<p>How can I match (PCRE) everything inbetween two tags?</p>
<p>I tried something like this:</p>
<blockquote>
<p><!--\s*LoginStart\s*-->(.*)<!--\s*LoginEnd\s*--></p>
</blockquote>
<p>But it didn't work out too well for me..</p>
<p>I'm kind of new to regular expressions, so I was hoping if someone would be kind enough to explain to me how I would accomplish this, if its even possible with regular expressions.</p>
<p>Thanks</p>
|
[
{
"answer_id": 288006,
"author": "John Fiala",
"author_id": 9143,
"author_profile": "https://Stackoverflow.com/users/9143",
"pm_score": 1,
"selected": false,
"text": "<p>PHP and regex? Here's some suggestions:</p>\n\n<pre><code>'/<!--\\s*LoginStart\\s*-->(.*)<!--\\s*LoginEnd\\s*-->/Us'\n</code></pre>\n\n<p>Might be better - the <code>U</code> capitalized makes the regex non-greedy, which means it'll stop at the first <code><!--</code> that may work. But the important one is the <code>s</code>, which tells the regex to match a newline with the <code>.</code> character.</p>\n\n<p>Depending on how certain you are on the capitalization, adding an <code>i</code> at the end will make the regex search case-insensitive.</p>\n"
},
{
"answer_id": 288015,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 5,
"selected": true,
"text": "<pre><code>$string = '<!-- LoginStart --><div id=\"stuff\">text</div><!-- LoginEnds -->';\n$regex = '#<!--\\s*LoginStart\\s*-->(.*?)<!--\\s*LoginEnds\\s*-->#s';\n\npreg_match($regex, $string, $matches);\n\nprint_r($matches); // $matches[1] = <div id=\"stuff\">text</div>\n</code></pre>\n\n<p>explanations:</p>\n\n<pre><code>(.*?) = non greedy match (match the first <!-- LoginEnds --> it finds\n s = modifier in $regex (end of the variable) allows multiline matches\n such as '<!-- LoginStart -->stuff\n more stuff\n <!-- LoginEnds -->'\n</code></pre>\n"
},
{
"answer_id": 4214104,
"author": "Gnanz",
"author_id": 512008,
"author_profile": "https://Stackoverflow.com/users/512008",
"pm_score": 0,
"selected": false,
"text": "<p>i have tried Owen's answer but its fails for the conditions like</p>\n\n<p><code><!-- LoginStart --><div id=\"stuff\">text</div><!-- LoginEnds --><b>\"DONT MIND THIS\"</b><!-- LoginStart --><div id=\"stuff\">text</div><!-- LoginEnds --></code></p>\n\n<p>This includes the line \"DONT MIND THIS\" also, that is it covers all the contents within first\n<!-- LoginStart --> and last <!-- LoginEnds --> tag</p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/287991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37439/"
] |
How can I match (PCRE) everything inbetween two tags?
I tried something like this:
>
> <!--\s\*LoginStart\s\*-->(.\*)<!--\s\*LoginEnd\s\*-->
>
>
>
But it didn't work out too well for me..
I'm kind of new to regular expressions, so I was hoping if someone would be kind enough to explain to me how I would accomplish this, if its even possible with regular expressions.
Thanks
|
```
$string = '<!-- LoginStart --><div id="stuff">text</div><!-- LoginEnds -->';
$regex = '#<!--\s*LoginStart\s*-->(.*?)<!--\s*LoginEnds\s*-->#s';
preg_match($regex, $string, $matches);
print_r($matches); // $matches[1] = <div id="stuff">text</div>
```
explanations:
```
(.*?) = non greedy match (match the first <!-- LoginEnds --> it finds
s = modifier in $regex (end of the variable) allows multiline matches
such as '<!-- LoginStart -->stuff
more stuff
<!-- LoginEnds -->'
```
|
288,007 |
<pre><code>SELECT DISTINCT
'LRS-TECH 1' || rpad(code,7) || rpad('APPTYPE',30) ||
rpad(licensing_no,30) || rpad(' ',300) AS RECORD
FROM APPS
WHERE L_code = '1000' AND licensing_no IS NOT NULL
</code></pre>
<p>This seems to be the primary culprit in why I cannot export these records to a textfile in my development environment. Is there any way I can get this query to run quicker. It returns roughly 2000+ lines of text. </p>
|
[
{
"answer_id": 288025,
"author": "digitalsanctum",
"author_id": 22436,
"author_profile": "https://Stackoverflow.com/users/22436",
"pm_score": 0,
"selected": false,
"text": "<p>If you don't already have indexes on L_code and licensing_no columns, I would try that.</p>\n"
},
{
"answer_id": 288072,
"author": "dkretz",
"author_id": 31641,
"author_profile": "https://Stackoverflow.com/users/31641",
"pm_score": 0,
"selected": false,
"text": "<p>If there are many records with L_code = '1000' and the only additional test is for NOT NULL, you probably have a cardinality problem. Indexes have a hard time selecting on NULL or not.</p>\n\n<p>The number of rows returned is unimportant - it's the number of rows examined that's the question.</p>\n\n<p>What indexes are there?</p>\n"
},
{
"answer_id": 288073,
"author": "JK.",
"author_id": 16253,
"author_profile": "https://Stackoverflow.com/users/16253",
"pm_score": -1,
"selected": false,
"text": "<p>Get rid of the DISTINCT.</p>\n"
},
{
"answer_id": 288117,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Hmmm... getting rid of DISTINCT may help considering that code is the PRIMARY KEY. I don't think it is what is causing the major processing problems. If believe the RPAD, etc. is causing most of the query delay.</p>\n\n<p>The indexes mainly ASCEND the CODE field. That's the only relevant indexes on the table.</p>\n"
},
{
"answer_id": 288303,
"author": "James",
"author_id": 16282,
"author_profile": "https://Stackoverflow.com/users/16282",
"pm_score": 0,
"selected": false,
"text": "<p>You could prebuild the RECORD derived value in a secondary table, view or column using a trigger and query that instead of building it on the fly if the table is frequently queried. </p>\n\n<p>It might help to know the size of the table. If you've got a large column in there, or a lot of records, it could be something IO or cache related.</p>\n"
},
{
"answer_id": 288360,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I'm sorry to everyone looking at this SQL, but this is a mindboggling server problem or something. The scenario seems to have drawn itself out,and I believe it's a data availability problem as to where the DB resides, but somebody may be able to give me some insight.</p>\n\n<p>On my Localhost, I run the code, works instantaneously. I export the data it gives me from a datatable to a textfile in less than a second... done.</p>\n\n<p>On our development environment, the same page is in old ASP. Half our site is in classic ASP as we convert to .NET. The problem seems to be that on the DEV site, the classic ASP page works perfectly, quickly and done in less than a second. When I uploaded the newly converted ASPX file, it hung for about 30 seconds on that query.</p>\n\n<p>On Localhost, the old classic ASP hangs for about 30 seconds.</p>\n\n<p>So, I have a vice versa problem here in that the classic ASP doesn't hang on the DEV site, but on my machine while my own ASPX page hangs on the DEV site, but NOT on my machine. The difference is that I believe the data is being pulled in my own code on the DEV site, while the ASP page is pulling the data from code that resides on an old DEV site server that ports the results to the DEV site. So, technically, the code isn't being run on the same server. The classic ASP code is on our old site server.</p>\n\n<p>I'm assuming there is some sort of speed issue or server issue between the two sites.</p>\n"
},
{
"answer_id": 289075,
"author": "David Aldridge",
"author_id": 6742,
"author_profile": "https://Stackoverflow.com/users/6742",
"pm_score": 2,
"selected": false,
"text": "<p>You cannot diagnose this problem unless you know how the query is being optimised.</p>\n\n<p>Try this:</p>\n\n<pre><code>explain plan for SELECT DISTINCT \n'LRS-TECH 1' || rpad(code,7) || rpad('APPTYPE',30) || \n rpad(licensing_no,30) || rpad(' ',300) AS RECORD \nFROM APPS\nWHERE L_code = '1000' AND licensing_no IS NOT NULL\n/\n\nselect * from table(dbms_xplan.display)\n/\n</code></pre>\n\n<p>Now, try this also ... it will help you detect a statistics problem:</p>\n\n<pre><code>explain plan for SELECT /*+ dynamic_sampling(4) */ DISTINCT \n'LRS-TECH 1' || rpad(code,7) || rpad('APPTYPE',30) || \n rpad(licensing_no,30) || rpad(' ',300) AS RECORD \nFROM APPS\nWHERE L_code = '1000' AND licensing_no IS NOT NULL\n/\n\nselect * from table(dbms_xplan.display)\n/\n</code></pre>\n\n<p>Please update your original post with the results of those.</p>\n"
},
{
"answer_id": 289240,
"author": "Leigh Riffel",
"author_id": 27010,
"author_profile": "https://Stackoverflow.com/users/27010",
"pm_score": 0,
"selected": false,
"text": "<p>As most of the answers here have indicated, your question sounds like an optimization question. Your later answer changes the nature of the question significantly. I suggest posting it as a new question or modifying the original question to ask what you really want to know.</p>\n\n<p>I can't help you on the ASP/ASPX issue, but if this were an optimization question I'd suggest creating a function based index for a new WHERE clause as follows:</p>\n\n<pre><code>SELECT DISTINCT \n 'LRS-TECH 1' || rpad(code,7) || rpad('APPTYPE',30) || \n rpad(licensing_no,30) || rpad(' ',300) AS RECORD \nFROM APPS\nWHERE DECODE(L_code,'1000',licensing_no,NULL) IS NOT NULL;\n</code></pre>\n\n<p>A function based index on DECODE(L_code,'1000',licensing_no,NULL) would include all the records you want to return. If you needed even more speed you could create a materialized view on the results of the query, but that would be more of a last ditch effort.</p>\n"
},
{
"answer_id": 289713,
"author": "hamishmcn",
"author_id": 3590,
"author_profile": "https://Stackoverflow.com/users/3590",
"pm_score": 0,
"selected": false,
"text": "<p>I wonder if it is because the oracle is using a different index (or not at all) for the query from the aspx page.<br>\nI would suggest updating the statistics on the table to see if that makes any difference.<br>\nSee <a href=\"https://stackoverflow.com/questions/120504/optimising-a-select-query-that-runs-slow-on-oracle-which-runs-quickly-on-sql-se#121161\">this question</a> for how to do it (and the comments that 'calculate statistics' is obsolete, replaced by a package instead)</p>\n"
},
{
"answer_id": 296871,
"author": "user34850",
"author_id": 34850,
"author_profile": "https://Stackoverflow.com/users/34850",
"pm_score": 2,
"selected": false,
"text": "<p>The solution is simple.</p>\n\n<p>Create an index on (code, licensing_no) and an index on (l_code, licensing_no) to fetch records faster. Do the 'beautification' piece later in the application or simply in external wrapper like this:</p>\n\n<pre><code>SELECT 'LRS-TECH 1'\n || RPAD (code, 7)\n || RPAD ('APPTYPE', 30)\n || RPAD (licensing_no, 30)\n || RPAD (' ', 300) AS RECORD\n FROM (SELECT DISTINCT code, licensing_no\n FROM apps\n WHERE l_code = '1000' AND licensing_no IS NOT NULL)\n</code></pre>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
```
SELECT DISTINCT
'LRS-TECH 1' || rpad(code,7) || rpad('APPTYPE',30) ||
rpad(licensing_no,30) || rpad(' ',300) AS RECORD
FROM APPS
WHERE L_code = '1000' AND licensing_no IS NOT NULL
```
This seems to be the primary culprit in why I cannot export these records to a textfile in my development environment. Is there any way I can get this query to run quicker. It returns roughly 2000+ lines of text.
|
You cannot diagnose this problem unless you know how the query is being optimised.
Try this:
```
explain plan for SELECT DISTINCT
'LRS-TECH 1' || rpad(code,7) || rpad('APPTYPE',30) ||
rpad(licensing_no,30) || rpad(' ',300) AS RECORD
FROM APPS
WHERE L_code = '1000' AND licensing_no IS NOT NULL
/
select * from table(dbms_xplan.display)
/
```
Now, try this also ... it will help you detect a statistics problem:
```
explain plan for SELECT /*+ dynamic_sampling(4) */ DISTINCT
'LRS-TECH 1' || rpad(code,7) || rpad('APPTYPE',30) ||
rpad(licensing_no,30) || rpad(' ',300) AS RECORD
FROM APPS
WHERE L_code = '1000' AND licensing_no IS NOT NULL
/
select * from table(dbms_xplan.display)
/
```
Please update your original post with the results of those.
|
288,011 |
<p>Joel often talks about using MS Excel for lightweight project management, but I'm curious about actual implementations of this idea. I've seen some templates that seem to clone MS Project via macros, which would be overkill for a lightweight project. Anyone have any useful templates?</p>
|
[
{
"answer_id": 288028,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 2,
"selected": false,
"text": "<p>You have some pretty advance template with <a href=\"http://pipetalk.stores.yahoo.net/frdopiexgasc.html\" rel=\"nofollow noreferrer\">Pipetalk Scheduler</a></p>\n\n<p><a href=\"http://ep.yimg.com/ip/I/pipetalk_2055_216386\" rel=\"nofollow noreferrer\">alt text http://ep.yimg.com/ip/I/pipetalk_2055_216386</a></p>\n\n<p>However, since it seems to be a <em>little too much</em>, I just transfered that to the <strong><a href=\"https://stackoverflow.com/questions/238177#289284\">worst UI thread</a></strong> ;)</p>\n"
},
{
"answer_id": 288060,
"author": "kenny",
"author_id": 3225,
"author_profile": "https://Stackoverflow.com/users/3225",
"pm_score": 1,
"selected": false,
"text": "<p>It's not excel, but I saw <a href=\"https://scrumy.com/\" rel=\"nofollow noreferrer\">scrumy</a> and liked it's <a href=\"https://scrumy.com/demo\" rel=\"nofollow noreferrer\">demo</a>. For a small project recently, I just generated a project plan using 'Cross Functional Flowchart' under Business Process with some flow/process stuff in Visio. </p>\n"
},
{
"answer_id": 288113,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 4,
"selected": true,
"text": "<p>try</p>\n\n<pre> feature task estimated hours actual hours current %\n ---------- ---------- --------------- ------------ ---------</pre>\n\n<p>if estimated hours times current % is greater than actual hours, you are behind schedule</p>\n\n<p>update the actual hours and current % on a daily basis</p>\n\n<p>see also <a href=\"http://www.joelonsoftware.com/articles/fog0000000245.html\" rel=\"noreferrer\">joel's old excel template</a></p>\n"
},
{
"answer_id": 288160,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Maybe a bit off-topic, but you might want to consider testing <strong><a href=\"http://docs.google.com\" rel=\"nofollow noreferrer\">Google Docs</a></strong>. There is a Gantt chart widget provided by <strong>Viewpath</strong> in the <em>\"Insert->Widget...\"</em> menu option.</p>\n"
},
{
"answer_id": 289280,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 0,
"selected": false,
"text": "<p>Much <strong>simpler</strong>: some <a href=\"http://www.hyperthot.com/pm_excel_gantt.htm\" rel=\"nofollow noreferrer\"><strong>Gantt graph</strong> in Excel</a> ,as <strong><a href=\"http://fr.youtube.com/watch?v=CW_wGSFavTc\" rel=\"nofollow noreferrer\">illustrated here</a></strong>.</p>\n"
},
{
"answer_id": 289306,
"author": "Kurt",
"author_id": 31056,
"author_profile": "https://Stackoverflow.com/users/31056",
"pm_score": 1,
"selected": false,
"text": "<p>Edward Tufte - aka \"the man\" when it comes to data representation has done a lot of work on Gantt charts (<a href=\"http://en.wikipedia.org/wiki/Gantt_chart\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Gantt_chart</a>) has some good information on this topic, but basically it boils down to using Excel as a Gantt chart creator, the advantage being that it's simple and won't get in your way much:</p>\n\n<p><a href=\"http://www.edwardtufte.com/bboard/q-and-a-fetch-msg?msg_id=000076\" rel=\"nofollow noreferrer\">http://www.edwardtufte.com/bboard/q-and-a-fetch-msg?msg_id=000076</a></p>\n"
},
{
"answer_id": 290182,
"author": "philant",
"author_id": 18804,
"author_profile": "https://Stackoverflow.com/users/18804",
"pm_score": 1,
"selected": false,
"text": "<p>You could consider using a <a href=\"http://agilesoftwaredevelopment.com/scrum/simple-sprint-backlog\" rel=\"nofollow noreferrer\">Sprint Backlog</a>. You estimate the time for every tasks of your project and your update the estimated <strong>remaining</strong> time every day or so. Then you have a burndown chart that shows the remaining effort to complete the project. </p>\n\n<p>If your project is too large for a daily tracking, you could either do the tracking every week, or manage a <a href=\"http://agilesoftwaredevelopment.com/scrum/simple-product-backlog\" rel=\"nofollow noreferrer\">product backlog</a> of the things to be done in your project as a coarse-grained level of planning and then choose the most prioritized one for the finer-grained planning level. </p>\n\n<p>You might want to look at Scrum(1) or any other <a href=\"http://en.wikipedia.org/wiki/Agile_software_development\" rel=\"nofollow noreferrer\">agile methods</a> for lightweight development methods for further details. </p>\n\n<p>(1) <a href=\"http://en.wikipedia.org/wiki/Scrum_(development)\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Scrum_(development)</a></p>\n"
},
{
"answer_id": 361334,
"author": "tecmo",
"author_id": 28955,
"author_profile": "https://Stackoverflow.com/users/28955",
"pm_score": 0,
"selected": false,
"text": "<p>The columns I use are</p>\n\n<p>1) Task Name\n2) Budget Hours \n3) Total Hours\n4) Remaining Hours</p>\n\n<p>The Key is column (4). Rather than getting the person to estimate a percent complete; get them to re-estimate from this point forward. Its a subtle change but the mindset is much different. Otherwise you almost always end up stuck at 90% complete.</p>\n"
},
{
"answer_id": 1033690,
"author": "gareth_bowles",
"author_id": 10715,
"author_profile": "https://Stackoverflow.com/users/10715",
"pm_score": 1,
"selected": false,
"text": "<p>If you like using spreadsheets and not getting involved with too many fancy tools, have a look at <a href=\"http://www.onepageprojectmanager.com/\" rel=\"nofollow noreferrer\">The One Page Project Manager</a> - it's exactly as described, a nice, lightweight way to keep track of all your important project info on a single worksheet.</p>\n"
},
{
"answer_id": 1966726,
"author": "Apezz",
"author_id": 239262,
"author_profile": "https://Stackoverflow.com/users/239262",
"pm_score": -1,
"selected": false,
"text": "<p>I use EasyProjectPlan which is an <strong>Excel Project Plan</strong> that syncs with <strong>Outlook</strong> and <strong>MSProject</strong>.</p>\n\n<p><strong><a href=\"http://www.easyprojectplan.com\" rel=\"nofollow noreferrer\">www.EasyProjectPlan.com</a></strong></p>\n\n<p>I use the Outlook and Calendar sync features to distribute and collect task information to my team members.</p>\n\n<p>I distribute the EPP Excel file to all team members either by email or I post it in a shared folder.</p>\n\n<p>My team members can edit the EPP excel file and send the changes back to me.</p>\n\n<p>Most of the companies I work for have no PM task management system so EPP allows me to walk onto any project and immediately distribute and collect task information to all team members. Considering that most companies use Excel and Outlook, there is nothing to install on any computer.</p>\n\n<p>In my experience, team members prefer to view task information in Excel and Outlook.</p>\n"
},
{
"answer_id": 4745114,
"author": "You knows who",
"author_id": 582687,
"author_profile": "https://Stackoverflow.com/users/582687",
"pm_score": 0,
"selected": false,
"text": "<p>There are a lot of useful template in <a href=\"http://www.exinfm.com/free_spreadsheets.html\" rel=\"nofollow\">this</a> page. Also, you can read more in our <a href=\"http://xprojectmanagement.com\" rel=\"nofollow\">project management software</a> blog.</p>\n\n<p>Hope it helps :)</p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/327/"
] |
Joel often talks about using MS Excel for lightweight project management, but I'm curious about actual implementations of this idea. I've seen some templates that seem to clone MS Project via macros, which would be overkill for a lightweight project. Anyone have any useful templates?
|
try
```
feature task estimated hours actual hours current %
---------- ---------- --------------- ------------ ---------
```
if estimated hours times current % is greater than actual hours, you are behind schedule
update the actual hours and current % on a daily basis
see also [joel's old excel template](http://www.joelonsoftware.com/articles/fog0000000245.html)
|
288,020 |
<p>I found one source which successfully overrode <code>Time.strftime</code> like this:</p>
<pre><code>class Time
alias :old_strftime :strftime
def strftime
#do something
old_strftime
end
end
</code></pre>
<p>The trouble is, <code>strftime</code> is an instance method. I need to override <code>Time.now</code> - a class method - in such away that any caller gets my new method, while the new method still calls the original <code>.now</code> method. I've looked at <code>alias_method</code> and have met with no success.</p>
|
[
{
"answer_id": 288077,
"author": "Austin Ziegler",
"author_id": 36378,
"author_profile": "https://Stackoverflow.com/users/36378",
"pm_score": 2,
"selected": false,
"text": "<p>Class methods are just methods. I highly recommend against this, but you have two equivalent choices:</p>\n\n<pre><code>class Time\n class << self\n alias_method :old_time_now, :now\n\n def now\n my_now = old_time_now\n # new code\n my_now\n end\n end\nend\n\nclass << Time\n alias_method :old_time_now, :now\n\n def now\n my_now = old_time_now\n # new code\n my_now\n end\nend\n</code></pre>\n"
},
{
"answer_id": 288088,
"author": "Cameron Price",
"author_id": 35526,
"author_profile": "https://Stackoverflow.com/users/35526",
"pm_score": 5,
"selected": true,
"text": "<p>This is kinda hard to get your head around sometimes, but you need to open the \"eigenclass\" which is the singleton associated with a specific class object. the syntax for this is class << self do...end. </p>\n\n<pre><code>class Time\n alias :old_strftime :strftime\n\n def strftime\n puts \"got here\"\n old_strftime\n end\nend\n\nclass Time\n class << self\n alias :old_now :now\n def now\n puts \"got here too\"\n old_now\n end\n end\nend\n\nt = Time.now\nputs t.strftime\n</code></pre>\n"
},
{
"answer_id": 288103,
"author": "Avdi",
"author_id": 20487,
"author_profile": "https://Stackoverflow.com/users/20487",
"pm_score": 1,
"selected": false,
"text": "<p>If the you need to override it for testing purposes (the reason I normally want to override Time.now), Ruby mocking/stubbing frameworks will do this for you easily. For instance, with RSpec (which uses flexmock):</p>\n\n<pre><code>Time.stub!(:now).and_return(Time.mktime(1970,1,1))\n</code></pre>\n\n<p>By the way, I highly recommend avoiding the need to stub out Time.now by giving your classes an overrideable clock:</p>\n\n<pre><code>class Foo\n def initialize(clock=Time)\n @clock = clock\n end\n\n def do_something\n time = @clock.now\n # ...\n end\nend\n</code></pre>\n"
},
{
"answer_id": 3393550,
"author": "Federico Ramallo",
"author_id": 237975,
"author_profile": "https://Stackoverflow.com/users/237975",
"pm_score": 0,
"selected": false,
"text": "<p>I've been trying to figure out how to override an instance method using modules.</p>\n\n<pre><code>module Mo\n def self.included(base)\n base.instance_eval do\n alias :old_time_now :now\n def now\n my_now = old_time_now\n puts 'overrided now'\n # new code\n my_now\n end\n end\n end\nend\nTime.send(:include, Mo) unless Time.include?(Mo)\n\n> Time.now\noverrided now\n=> Mon Aug 02 23:12:31 -0500 2010\n</code></pre>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30997/"
] |
I found one source which successfully overrode `Time.strftime` like this:
```
class Time
alias :old_strftime :strftime
def strftime
#do something
old_strftime
end
end
```
The trouble is, `strftime` is an instance method. I need to override `Time.now` - a class method - in such away that any caller gets my new method, while the new method still calls the original `.now` method. I've looked at `alias_method` and have met with no success.
|
This is kinda hard to get your head around sometimes, but you need to open the "eigenclass" which is the singleton associated with a specific class object. the syntax for this is class << self do...end.
```
class Time
alias :old_strftime :strftime
def strftime
puts "got here"
old_strftime
end
end
class Time
class << self
alias :old_now :now
def now
puts "got here too"
old_now
end
end
end
t = Time.now
puts t.strftime
```
|
288,027 |
<p>In Object Oriented Paradigm, I would create an object/conceptual model before I start implementing it using OO language.</p>
<p>Is there anything parallel to object model in functional programming. Is it called functional model? or we create the same conceptual model in both the paradigm before implementing it in one of the language.. </p>
<p>Are there articles/books where I can read about functional model in case it exist? </p>
<p>or to put it in different way... even if we are using functional programming language, would we start with object model?</p>
|
[
{
"answer_id": 288079,
"author": "Rohit",
"author_id": 16071,
"author_profile": "https://Stackoverflow.com/users/16071",
"pm_score": 0,
"selected": false,
"text": "<p>A flowchart and/or process model/diagram can be used as a functional model for non OO programs. But it still doesn't give the sense of boundaries similar to that of the OO model.</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Functional_model\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Functional_model</a></p>\n"
},
{
"answer_id": 333145,
"author": "Daishiman",
"author_id": 42345,
"author_profile": "https://Stackoverflow.com/users/42345",
"pm_score": 3,
"selected": false,
"text": "<p>In fact there is. There is a form of specification for functional languages based on Abstract Data Types called algebraic specification. Their behavior is very similar to that of objects in some ways, however the constructs are logical and mathematical, and are immutable like functional constructs.</p>\n\n<p>A particular functional specification language that's used in the Algorithms and Data Structures class in the University of Buenos Aires has generators, observers, and additional operations.\nA generator is an expression that is both an instance and a possible composition of the data type.\nFor example, for a binary tree (ADT bt), we have null nodes, and binary nodes. So we would have the generators:</p>\n\n<pre><code>-nil\n-bin(left:bt, root: a, right:bt)\n</code></pre>\n\n<p>Where left is an instance of a bt, the root is a generic value, and right is another bt.\nSo, nil is a valid form of a bt, but bin(bin(nil,1,nil),2,nil) is also valid, representing a binary tree with a root node with a value of 2, a left child node with a value of 1, and a null child right node.</p>\n\n<p>So for a function that say, calculates the number of nodes in a tree, you define an observer of the ADT, and you define a set of axioms which map to each generator.\nSo, for example:</p>\n\n<pre><code>numberOfNodes(nil) == 0\nnumberOfNodes(bin(left,x,right))== 1 + numberOfNodes(left) + numberOfNodes(right)\n</code></pre>\n\n<p>This has the advantage of using recursive definitions of operations, and has the more, formally interesting property that you can use something called structural induction to PROVE that your specification is correct (yes, you demonstrate that your algorithm will produce the proper result).</p>\n\n<p>This is a fairly academic topic rarely seen outside of academic circles, but it's worth it to get an insight on program design that may change the way you think about algorithms and data structures.\nThe proper bibliography includes:</p>\n\n<blockquote>\n <p>Bernot, G., Bidoit, M., and Knapik, T.\n 1995. Observational specifications and the indistinguishability assumption.\n Theor. Comput. Sci. 139, 1-2 (Mar.\n 1995), 275-314. DOI=\n <a href=\"http://dx.doi.org/10.1016/0304-3975(94)00017-D\" rel=\"noreferrer\">http://dx.doi.org/10.1016/0304-3975(94)00017-D</a></p>\n \n <p>Guttag, J. V. and Horning, J. J. 1993.\n Larch: Languages and Tools for Formal\n Specification. Springer-Verlag New\n York, Inc. Abstraction and\n Specification in Software Development,\n Barbara Liskov y John Guttag, MIT\n Press, 1986.</p>\n \n <p>Fundamentals of Algebraic\n Specification 1. Equations and Initial\n Semantics. H. Ehrig y B. Mahr\n Springer-Verlag, Berlin, Heidelberg,\n New York, Tokyo, Germany, 1985.</p>\n</blockquote>\n\n<p>With corresponding links:\n<a href=\"http://www.cs.st-andrews.ac.uk/~ifs/Resources/Notes/FormalSpec/AlgebraicSpec.pdf\" rel=\"noreferrer\">http://www.cs.st-andrews.ac.uk/~ifs/Resources/Notes/FormalSpec/AlgebraicSpec.pdf</a>\n<a href=\"http://nms.lcs.mit.edu/larch/pub/larchBook.ps\" rel=\"noreferrer\">http://nms.lcs.mit.edu/larch/pub/larchBook.ps</a></p>\n\n<p>It's a heck of an interesting topic.</p>\n"
},
{
"answer_id": 415327,
"author": "ja.",
"author_id": 15467,
"author_profile": "https://Stackoverflow.com/users/15467",
"pm_score": 1,
"selected": false,
"text": "<p>In both OO and FP paradigms, you form your domain model (the problem you're solving) and then create objects in your program to mirror the domain objects. There are some differences, in that how the program objects mirror the domain objects is influenced by the paradigm and langauge you're using. Some examples (in Haskell): </p>\n\n<ul>\n<li>from finance: <a href=\"http://contracts.scheming.org/\" rel=\"nofollow noreferrer\">Composing Contracts</a></li>\n<li>from word processing: <a href=\"http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.47.3229\" rel=\"nofollow noreferrer\">Bridging the Algorithm Gap</a></li>\n<li>a simple web server: <a href=\"http://lstephen.wordpress.com/2008/02/14/a-simple-haskell-web-server/\" rel=\"nofollow noreferrer\">http://lstephen.wordpress.com/2008/02/14/a-simple-haskell-web-server/</a> </li>\n<li>music: <a href=\"http://www.haskell.org/haskore/\" rel=\"nofollow noreferrer\">http://www.haskell.org/haskore/</a></li>\n</ul>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30917/"
] |
In Object Oriented Paradigm, I would create an object/conceptual model before I start implementing it using OO language.
Is there anything parallel to object model in functional programming. Is it called functional model? or we create the same conceptual model in both the paradigm before implementing it in one of the language..
Are there articles/books where I can read about functional model in case it exist?
or to put it in different way... even if we are using functional programming language, would we start with object model?
|
In fact there is. There is a form of specification for functional languages based on Abstract Data Types called algebraic specification. Their behavior is very similar to that of objects in some ways, however the constructs are logical and mathematical, and are immutable like functional constructs.
A particular functional specification language that's used in the Algorithms and Data Structures class in the University of Buenos Aires has generators, observers, and additional operations.
A generator is an expression that is both an instance and a possible composition of the data type.
For example, for a binary tree (ADT bt), we have null nodes, and binary nodes. So we would have the generators:
```
-nil
-bin(left:bt, root: a, right:bt)
```
Where left is an instance of a bt, the root is a generic value, and right is another bt.
So, nil is a valid form of a bt, but bin(bin(nil,1,nil),2,nil) is also valid, representing a binary tree with a root node with a value of 2, a left child node with a value of 1, and a null child right node.
So for a function that say, calculates the number of nodes in a tree, you define an observer of the ADT, and you define a set of axioms which map to each generator.
So, for example:
```
numberOfNodes(nil) == 0
numberOfNodes(bin(left,x,right))== 1 + numberOfNodes(left) + numberOfNodes(right)
```
This has the advantage of using recursive definitions of operations, and has the more, formally interesting property that you can use something called structural induction to PROVE that your specification is correct (yes, you demonstrate that your algorithm will produce the proper result).
This is a fairly academic topic rarely seen outside of academic circles, but it's worth it to get an insight on program design that may change the way you think about algorithms and data structures.
The proper bibliography includes:
>
> Bernot, G., Bidoit, M., and Knapik, T.
> 1995. Observational specifications and the indistinguishability assumption.
> Theor. Comput. Sci. 139, 1-2 (Mar.
> 1995), 275-314. DOI=
> <http://dx.doi.org/10.1016/0304-3975(94)00017-D>
>
>
> Guttag, J. V. and Horning, J. J. 1993.
> Larch: Languages and Tools for Formal
> Specification. Springer-Verlag New
> York, Inc. Abstraction and
> Specification in Software Development,
> Barbara Liskov y John Guttag, MIT
> Press, 1986.
>
>
> Fundamentals of Algebraic
> Specification 1. Equations and Initial
> Semantics. H. Ehrig y B. Mahr
> Springer-Verlag, Berlin, Heidelberg,
> New York, Tokyo, Germany, 1985.
>
>
>
With corresponding links:
<http://www.cs.st-andrews.ac.uk/~ifs/Resources/Notes/FormalSpec/AlgebraicSpec.pdf>
<http://nms.lcs.mit.edu/larch/pub/larchBook.ps>
It's a heck of an interesting topic.
|
288,034 |
<p>I need some help regarding algorithm for randomness. So Problem is.</p>
<p>There are 50 events going to happen in 8 hours duration. Events can happen at random times.
Now it means in each second there is a chance of event happening is 50/(8*60*60)= .001736.
How can I do this with random generation algorithm?</p>
<p>I can get random number </p>
<pre><code>int r = rand();
double chance = r/RAND_MAX;
if(chance < 0.001736)
then event happens
else
no event
</code></pre>
<p>But most of times rand() returns 0 and 0<0.001736 and I am getting more events than required.</p>
<p>Any suggestions?</p>
<hr>
<p>sorry I forget to mention
I calculated chance as
double chance = (static_cast )(r) / (static_cast)(RAND_MAX);</p>
<hr>
<p>It removed double from static_cast</p>
<p>double chance = (double)r/(double)(RAND_MAX);</p>
|
[
{
"answer_id": 288046,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 3,
"selected": false,
"text": "<p>Both <code>r</code> and <code>RAND_MAX</code> are integers, so the expression</p>\n\n<pre><code>double chance = r / RAND_MAX;\n</code></pre>\n\n<p>is computed with integer arithmetic. Try:</p>\n\n<pre><code>double chance = 1.0 * r / RAND_MAX;\n</code></pre>\n\n<p>which will cause the division to be a floating point division.</p>\n\n<p>However, a better solution would be to use a random function that returns a floating point value in the first place. If you use an integer random number generator, you will get some bias errors in your probability calculations.</p>\n"
},
{
"answer_id": 288048,
"author": "Sniggerfardimungus",
"author_id": 30997,
"author_profile": "https://Stackoverflow.com/users/30997",
"pm_score": 3,
"selected": false,
"text": "<p>If you choose whether an event will happen in each second, you have a change of 0 events occurring or 8*60*60 events occurring. If 50 events is a constraint, choose 50 random times during the 8 hour period and store them off.</p>\n"
},
{
"answer_id": 288050,
"author": "Toon Krijthe",
"author_id": 18061,
"author_profile": "https://Stackoverflow.com/users/18061",
"pm_score": 3,
"selected": true,
"text": "<ul>\n<li>Create a list of 50 numbers.</li>\n<li>Fill them with a random number between 1 and 8 * 60 * 60.</li>\n<li>Sort them</li>\n</ul>\n\n<p>And you have the 50 seconds. </p>\n\n<p>Note that you can have duplicates.</p>\n"
},
{
"answer_id": 288052,
"author": "JB King",
"author_id": 8745,
"author_profile": "https://Stackoverflow.com/users/8745",
"pm_score": 0,
"selected": false,
"text": "<p>Why not create a 28,800 element list and pull 50 elements from it to determine the time of the events? This does assume that 2 events can't occur at the same time and each event takes 1 second of time. You can use the random number generator to generate integer values between 0 and x so that it is possible to pick within the limits.</p>\n"
},
{
"answer_id": 288133,
"author": "Dan Dyer",
"author_id": 5171,
"author_profile": "https://Stackoverflow.com/users/5171",
"pm_score": 2,
"selected": false,
"text": "<p>Exactly 50, or on average 50?</p>\n\n<p>You might want to look into the <a href=\"http://en.wikipedia.org/wiki/Exponential_distribution\" rel=\"nofollow noreferrer\">Exponential distribution</a> and find a library for your language that supports it.</p>\n\n<p>The Exponential distribution will give you the intervals between events that occur randomly at a specified average rate.</p>\n\n<p>You can \"fake\" it with a uniform RNG as follows:</p>\n\n<pre><code> double u;\n do\n {\n // Get a uniformally-distributed random double between\n // zero (inclusive) and 1 (exclusive)\n u = rng.nextDouble();\n } while (u == 0d); // Reject zero, u must be +ve for this to work.\n return (-Math.log(u)) / rate;\n</code></pre>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33411/"
] |
I need some help regarding algorithm for randomness. So Problem is.
There are 50 events going to happen in 8 hours duration. Events can happen at random times.
Now it means in each second there is a chance of event happening is 50/(8\*60\*60)= .001736.
How can I do this with random generation algorithm?
I can get random number
```
int r = rand();
double chance = r/RAND_MAX;
if(chance < 0.001736)
then event happens
else
no event
```
But most of times rand() returns 0 and 0<0.001736 and I am getting more events than required.
Any suggestions?
---
sorry I forget to mention
I calculated chance as
double chance = (static\_cast )(r) / (static\_cast)(RAND\_MAX);
---
It removed double from static\_cast
double chance = (double)r/(double)(RAND\_MAX);
|
* Create a list of 50 numbers.
* Fill them with a random number between 1 and 8 \* 60 \* 60.
* Sort them
And you have the 50 seconds.
Note that you can have duplicates.
|
288,044 |
<p>I am using a <code>ListView</code> to display the main screen of my application.<br>
The main screen is essentially a <code>menu</code> to get into the different sections of application. Currently, I have the <code>ListView</code> whose contents are added programmatically in the <code>onCreate</code> method. </p>
<p>Here is the code snippet that does this:</p>
<pre><code>String[] mainItems = {
"Inbox", "Projects", "Contexts", "Next Actions"
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
setListAdapter(new ArrayAdapter<String>(
this, android.R.layout.simple_list_item_1, mainItems));
registerForContextMenu(getListView());
}
</code></pre>
<p>So the menu is essentially just a bunch of nodes with the text contained in the mainItems array. I know that I can create an XML layout (i.e. <code>R.layout.mainMenu_item</code>) that has an ImageView and TextView in it, but I am unsure how to set the ImageView's icon. I have seen that there is a setImageResouce(int resId) method, but the way to use this when generating with an ArrayAdapter is eluding me. Is there a better way to do this?</p>
|
[
{
"answer_id": 322555,
"author": "Feet",
"author_id": 18340,
"author_profile": "https://Stackoverflow.com/users/18340",
"pm_score": 1,
"selected": false,
"text": "<p>From the google docs for ArrayAdapter.</p>\n\n<blockquote>\n <p>To use something other than TextViews\n for the array display, for instance,\n ImageViews, or to have some of data\n besides toString() results fill the\n views, override getView(int, View,\n ViewGroup) to return the type of view\n you want.</p>\n</blockquote>\n"
},
{
"answer_id": 339021,
"author": "jasonhudgins",
"author_id": 24590,
"author_profile": "https://Stackoverflow.com/users/24590",
"pm_score": 5,
"selected": true,
"text": "<p>What I typically do for a ListView is to implement my own Adapter by extending the handy BaseAdapter class. One of the abstract methods you'll implement will be getView() as the previous poster mentioned. From there you can inflate a layout containing an ImageView, get a reference to it using findViewById, and set the image to whatever drawable you've added into your resources.</p>\n\n<pre><code>public View getView(int position, View convertView, ViewGroup parent) {\n\n View row = inflater.inflate(R.layout.menu_row, null);\n\n ImageView icon = (ImageView) row.findViewById(R.id.icon);\n icon.setImageResource(..your drawable's id...);\n\n return view;\n}\n</code></pre>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37436/"
] |
I am using a `ListView` to display the main screen of my application.
The main screen is essentially a `menu` to get into the different sections of application. Currently, I have the `ListView` whose contents are added programmatically in the `onCreate` method.
Here is the code snippet that does this:
```
String[] mainItems = {
"Inbox", "Projects", "Contexts", "Next Actions"
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
setListAdapter(new ArrayAdapter<String>(
this, android.R.layout.simple_list_item_1, mainItems));
registerForContextMenu(getListView());
}
```
So the menu is essentially just a bunch of nodes with the text contained in the mainItems array. I know that I can create an XML layout (i.e. `R.layout.mainMenu_item`) that has an ImageView and TextView in it, but I am unsure how to set the ImageView's icon. I have seen that there is a setImageResouce(int resId) method, but the way to use this when generating with an ArrayAdapter is eluding me. Is there a better way to do this?
|
What I typically do for a ListView is to implement my own Adapter by extending the handy BaseAdapter class. One of the abstract methods you'll implement will be getView() as the previous poster mentioned. From there you can inflate a layout containing an ImageView, get a reference to it using findViewById, and set the image to whatever drawable you've added into your resources.
```
public View getView(int position, View convertView, ViewGroup parent) {
View row = inflater.inflate(R.layout.menu_row, null);
ImageView icon = (ImageView) row.findViewById(R.id.icon);
icon.setImageResource(..your drawable's id...);
return view;
}
```
|
288,045 |
<p>I am accessing a .NET COM object from C++. I want to know the version information about this COM object. When I open the TLB in OLEVIEW.exe I can see the version information associated with the coclass. How can I access this information from C++? This is the information I get:</p>
<pre><code>[
uuid(XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX),
version(1.0),
custom(XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX, XXXX)
]
coclass XXXXXXXX{
[default] interface XXXXXXXX;
interface _Object;
interface XXXXXXXX;
};
</code></pre>
|
[
{
"answer_id": 322555,
"author": "Feet",
"author_id": 18340,
"author_profile": "https://Stackoverflow.com/users/18340",
"pm_score": 1,
"selected": false,
"text": "<p>From the google docs for ArrayAdapter.</p>\n\n<blockquote>\n <p>To use something other than TextViews\n for the array display, for instance,\n ImageViews, or to have some of data\n besides toString() results fill the\n views, override getView(int, View,\n ViewGroup) to return the type of view\n you want.</p>\n</blockquote>\n"
},
{
"answer_id": 339021,
"author": "jasonhudgins",
"author_id": 24590,
"author_profile": "https://Stackoverflow.com/users/24590",
"pm_score": 5,
"selected": true,
"text": "<p>What I typically do for a ListView is to implement my own Adapter by extending the handy BaseAdapter class. One of the abstract methods you'll implement will be getView() as the previous poster mentioned. From there you can inflate a layout containing an ImageView, get a reference to it using findViewById, and set the image to whatever drawable you've added into your resources.</p>\n\n<pre><code>public View getView(int position, View convertView, ViewGroup parent) {\n\n View row = inflater.inflate(R.layout.menu_row, null);\n\n ImageView icon = (ImageView) row.findViewById(R.id.icon);\n icon.setImageResource(..your drawable's id...);\n\n return view;\n}\n</code></pre>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8661/"
] |
I am accessing a .NET COM object from C++. I want to know the version information about this COM object. When I open the TLB in OLEVIEW.exe I can see the version information associated with the coclass. How can I access this information from C++? This is the information I get:
```
[
uuid(XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX),
version(1.0),
custom(XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX, XXXX)
]
coclass XXXXXXXX{
[default] interface XXXXXXXX;
interface _Object;
interface XXXXXXXX;
};
```
|
What I typically do for a ListView is to implement my own Adapter by extending the handy BaseAdapter class. One of the abstract methods you'll implement will be getView() as the previous poster mentioned. From there you can inflate a layout containing an ImageView, get a reference to it using findViewById, and set the image to whatever drawable you've added into your resources.
```
public View getView(int position, View convertView, ViewGroup parent) {
View row = inflater.inflate(R.layout.menu_row, null);
ImageView icon = (ImageView) row.findViewById(R.id.icon);
icon.setImageResource(..your drawable's id...);
return view;
}
```
|
288,054 |
<p>Goal: Efficiently show/hide rows based on the data in the row.</p>
<ol>
<li>Create a helper column that determines whether or not
a row should be hidden.</li>
<li>Have the formula in the helper
column return an error or a number.</li>
<li>Hide the helper column and write
code to execute the hiding/showing.</li>
</ol>
<p>Question: Which one of the following methods would you expect to be faster? Column B is the helper column and will always be contiguous.</p>
<pre><code> Sub SetRowVisibility1()
Dim rowsToCheck As Range
With ActiveSheet
Set rowsToCheck = .Range(Range("B7"), Range("B7").End(xlDown))
End With
Dim needToShow As Range, needToShow_Showing As Range
Dim needToHide As Range, needToHide_Showing As Range
Set needToShow = rowsToCheck.SpecialCells(xlCellTypeFormulas, xlNumbers)
Set needToHide = rowsToCheck.SpecialCells(xlCellTypeFormulas, xlErrors)
On Error Resume Next
Set needToShow_Showing = needToShow.Offset(0, 1).SpecialCells(xlCellTypeVisible)
Set needToHide_Showing = needToHide.Offset(0, 1).SpecialCells(xlCellTypeVisible)
On Error GoTo 0
If Not needToHide_Showing Is Nothing Then
needToHide_Showing.EntireRow.Hidden = True
End If
If Not needToShow Is Nothing Then
If needToShow.Count <> needToShow_Showing.Count Then
needToShow.EntireRow.Hidden = False
End If
End If
End Sub
Sub SetRowVisibility2()
Dim rowsToCheck As Range
With ActiveSheet
Set rowsToCheck = .Range(Range("B7"), Range("B7").End(xlDown))
End With
Dim needToShow As Range, needToHide As Range
Dim cell As Range
For Each cell In rowsToCheck
If IsError(cell.Value) And (cell.EntireRow.Hidden = False) Then
If needToHide Is Nothing Then
Set needToHide = cell
Else
Set needToHide = Union(needToHide, cell)
End If
End If
If Not IsError(cell.Value) And (cell.EntireRow.Hidden = True) Then
If needToShow Is Nothing Then
Set needToShow = cell
Else
Set needToShow = Union(needToShow, cell)
End If
End If
Next cell
If Not needToHide Is Nothing Then needToHide.EntireRow.Hidden = True
If Not needToShow Is Nothing Then needToShow.EntireRow.Hidden = False
End Sub
</code></pre>
|
[
{
"answer_id": 288970,
"author": "SpyJournal",
"author_id": 10326,
"author_profile": "https://Stackoverflow.com/users/10326",
"pm_score": 1,
"selected": false,
"text": "<p>there is a different way and that is to use th auto filter feature - after all VBA has an A in it - use the features of the application wherever possible\nso this bit of code is pretty short and sweet - assumes that the data is a contiguous block in columns a and b and assumes no other error handling in play. the resume next line allows for the filter to be already turned on.</p>\n\n<pre>Sub showHideRange()\nDim testrange\n testrange = Range(\"A1\").CurrentRegion.Address\n On Error Resume Next\n testrange.AutoFilter\n ActiveSheet.Range(testrange).AutoFilter Field:=2, Criteria1:=\"show\"\nEnd Sub\n</pre>\n"
},
{
"answer_id": 2193212,
"author": "Dave DuPlantis",
"author_id": 8174,
"author_profile": "https://Stackoverflow.com/users/8174",
"pm_score": 0,
"selected": false,
"text": "<p>If you do not wish to show the user what's happening, would it not be better to perform the calculation in VBA itself, rather than in a hidden column? Granted, that would seem to lock you into option 2, which I suspect is the slower option ... most of my VBA experience is in older versions of Excel, so I've not had the pleasure of working with some of the newer features, and the tasks I've done that involved processing rows of data were done row-by-row. </p>\n\n<p>I guess one possible issue with the first sub is that if there is a problem with the worksheet or the values you're using to determine hiding/showing, the process will fail. If you check row-by-row and there is a row that causes problems, you could skip over that row and process the other ones correctly.</p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25197/"
] |
Goal: Efficiently show/hide rows based on the data in the row.
1. Create a helper column that determines whether or not
a row should be hidden.
2. Have the formula in the helper
column return an error or a number.
3. Hide the helper column and write
code to execute the hiding/showing.
Question: Which one of the following methods would you expect to be faster? Column B is the helper column and will always be contiguous.
```
Sub SetRowVisibility1()
Dim rowsToCheck As Range
With ActiveSheet
Set rowsToCheck = .Range(Range("B7"), Range("B7").End(xlDown))
End With
Dim needToShow As Range, needToShow_Showing As Range
Dim needToHide As Range, needToHide_Showing As Range
Set needToShow = rowsToCheck.SpecialCells(xlCellTypeFormulas, xlNumbers)
Set needToHide = rowsToCheck.SpecialCells(xlCellTypeFormulas, xlErrors)
On Error Resume Next
Set needToShow_Showing = needToShow.Offset(0, 1).SpecialCells(xlCellTypeVisible)
Set needToHide_Showing = needToHide.Offset(0, 1).SpecialCells(xlCellTypeVisible)
On Error GoTo 0
If Not needToHide_Showing Is Nothing Then
needToHide_Showing.EntireRow.Hidden = True
End If
If Not needToShow Is Nothing Then
If needToShow.Count <> needToShow_Showing.Count Then
needToShow.EntireRow.Hidden = False
End If
End If
End Sub
Sub SetRowVisibility2()
Dim rowsToCheck As Range
With ActiveSheet
Set rowsToCheck = .Range(Range("B7"), Range("B7").End(xlDown))
End With
Dim needToShow As Range, needToHide As Range
Dim cell As Range
For Each cell In rowsToCheck
If IsError(cell.Value) And (cell.EntireRow.Hidden = False) Then
If needToHide Is Nothing Then
Set needToHide = cell
Else
Set needToHide = Union(needToHide, cell)
End If
End If
If Not IsError(cell.Value) And (cell.EntireRow.Hidden = True) Then
If needToShow Is Nothing Then
Set needToShow = cell
Else
Set needToShow = Union(needToShow, cell)
End If
End If
Next cell
If Not needToHide Is Nothing Then needToHide.EntireRow.Hidden = True
If Not needToShow Is Nothing Then needToShow.EntireRow.Hidden = False
End Sub
```
|
there is a different way and that is to use th auto filter feature - after all VBA has an A in it - use the features of the application wherever possible
so this bit of code is pretty short and sweet - assumes that the data is a contiguous block in columns a and b and assumes no other error handling in play. the resume next line allows for the filter to be already turned on.
```
Sub showHideRange()
Dim testrange
testrange = Range("A1").CurrentRegion.Address
On Error Resume Next
testrange.AutoFilter
ActiveSheet.Range(testrange).AutoFilter Field:=2, Criteria1:="show"
End Sub
```
|
288,062 |
<p>It seems as though the following calls do what you'd expect (close the stream and not allow any further input - anything waiting for input on the stream returns error), but is it guaranteed to be correct across all compilers/platforms?</p>
<pre><code>close(fileno(stdin));
fclose(stdin);
</code></pre>
|
[
{
"answer_id": 288089,
"author": "Sniggerfardimungus",
"author_id": 30997,
"author_profile": "https://Stackoverflow.com/users/30997",
"pm_score": 4,
"selected": false,
"text": "<p>DO NOT DO a close on fileno(FILE*). FILE is a buffering object. Looking into its implementation and meddling with its state carries all the caveats and dangers that would come with similar misbehavior on any other software module.</p>\n\n<p>Don't do it.</p>\n\n<p>AGH. Seriously. Nasty.</p>\n"
},
{
"answer_id": 288097,
"author": "Jason Coco",
"author_id": 34218,
"author_profile": "https://Stackoverflow.com/users/34218",
"pm_score": 3,
"selected": true,
"text": "<p>Nothing is guaranteed correct across every possible operating system. However, calling fclose(stdin) will work on any POSIX compliant operating system as well as Windows operating systems, so you should hit pretty much anything in general use at the moment.</p>\n\n<p>As stated by the previous answer as well as my comment, there is no need to call close on the file handle. fclose() will properly close everything down for you.</p>\n"
},
{
"answer_id": 5925575,
"author": "R.. GitHub STOP HELPING ICE",
"author_id": 379897,
"author_profile": "https://Stackoverflow.com/users/379897",
"pm_score": 5,
"selected": false,
"text": "<p><code>fclose(stdin)</code> causes any further use of <code>stdin</code> (implicit or explicit) to invoke undefined behavior, which is a <strong>very bad thing</strong>. It does not \"inhibit input\".</p>\n\n<p><code>close(fileno(stdin))</code> causes any further attempts at input from <code>stdin</code>, after the current buffer has been depleted, to fail with <code>EBADF</code>, but only until you open another file, in which case that file will become fd #0 and <strong>bad things will happen</strong>.</p>\n\n<p>A more robust approach might be:</p>\n\n<pre><code>int fd = open(\"/dev/null\", O_WRONLY);\ndup2(fd, 0);\nclose(fd);\n</code></pre>\n\n<p>with a few added error checks. This will ensure that all reads (after the current buffer is depleted) result in errors. If you just want them to result in EOF, not an error, use <code>O_RDONLY</code> instead of <code>O_WRONLY</code>.</p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5963/"
] |
It seems as though the following calls do what you'd expect (close the stream and not allow any further input - anything waiting for input on the stream returns error), but is it guaranteed to be correct across all compilers/platforms?
```
close(fileno(stdin));
fclose(stdin);
```
|
Nothing is guaranteed correct across every possible operating system. However, calling fclose(stdin) will work on any POSIX compliant operating system as well as Windows operating systems, so you should hit pretty much anything in general use at the moment.
As stated by the previous answer as well as my comment, there is no need to call close on the file handle. fclose() will properly close everything down for you.
|
288,068 |
<p>I need to add localization to the exceptions thrown by my application as a lot are ApplicationExceptions and handled and logged to an error report. Ideally I want to create a new Exception, imheriting from ApplicationException that I can pass the resource key as well as arguments to, so that the exception messsage can be built up from the resource information. Unfortunately (I think) the only way to set the message in an exception is in the New()...</p>
<p>I would like something like:</p>
<pre><code>public class LocalizedException
Inherits ApplicationException
public Sub New(ResourceKey as string, arg0 as Object)
MyBase.New()
' get the localized text'
Dim ResMan as New Global.System.Resources.ResourceManager("AppName.ExceptionResources", _
System.Reflection.Assembly.GetExecutingAssembly)
Dim LocalText as string = ResMan.GetString(ResourceKey)
Dim ErrorText as String = ""
Try
Dim ErrorText = String.Format(LocalText, arg0)
Catch
ErrorText = LocalText + arg0.ToString() ' in case String.Format fails'
End Try
' cannot now set the exception message!'
End Sub
End Class
</code></pre>
<p>However I can only have MyBase.New() as the first line
Message is ReadOnly</p>
<p>Does anyone have any recommendations as to how to get localised strings into the Exception handler? I will need this in a few different exceptions, though could go the way of a exceptioncreation function that gets the localised string and creates teh exception, though the stack info would then be wrong. I also don't want too much in the main body before teh Throw as it obviously starts to impinge on readability of the flow. </p>
|
[
{
"answer_id": 288129,
"author": "labilbe",
"author_id": 1195872,
"author_profile": "https://Stackoverflow.com/users/1195872",
"pm_score": 3,
"selected": true,
"text": "<p>Here is a sample of what I do.\nEmillException inherits from ApplicationException.</p>\n\n<pre><code>\nnamespace eMill.Model.Exceptions\n{\n public sealed class AccountNotFoundException : EmillException\n {\n private readonly string _accountName;\n\n public AccountNotFoundException(string accountName)\n {\n _accountName = accountName;\n }\n\n public override string Message\n {\n get { return string.Format(Resource.GetString(\"ErrAccountNotFoundFmt\"), _accountName); }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 331009,
"author": "Hath",
"author_id": 5186,
"author_profile": "https://Stackoverflow.com/users/5186",
"pm_score": 0,
"selected": false,
"text": "<p>have a look at this: </p>\n\n<p><a href=\"http://visualstudiomagazine.com/features/article.aspx?editorialsid=2562\" rel=\"nofollow noreferrer\">http://visualstudiomagazine.com/features/article.aspx?editorialsid=2562</a></p>\n\n<p>I don't have to deal with localization but it makes allot of sense.</p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6684/"
] |
I need to add localization to the exceptions thrown by my application as a lot are ApplicationExceptions and handled and logged to an error report. Ideally I want to create a new Exception, imheriting from ApplicationException that I can pass the resource key as well as arguments to, so that the exception messsage can be built up from the resource information. Unfortunately (I think) the only way to set the message in an exception is in the New()...
I would like something like:
```
public class LocalizedException
Inherits ApplicationException
public Sub New(ResourceKey as string, arg0 as Object)
MyBase.New()
' get the localized text'
Dim ResMan as New Global.System.Resources.ResourceManager("AppName.ExceptionResources", _
System.Reflection.Assembly.GetExecutingAssembly)
Dim LocalText as string = ResMan.GetString(ResourceKey)
Dim ErrorText as String = ""
Try
Dim ErrorText = String.Format(LocalText, arg0)
Catch
ErrorText = LocalText + arg0.ToString() ' in case String.Format fails'
End Try
' cannot now set the exception message!'
End Sub
End Class
```
However I can only have MyBase.New() as the first line
Message is ReadOnly
Does anyone have any recommendations as to how to get localised strings into the Exception handler? I will need this in a few different exceptions, though could go the way of a exceptioncreation function that gets the localised string and creates teh exception, though the stack info would then be wrong. I also don't want too much in the main body before teh Throw as it obviously starts to impinge on readability of the flow.
|
Here is a sample of what I do.
EmillException inherits from ApplicationException.
```
namespace eMill.Model.Exceptions
{
public sealed class AccountNotFoundException : EmillException
{
private readonly string _accountName;
public AccountNotFoundException(string accountName)
{
_accountName = accountName;
}
public override string Message
{
get { return string.Format(Resource.GetString("ErrAccountNotFoundFmt"), _accountName); }
}
}
}
```
|
288,070 |
<p>I am using a WCF service and a net.tcp endpoint with serviceAuthentication's principal PermissionMode set to UseWindowsGroups.</p>
<p>Currently in the implementation of the service i am using the PrincipalPermission attribute to set the role requirements for each method. </p>
<pre><code> [PrincipalPermission(SecurityAction.Demand, Role = "Administrators")]
[OperationBehavior(Impersonation = ImpersonationOption.Required)]
public string method1()
</code></pre>
<p>I am trying to do pretty much the same exact thing, except have the configuration for the role set in the app.config. Is there any way to do this and still be using windows groups authentication?</p>
<p>Thanks</p>
|
[
{
"answer_id": 288758,
"author": "Panos",
"author_id": 8049,
"author_profile": "https://Stackoverflow.com/users/8049",
"pm_score": 3,
"selected": true,
"text": "<p>If I understood well you want to select the role at runtime. This can be done with a <a href=\"http://msdn.microsoft.com/en-us/library/system.security.permissions.principalpermission.aspx\" rel=\"nofollow noreferrer\">permission</a> demand within the WCF operation. E.g.</p>\n\n<pre><code>public string method1()\n{\n PrincipalPermission p = new PrincipalPermission(null, \"Administrators\");\n p.Demand();\n ...\n</code></pre>\n"
},
{
"answer_id": 289696,
"author": "Enrico Campidoglio",
"author_id": 26396,
"author_profile": "https://Stackoverflow.com/users/26396",
"pm_score": 3,
"selected": false,
"text": "<p>If you are hosting your WCF service in IIS, it will run in the ASP.NET worker process, which means you can configure authentication and authorization as you would do with ASMX web services:</p>\n\n<pre><code><system.Web>\n <authentication mode=\"Windows\"/>\n <authorization>\n <allow roles=\".\\Administrators\"/>\n <deny users=\"*\"/>\n </authorization>\n</system.Web>\n</code></pre>\n\n<p>Then you will have to disable anonymous access to your endpoint in IIS, and instead enable <strong>Windows Integrated Authentication</strong>.<br/>In the IIS management console you do that by bringing up the '<em>Properties</em>' dialog for your virtual directory. You will then find the security settings in the '<em>Directory Security</em>' tab.</p>\n\n<p>Of course, the only communication channel available will be HTTP. Clients will have to provide their Windows identity in the request at the <em>transport-level</em> with these settings:</p>\n\n<pre><code><system.serviceModel>\n <bindings>\n <wsHttpBinding>\n <binding name=\"WindowsSecurity\">\n <security mode=\"Transport\">\n <transport clientCredentialType=\"Windows\" />\n </security>\n </binding>\n </wsHttpBinding>\n </bindings>\n <client>\n <endpoint address=\"https://localhost/myservice\"\n binding=\"wsHttpBinding\"\n bindingConfiguration=\"WindowsSecurity\"\n contract=\"IMyService\" />\n </client>\n</system.serviceModel>\n</code></pre>\n\n<p>Note that if your service endpoint uses <strong>wsHttpBinding</strong> then you will also have to add SSL to your endpoint since that's a requirement enforced by WCF when you using transport-level security.<br/>\nIf you instead go for the <strong>basicHttpBinding</strong>, you are then able to use a <em>less secure</em> authentication mode available in WCF called <strong>TransportCredentialOnly</strong>, where SSL is no longer required.</p>\n\n<p>For more detailed information, <a href=\"http://www.code-magazine.com/articleprint.aspx?quickid=0611051\" rel=\"noreferrer\">here</a> is a good overview of the security infrastructure in WCF.</p>\n"
},
{
"answer_id": 1281410,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Lars Wilhelmsen has posted a solution for this problem. Have a look at\n<a href=\"http://www.larswilhelmsen.com/2008/12/17/configurable-principalpermission-attribute/\" rel=\"nofollow noreferrer\">http://www.larswilhelmsen.com/2008/12/17/configurable-principalpermission-attribute/</a></p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37444/"
] |
I am using a WCF service and a net.tcp endpoint with serviceAuthentication's principal PermissionMode set to UseWindowsGroups.
Currently in the implementation of the service i am using the PrincipalPermission attribute to set the role requirements for each method.
```
[PrincipalPermission(SecurityAction.Demand, Role = "Administrators")]
[OperationBehavior(Impersonation = ImpersonationOption.Required)]
public string method1()
```
I am trying to do pretty much the same exact thing, except have the configuration for the role set in the app.config. Is there any way to do this and still be using windows groups authentication?
Thanks
|
If I understood well you want to select the role at runtime. This can be done with a [permission](http://msdn.microsoft.com/en-us/library/system.security.permissions.principalpermission.aspx) demand within the WCF operation. E.g.
```
public string method1()
{
PrincipalPermission p = new PrincipalPermission(null, "Administrators");
p.Demand();
...
```
|
288,076 |
<p>I'm trying to upload an image to my site through a form, however it's much more efficient to (rather than bog down the database) just store the location of the image in the database.</p>
<p>I'm having trouble with my form and really don't know where to go:</p>
<pre><code><?=form_open('bro/submit_new');?>
//other form data
Image: <input type="file" name="image" size="20" /> <br>
<input type="submit" value="Submit" />
</form>
</code></pre>
<p>Now the form itself works fine, the problem is that it's trying to store the image into the database field 'image' (which is type TEXT). What's the easiest way to tell it to just store the file, and give the file location to store in the 'image' field? (I tell it where to upload the file via the controller).</p>
<p>Thanks</p>
<p>Edit: controller code (for this part):</p>
<pre><code>function submit_new(){
$config['upload_path'] = './images/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '2000';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
$this->db->insert('post', $_POST);
redirect('bro');
}
</code></pre>
|
[
{
"answer_id": 288101,
"author": "victoriah",
"author_id": 37014,
"author_profile": "https://Stackoverflow.com/users/37014",
"pm_score": 4,
"selected": true,
"text": "<p>CodeIgniter's file uploading class will do this for you. The <a href=\"http://codeigniter.com/user_guide/libraries/file_uploading.html\" rel=\"noreferrer\">entry in their user guide</a> explains as well as I could, so I'm going to point you there. </p>\n\n<p>Essentially you'd just need to modify the controller that they have there to include a bit where you put the file URL in the database, which you can accomplish easily by using $this->upload->data() and extracting [full_path] from the resulting array, and then sending it to a model which handles the database input.</p>\n"
},
{
"answer_id": 1154318,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>use form_open_multipart() not form_open()</p>\n"
},
{
"answer_id": 16209781,
"author": "abcdef",
"author_id": 2318805,
"author_profile": "https://Stackoverflow.com/users/2318805",
"pm_score": -1,
"selected": false,
"text": "<p>use the model pages to upload data to database</p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288076",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24565/"
] |
I'm trying to upload an image to my site through a form, however it's much more efficient to (rather than bog down the database) just store the location of the image in the database.
I'm having trouble with my form and really don't know where to go:
```
<?=form_open('bro/submit_new');?>
//other form data
Image: <input type="file" name="image" size="20" /> <br>
<input type="submit" value="Submit" />
</form>
```
Now the form itself works fine, the problem is that it's trying to store the image into the database field 'image' (which is type TEXT). What's the easiest way to tell it to just store the file, and give the file location to store in the 'image' field? (I tell it where to upload the file via the controller).
Thanks
Edit: controller code (for this part):
```
function submit_new(){
$config['upload_path'] = './images/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '2000';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
$this->db->insert('post', $_POST);
redirect('bro');
}
```
|
CodeIgniter's file uploading class will do this for you. The [entry in their user guide](http://codeigniter.com/user_guide/libraries/file_uploading.html) explains as well as I could, so I'm going to point you there.
Essentially you'd just need to modify the controller that they have there to include a bit where you put the file URL in the database, which you can accomplish easily by using $this->upload->data() and extracting [full\_path] from the resulting array, and then sending it to a model which handles the database input.
|
288,084 |
<p>Is there any other way to get a list of file names via <code>T-SQL</code> other than </p>
<pre><code>INSERT INTO @backups(filename)
EXEC master.sys.xp_cmdshell 'DIR /b c:\some folder with sql backups in it
</code></pre>
<p>I am attempting to get a list of SQL backup files from a folder to restore and I do NOT want to use the <code>xp_cmdshell</code> for obvious security reasons.</p>
|
[
{
"answer_id": 288451,
"author": "Sam",
"author_id": 37379,
"author_profile": "https://Stackoverflow.com/users/37379",
"pm_score": 1,
"selected": false,
"text": "<p>If you have access to the <em>server that backup up the files</em>, you can use the system tables to find the backup file(s) you prefer.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms188062.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms188062.aspx</a></p>\n\n<p>You'll be interested in the backup tables. </p>\n"
},
{
"answer_id": 288759,
"author": "Kevin Crumley",
"author_id": 1818,
"author_profile": "https://Stackoverflow.com/users/1818",
"pm_score": 1,
"selected": false,
"text": "<p>Three options, depending on your environment and needs:</p>\n\n<ol>\n<li>If you're using SQL2005 or 2008, you can almost certainly write a CLR stored procedure to do this job. If you haven't done it before, it's probably more work than you're looking to do, but since I already have a project I could add this to, it's probably what I would do if I really needed SQL to be able to read from a directory.</li>\n<li>As Sam suggests, if you have access to the source of the backups, you can query the tables in the MSDB database. My suggestion might be to query msdb.dbo.backupmediafamily.physical_device_name to get a list of files that <em>might</em> be in available to you, then test if they exist by using: \n<code>RESTORE FILELISTONLY disk='FULL_PATH_TO_YOUR_FILE'</code>. This throws a non-fatal error if the file doesn't exist. You can check for an error in T-SQL by testing if @@error is non-zero. </li>\n<li>If your environment makes it possible, a quick script running in Windows, outside of SQL Server, might be your best bet. You can set it up as a scheduled task if you need to. You could, for example, have it run every 15 minutes, check if a file has appeared since the last time the script ran, and insert any files into a table in SQL Server. I've done similar-enough tasks in Perl, Ruby, and VBScript. It could probably be done with a batch file, too. Again, I don't know your exact needs or skillset, but if I just needed to get this done, and didn't 100% need it to run from within SQL Server, I'd probably just write a script.</li>\n</ol>\n"
},
{
"answer_id": 288860,
"author": "Ron Skufca",
"author_id": 4096,
"author_profile": "https://Stackoverflow.com/users/4096",
"pm_score": 1,
"selected": true,
"text": "<p>The alternative to xp_cmdshell I came up is below:</p>\n\n<p>My situation is a little unique in that I am attempting a poor man's log shipping. I have a folder (not the default SQL backup location) where transaction logs are deposited from a remote server. I am writing a c# app that loops through that directory and creates a comma delimited string of file names with paths (e.g. FooA.txn,FooB.txn,FooC.txn). I then feed this string into a stored procedure that I wrote which parses the string and inserts the file names into a temp table. Then I loop through the temp table restoring each transaction log in order.</p>\n\n<p>Basically the C# app replaces xp_cmdshell and from the app I can call a stored procedure.</p>\n"
},
{
"answer_id": 16380244,
"author": "Jeff Moden",
"author_id": 313265,
"author_profile": "https://Stackoverflow.com/users/313265",
"pm_score": 1,
"selected": false,
"text": "<p>I do realize that this thread is 5 years old but I thought I'd post another non-xpCmdShell, non-CLR alternative. Details are in the following code and it's pretty simple stuff.</p>\n\n<pre><code>--===== Define the path and populate it.\n -- This could be a parameter in a proc\nDECLARE @pPath VARCHAR(512);\n SELECT @pPath = 'C:\\Temp';\n\n--===== Create a table to store the directory information in\n CREATE TABLE #DIR\n (\n RowNum INT IDENTITY(1,1),\n ObjectName VARCHAR(512),\n Depth TINYINT,\n IsFile BIT,\n Extension AS RIGHT(ObjectName,CHARINDEX('.',REVERSE(ObjectName))) PERSISTED\n )\n;\n--===== Get the directory information and remember it\n INSERT INTO #DIR\n (ObjectName,Depth,IsFile)\n EXEC xp_DirTree 'C:\\Temp',1,1\n;\n--===== Now do whatever it is you need to do with it\n SELECT * FROM #DIR;\n</code></pre>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4096/"
] |
Is there any other way to get a list of file names via `T-SQL` other than
```
INSERT INTO @backups(filename)
EXEC master.sys.xp_cmdshell 'DIR /b c:\some folder with sql backups in it
```
I am attempting to get a list of SQL backup files from a folder to restore and I do NOT want to use the `xp_cmdshell` for obvious security reasons.
|
The alternative to xp\_cmdshell I came up is below:
My situation is a little unique in that I am attempting a poor man's log shipping. I have a folder (not the default SQL backup location) where transaction logs are deposited from a remote server. I am writing a c# app that loops through that directory and creates a comma delimited string of file names with paths (e.g. FooA.txn,FooB.txn,FooC.txn). I then feed this string into a stored procedure that I wrote which parses the string and inserts the file names into a temp table. Then I loop through the temp table restoring each transaction log in order.
Basically the C# app replaces xp\_cmdshell and from the app I can call a stored procedure.
|
288,111 |
<p>I have an HTTPHandler that is reading in a set of CSS files and combining them and then GZipping them. However, some of the CSS files contain a Byte Order Mark (due to a bug in TFS 2005 auto merge) and in FireFox the BOM is being read as part of the actual content so it's screwing up my class names etc. How can I strip out the BOM characters? Is there an easy way to do this without manually going through the byte array looking for ""?</p>
|
[
{
"answer_id": 289114,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 3,
"selected": false,
"text": "<p>Expanding on <a href=\"https://stackoverflow.com/questions/288111/remove-byte-order-mark-from-a-file-readallbytes-byte#comment21871755_288111\">Jon's comment</a> with a sample.</p>\n\n<pre><code>var name = GetFileName();\nvar bytes = System.IO.File.ReadAllBytes(name);\nSystem.IO.File.WriteAllBytes(name, bytes.Skip(3).ToArray());\n</code></pre>\n"
},
{
"answer_id": 289505,
"author": "Tim Bailey",
"author_id": 1077232,
"author_profile": "https://Stackoverflow.com/users/1077232",
"pm_score": 1,
"selected": false,
"text": "<p>Another way, assuming UTF-8 to ASCII.</p>\n\n<pre><code>File.WriteAllText(filename, File.ReadAllText(filename, Encoding.UTF8), Encoding.ASCII);\n</code></pre>\n"
},
{
"answer_id": 1136541,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<pre><code>var text = File.ReadAllText(args.SourceFileName);\nvar streamWriter = new StreamWriter(args.DestFileName, args.Append, new UTF8Encoding(false));\nstreamWriter.Write(text);\nstreamWriter.Close();\n</code></pre>\n"
},
{
"answer_id": 2863890,
"author": "Olivier de Rivoyre",
"author_id": 26071,
"author_profile": "https://Stackoverflow.com/users/26071",
"pm_score": 3,
"selected": false,
"text": "<p>Expanding JaredPar sample to recurse over sub-directories:</p>\n\n<pre><code>using System.Linq;\nusing System.IO;\nnamespace BomRemover\n{\n /// <summary>\n /// Remove UTF-8 BOM (EF BB BF) of all *.php files in current & sub-directories.\n /// </summary>\n class Program\n {\n private static void removeBoms(string filePattern, string directory)\n {\n foreach (string filename in Directory.GetFiles(directory, file Pattern))\n {\n var bytes = System.IO.File.ReadAllBytes(filename);\n if(bytes.Length > 2 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF)\n {\n System.IO.File.WriteAllBytes(filename, bytes.Skip(3).ToArray()); \n }\n }\n foreach (string subDirectory in Directory.GetDirectories(directory))\n {\n removeBoms(filePattern, subDirectory);\n }\n }\n static void Main(string[] args)\n {\n string filePattern = \"*.php\";\n string startDirectory = Directory.GetCurrentDirectory();\n removeBoms(filePattern, startDirectory); \n } \n }\n}\n</code></pre>\n\n<p>I had need that C# piece of code after discovering that the UTF-8 BOM corrupts file when you try to do a basic PHP download file.</p>\n"
},
{
"answer_id": 49279224,
"author": "Ashokan Sivapragasam",
"author_id": 6928056,
"author_profile": "https://Stackoverflow.com/users/6928056",
"pm_score": 0,
"selected": false,
"text": "<p>For larger file, use the following code; memory efficient!</p>\n\n<pre><code>StreamReader sr = new StreamReader(path: @\"<Input_file_full_path_with_byte_order_mark>\", \n detectEncodingFromByteOrderMarks: true);\n\nStreamWriter sw = new StreamWriter(path: @\"<Output_file_without_byte_order_mark>\", \n append: false, \n encoding: new UnicodeEncoding(bigEndian: false, byteOrderMark: false));\n\nvar lineNumber = 0;\nwhile (!sr.EndOfStream)\n{\n sw.WriteLine(sr.ReadLine());\n lineNumber += 1;\n if (lineNumber % 100000 == 0)\n Console.Write(\"\\rLine# \" + lineNumber.ToString(\"000000000000\"));\n}\n\nsw.Flush();\nsw.Close();\n</code></pre>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4541/"
] |
I have an HTTPHandler that is reading in a set of CSS files and combining them and then GZipping them. However, some of the CSS files contain a Byte Order Mark (due to a bug in TFS 2005 auto merge) and in FireFox the BOM is being read as part of the actual content so it's screwing up my class names etc. How can I strip out the BOM characters? Is there an easy way to do this without manually going through the byte array looking for ""?
|
Expanding on [Jon's comment](https://stackoverflow.com/questions/288111/remove-byte-order-mark-from-a-file-readallbytes-byte#comment21871755_288111) with a sample.
```
var name = GetFileName();
var bytes = System.IO.File.ReadAllBytes(name);
System.IO.File.WriteAllBytes(name, bytes.Skip(3).ToArray());
```
|
288,153 |
<p>I would like to know How to create a fps-game with SDL lib? </p>
<p>Are there any books that explain with examples? </p>
|
[
{
"answer_id": 288165,
"author": "Dan Blair",
"author_id": 1327,
"author_profile": "https://Stackoverflow.com/users/1327",
"pm_score": 0,
"selected": false,
"text": "<p>Pretty much anything that says in the TItle the \"Tricks of the Game Programming Gurus\" is going to show you how to make a FPS game. LeMothe loves them.</p>\n\n<p>Edit : forgot those titles.</p>\n"
},
{
"answer_id": 288246,
"author": "user32141",
"author_id": 32141,
"author_profile": "https://Stackoverflow.com/users/32141",
"pm_score": 3,
"selected": false,
"text": "<p>Download the quake 3 sources at <a href=\"http://www.fileshack.com/file.x?fid=7547\" rel=\"noreferrer\">fileshack</a> and learn from them.</p>\n"
},
{
"answer_id": 288376,
"author": "David Frenkel",
"author_id": 28747,
"author_profile": "https://Stackoverflow.com/users/28747",
"pm_score": 5,
"selected": true,
"text": "<p>this wins for most open ended question. You could literally write a book. But lets settle for pointing in the right direction...</p>\n\n<p>Step one, you will need good debugging skills for a project like this. Pick up Code Complete by Steve McConnell. Read the whole thing. The time invested will pay for itself more than anything else you could read/experiment with.</p>\n\n<p>Get your hands on some source code of some game. ANY game. Make sure you see something simple before you see something big and complex, and keep in mind when you look at any game code that they may have had a combined team put WAY more time into it than you will ever have. The point in this is to see code structure.</p>\n\n<p>Get a reference for 3D math, doesn't have to be THAT in depth, but you will need to know stuff like dot products backwards and forwards, be able to figure out how to create the matrix for your camera in the world etc. (even if your writing 0% of the rendering code)</p>\n\n<p><em>(edit)</em> Here's a great book on 3D math<a href=\"https://rads.stackoverflow.com/amzn/click/com/1584502770\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Mathematics for 3D Game Programming and Computer Graphics, Second Edition (Game Development Series)</a> This isn't the kind you learn in college, it's more like a cross between trig and more advanced practical concepts: How to create a toolbox for yourself of simple physics, efficient collision detection, etc.</p>\n\n<p>You will need to know something about rendering, and pipelines. SDL gives you a leg up, but make sure you understand the concepts of what it's doing.</p>\n\n<p>Read up about practical system design. Your various systems will have to interlock. Think it out well. Your system can be just a good in C or in C++, it's the THOUGHT that is put into how your data/control will flow that will count, NOT how perfectly you emulate design patterns (though these are very useful as well of coarse)</p>\n\n<p>Fundamentals of AI, not \"real\" AI, but functional AI; there is a big difference. State machines are great to start with, and sufficient for a simple FPS. </p>\n\n<p>Learn a little about estimation and planning. You will not have time to do everything you would want to do to properly make an FPS. You will have to both triage AND learn how to triage; they are 2 separate things, the latter being mroe difficult. Experience is the best teacher here of coarse. (though the legendary McConnell has book on this as well)</p>\n\n<p>Have a system to insert your gameplay into your level. If it is JUST you as a programmer, then your best bet is to write a plug in for an already existing editing program such as 3DS Max. I would highly recommend Max over Maya for a programmer. Maya script is nice, but it is more geared toward clever non-programmers. I find 3DS Max to think more along the lines of how a programmer would about creating and editing your world.</p>\n\n<p>You can spend YEARS making tools to let you do this right, so you want to do things in such a way that you can edit fast and accurately\nIf you making your own editor, incorporate it into your game world.\nIf your world is not TRULY 3D and you want to make lots of level fast you can save your level data as something like this, which will save you a lot of time\nWhere X is a wall, the other letters are game objects which a dirt simple parser can translate into game objects and world coordinates</p>\n\n<pre><code> xxxxxxxxxxxxxxxxxxxxxxxx\n xx..........P..........x\n xxxxxxx...........I....x\n xR....xxx...........E..x\n xx.................0xxxx\n xxxxxxxxxxxxxxxxxxxxxxxx\n</code></pre>\n\n<p>But it all depends on your game. My point is that you will need to resort to \"ghetto coding\" how you get your gameplay data into your world is very important and you need to think of something that is both fast for you to implement AND fast with you to work with.</p>\n\n<p>And what it comes down to is what is your goal here? If it's to learn to code something the absolute right way, expect to spend most of your time iterating on code that seemed decent a month ago, but now that you realize what your requirements are, it could really use another pass. Do not be afraid to rewrite, you learn a lot by doing that, but if you goal is functionality, you will probably need to figure out where to hack some things in (like embedding gameplay data nad coordinates into code files) It <em>IS</em> ok to hack as long as you KNOW where you have hacked, and have carefully kept it separate from your good code so you can go back and properly write the code when you get the chance.</p>\n\n<p>The bottom line is, you need to decide what your goal in this is, learning, or functionality and find the happy medium between.</p>\n"
},
{
"answer_id": 293572,
"author": "Atiaxi",
"author_id": 2555346,
"author_profile": "https://Stackoverflow.com/users/2555346",
"pm_score": 1,
"selected": false,
"text": "<p>While not SDL specific, the <a href=\"http://nehe.gamedev.net/\" rel=\"nofollow noreferrer\">NeHe</a> OpenGL tutorials are an excellent place to start for learning about how to do 3D.</p>\n\n<p>If this is your first game, you'll probably want to aim lower than an FPS. Writing a simple 2D Tetris game using SDL will teach you everything you'll need to know about that library.</p>\n"
},
{
"answer_id": 297557,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Although the very long post is valueable in the long run, I feel it doesn't give the proper instant motivation of getting things on screen. Here's some facts, along with my opinion</p>\n\n<p>-SDL is a 2D graphics library, you can't write an FPS in 2D, therefore you have to go with a 3D library, either DirectX, or openGL</p>\n\n<p>-SDL has the ability to \"sync\" with openGL, using it for graphics, but there's not a whole lot of help online for that topic</p>\n\n<p>I suggest you go to Lazyfoo.net, which is an absolutly amazing beginner's resource for game programming with SDL, it shows you how to draw to the screen, but also teaches you how to apply this to programming games. After going through this, you'll be able to make a tetris clone, or most other 2D type games</p>\n\n<p>After this, you'll be ready for 3D(it's a lot more complex, requires a better grasp of math, and takes a lot more code to do simpler things) if you go with openGL, check out NeHe's Tutorials , they're currently working on a new set, using SDL with openGL, because the older tutorials, although valueable, are coded rather badly and use the windows(win32) API</p>\n\n<p>keep in mind, game development is one of the most demanding, and rewarding programming you'll come across, so good luck</p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24639/"
] |
I would like to know How to create a fps-game with SDL lib?
Are there any books that explain with examples?
|
this wins for most open ended question. You could literally write a book. But lets settle for pointing in the right direction...
Step one, you will need good debugging skills for a project like this. Pick up Code Complete by Steve McConnell. Read the whole thing. The time invested will pay for itself more than anything else you could read/experiment with.
Get your hands on some source code of some game. ANY game. Make sure you see something simple before you see something big and complex, and keep in mind when you look at any game code that they may have had a combined team put WAY more time into it than you will ever have. The point in this is to see code structure.
Get a reference for 3D math, doesn't have to be THAT in depth, but you will need to know stuff like dot products backwards and forwards, be able to figure out how to create the matrix for your camera in the world etc. (even if your writing 0% of the rendering code)
*(edit)* Here's a great book on 3D math[Mathematics for 3D Game Programming and Computer Graphics, Second Edition (Game Development Series)](https://rads.stackoverflow.com/amzn/click/com/1584502770) This isn't the kind you learn in college, it's more like a cross between trig and more advanced practical concepts: How to create a toolbox for yourself of simple physics, efficient collision detection, etc.
You will need to know something about rendering, and pipelines. SDL gives you a leg up, but make sure you understand the concepts of what it's doing.
Read up about practical system design. Your various systems will have to interlock. Think it out well. Your system can be just a good in C or in C++, it's the THOUGHT that is put into how your data/control will flow that will count, NOT how perfectly you emulate design patterns (though these are very useful as well of coarse)
Fundamentals of AI, not "real" AI, but functional AI; there is a big difference. State machines are great to start with, and sufficient for a simple FPS.
Learn a little about estimation and planning. You will not have time to do everything you would want to do to properly make an FPS. You will have to both triage AND learn how to triage; they are 2 separate things, the latter being mroe difficult. Experience is the best teacher here of coarse. (though the legendary McConnell has book on this as well)
Have a system to insert your gameplay into your level. If it is JUST you as a programmer, then your best bet is to write a plug in for an already existing editing program such as 3DS Max. I would highly recommend Max over Maya for a programmer. Maya script is nice, but it is more geared toward clever non-programmers. I find 3DS Max to think more along the lines of how a programmer would about creating and editing your world.
You can spend YEARS making tools to let you do this right, so you want to do things in such a way that you can edit fast and accurately
If you making your own editor, incorporate it into your game world.
If your world is not TRULY 3D and you want to make lots of level fast you can save your level data as something like this, which will save you a lot of time
Where X is a wall, the other letters are game objects which a dirt simple parser can translate into game objects and world coordinates
```
xxxxxxxxxxxxxxxxxxxxxxxx
xx..........P..........x
xxxxxxx...........I....x
xR....xxx...........E..x
xx.................0xxxx
xxxxxxxxxxxxxxxxxxxxxxxx
```
But it all depends on your game. My point is that you will need to resort to "ghetto coding" how you get your gameplay data into your world is very important and you need to think of something that is both fast for you to implement AND fast with you to work with.
And what it comes down to is what is your goal here? If it's to learn to code something the absolute right way, expect to spend most of your time iterating on code that seemed decent a month ago, but now that you realize what your requirements are, it could really use another pass. Do not be afraid to rewrite, you learn a lot by doing that, but if you goal is functionality, you will probably need to figure out where to hack some things in (like embedding gameplay data nad coordinates into code files) It *IS* ok to hack as long as you KNOW where you have hacked, and have carefully kept it separate from your good code so you can go back and properly write the code when you get the chance.
The bottom line is, you need to decide what your goal in this is, learning, or functionality and find the happy medium between.
|
288,178 |
<p>I have been trying to learn more about lambda expressions lately, and thought of a interesting exercise...</p>
<p>is there a way to simplify a c++ integration function like this:</p>
<pre><code>// Integral Function
double integrate(double a, double b, double (*f)(double))
{
double sum = 0.0;
// Evaluate integral{a,b} f(x) dx
for(int n = 0 ; n <= 100; ++n)
{
double x = a + n*(b-a)/100.0;
sum += (*f)(x) * (b-a)/101.0;
}
return sum;
}
</code></pre>
<p>by using c# and lambda expressions?</p>
|
[
{
"answer_id": 288311,
"author": "Christian C. SalvadΓ³",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 4,
"selected": true,
"text": "<p>What about this:</p>\n\n<pre><code>public double Integrate(double a,double b, Func<double, double> f)\n{\n double sum = 0.0;\n\n for (int n = 0; n <= 100; ++n)\n {\n double x = a + n * (b - a) / 100.0;\n sum += f(x) * (b - a) / 101.0;\n }\n return sum;\n}\n</code></pre>\n\n<p>Test:</p>\n\n<pre><code> Func<double, double> fun = x => Math.Pow(x,2); \n double result = Integrate(0, 10, fun);\n</code></pre>\n"
},
{
"answer_id": 288315,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 0,
"selected": false,
"text": "<p>The real power comes, as stated, when calling it. For example, in C#</p>\n\n<pre><code> static double Integrate(double a, double b, Func<double, double> func)\n {\n double sum = 0.0;\n\n // Evaluate integral{a,b} f(x) dx\n for(int n = 0 ; n <= 100; ++n)\n {\n double x = a + n*(b-a)/100.0;\n sum += func(x) * (b - a) / 101.0;\n }\n return sum;\n }\n</code></pre>\n\n<p>Then:</p>\n\n<pre><code> double value = Integrate(1,2,x=>x*x); // yields 2.335\n // expect C+(x^3)/3, i.e. 8/3-1/3=7/3=2.33...\n</code></pre>\n"
},
{
"answer_id": 288344,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 2,
"selected": false,
"text": "<p>Lambda Powa! Not sure whether this is right (No C# programmer! Just liking its lambda stuff)</p>\n\n<pre><code>(a, b, c) => {\n double sum = 0.0;\n Func<double, double> dox = (x) => a + x*(b-a)/100.0;\n\n // Evaluate integral{a,b} f(x) dx\n for(int n = 0 ; n <= 100; ++n)\n sum += c(dox(n)) * (b-a)/101.0;\n\n return sum;\n}\n</code></pre>\n\n<p>Ok, so i think while the code is C++, why not keep it C++ and get lambda in? Here it is how it looks for c++0x, being hopefully released as a Standard very soon :</p>\n\n<pre><code>static double Integrate(double a, double b, function<double(double)> f)\n{\n double sum = 0.0;\n\n // Evaluate integral{a,b} f(x) dx\n for(int n = 0; n < 100; ++n) {\n double x = a + n * (b - a) / 100.0;\n sum += f(x) * (b - a) / 101.0;\n }\n return sum;\n} \n\nint main() {\n Integrate(0, 1, [](double a) { return a * a; });\n}\n</code></pre>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have been trying to learn more about lambda expressions lately, and thought of a interesting exercise...
is there a way to simplify a c++ integration function like this:
```
// Integral Function
double integrate(double a, double b, double (*f)(double))
{
double sum = 0.0;
// Evaluate integral{a,b} f(x) dx
for(int n = 0 ; n <= 100; ++n)
{
double x = a + n*(b-a)/100.0;
sum += (*f)(x) * (b-a)/101.0;
}
return sum;
}
```
by using c# and lambda expressions?
|
What about this:
```
public double Integrate(double a,double b, Func<double, double> f)
{
double sum = 0.0;
for (int n = 0; n <= 100; ++n)
{
double x = a + n * (b - a) / 100.0;
sum += f(x) * (b - a) / 101.0;
}
return sum;
}
```
Test:
```
Func<double, double> fun = x => Math.Pow(x,2);
double result = Integrate(0, 10, fun);
```
|
288,192 |
<p>I'm writing Application A and DLL B, both in C#.NET. How do I do the following: </p>
<ol>
<li>A calls function in B </li>
<li>Want B to use delegate/callback to update status in UI of A </li>
</ol>
<p>This is <em>not</em> about BackgroundWorker...that part works fine in A. What I can't see is how to let B know what function to call in A.</p>
|
[
{
"answer_id": 288212,
"author": "Rob Prouse",
"author_id": 30827,
"author_profile": "https://Stackoverflow.com/users/30827",
"pm_score": 3,
"selected": false,
"text": "<p>You have two options. The most common is to have an event in B and have your UI in A subscribe to that event. B then fires that event.</p>\n\n<p>The second option is to pass in a delegate from A as a parameter to the method call in B. B can then Invoke that delegate.</p>\n"
},
{
"answer_id": 288216,
"author": "Brody",
"author_id": 17131,
"author_profile": "https://Stackoverflow.com/users/17131",
"pm_score": 1,
"selected": false,
"text": "<p>Pass in the callback object in the call A make to B. Use an interface (or tightly bound libraries). Make sure the callback object is thread aware and thread safe.</p>\n"
},
{
"answer_id": 288234,
"author": "Jeromy Irvine",
"author_id": 8223,
"author_profile": "https://Stackoverflow.com/users/8223",
"pm_score": 4,
"selected": false,
"text": "<p>To expand on Rob Prouse's answer, you need to declare a delegate and then pass a matching method into it.</p>\n\n<p>In B:</p>\n\n<pre><code>public delegate void CallbackDelegate(string status);\n\npublic void DoWork(string param, CallbackDelegate callback)\n{\n callback(\"status\");\n}\n</code></pre>\n\n<p>In A:</p>\n\n<pre><code>public void MyCallback(string status)\n{\n // Update your UI.\n}\n</code></pre>\n\n<p>And when you call the method:</p>\n\n<pre><code>B.DoWork(\"my params\", MyCallback);\n</code></pre>\n"
},
{
"answer_id": 288247,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 1,
"selected": false,
"text": "<p>If you control B, then Rob Prouse or Brody's answers will work fine.</p>\n\n<p>But what if you can't change B at all? In that case, you can always wrap a method in a delegate of your own making, as long it's signature matches that of the signature of the target method.</p>\n\n<p>So, say you have a class instance named B with a public method named b() (from the B dll assembly, of course). Class A in the A application can call it asynchronously like this:</p>\n\n<pre><code>public class A\n{\n delegate void BDelegate();\n\n public void BegineBMethod()\n {\n BDelegate b_method = new BDelegate(B.b);\n b_method.BeginInvoke(BCallback, null);\n }\n\n void BCallback(IAsyncResult ar)\n {\n // cleanup/get return value/check exceptions here\n }\n}\n</code></pre>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I'm writing Application A and DLL B, both in C#.NET. How do I do the following:
1. A calls function in B
2. Want B to use delegate/callback to update status in UI of A
This is *not* about BackgroundWorker...that part works fine in A. What I can't see is how to let B know what function to call in A.
|
To expand on Rob Prouse's answer, you need to declare a delegate and then pass a matching method into it.
In B:
```
public delegate void CallbackDelegate(string status);
public void DoWork(string param, CallbackDelegate callback)
{
callback("status");
}
```
In A:
```
public void MyCallback(string status)
{
// Update your UI.
}
```
And when you call the method:
```
B.DoWork("my params", MyCallback);
```
|
288,200 |
<p>We're having a bit of fun here at work. It all started with one of the guys setting up a Hackintosh and we were wondering whether it was faster than a Windows Box of (nearly) same specs that we have. So we decided to write a little test for it. Just a simple Prime number calculator. It's written in Java and tells us the time it takes to calculate the first n Prime numbers.</p>
<p>Optimised version below - now takes ~6.6secs</p>
<pre><code>public class Primes {
public static void main(String[] args) {
int topPrime = 150000;
int current = 2;
int count = 0;
int lastPrime = 2;
long start = System.currentTimeMillis();
while (count < topPrime) {
boolean prime = true;
int top = (int)Math.sqrt(current) + 1;
for (int i = 2; i < top; i++) {
if (current % i == 0) {
prime = false;
break;
}
}
if (prime) {
count++;
lastPrime = current;
}
if (current == 2) {
current++;
} else {
current = current + 2;
}
}
System.out.println("Last prime = " + lastPrime);
System.out.println("Total time = " + (double)(System.currentTimeMillis() - start) / 1000);
}
}
</code></pre>
<p>We've pretty much lost the plot of the whole Hackintosh vs PC thing and are just having some fun with optimising it. First attempt with no optimisations (the above code has a couple) ran around 52.6min to find the first 150000 prime numbers. This optimisation is running around 47.2mins.</p>
<p>If you want to have a go and post your results, then stick em up.</p>
<p>Specs for the PC I'm running it on are Pentium D 2.8GHz, 2GB RAM, running Ubuntu 8.04.</p>
<p><strong>Best Optimisation so far has been the square root of current, first mentioned by Jason Z.</strong></p>
|
[
{
"answer_id": 288252,
"author": "BP.",
"author_id": 36984,
"author_profile": "https://Stackoverflow.com/users/36984",
"pm_score": 1,
"selected": false,
"text": "<p>Keeping in mind that there are better ways to look for primes...</p>\n\n<p>I think that you can take this loop:</p>\n\n<blockquote>\n <p><code>for (int i = 2; i < top; i++)</code></p>\n</blockquote>\n\n<p>and make it so that your counter variable i goes from 3 and only tries to do the mod on odd numbers, since all primes other than 2 are never divisible by any even numbers.</p>\n"
},
{
"answer_id": 288263,
"author": "Sani Singh Huttunen",
"author_id": 26742,
"author_profile": "https://Stackoverflow.com/users/26742",
"pm_score": 4,
"selected": true,
"text": "<p>Well I see a couple of quick optimizations that can be done.\nFirst you don't have to try each number up to half of the current number.</p>\n\n<p>Instead you only have try up to the square root of the current number.</p>\n\n<p>And the other optimization was what BP said with a twist:\nInstead of</p>\n\n<pre><code>int count = 0;\n...\nfor (int i = 2; i < top; i++)\n...\nif (current == 2)\n current++;\nelse\n current += 2;\n</code></pre>\n\n<p>use</p>\n\n<pre><code>int count = 1;\n...\nfor (int i = 3; i < top; i += 2)\n...\ncurrent += 2;\n</code></pre>\n\n<p>This should speed things up quite a lot.</p>\n\n<p><strong>Edit:</strong><br>\nMore optimization courtesy of Joe Pineda:<br>\nRemove the variable \"top\". </p>\n\n<pre><code>int count = 1;\n...\nfor (int i = 3; i*i <= current; i += 2)\n...\ncurrent += 2;\n</code></pre>\n\n<p>If this optimization indeed increases speed is up to java.<br>\nCalculating the square root takes a lot of time compared to multiplying two numbers. However since we move the multiplication into the for loop this is done every single loop. So this COULD slow things down depending on how fast the square root algorithm in java is.</p>\n"
},
{
"answer_id": 288268,
"author": "Stephan Eggermont",
"author_id": 35306,
"author_profile": "https://Stackoverflow.com/users/35306",
"pm_score": 3,
"selected": false,
"text": "<p>That's a bit worse than my sieve did on a 8 Mhz 8088 in turbo pascal in 1986 or so. But that was after optimisations :)</p>\n"
},
{
"answer_id": 288309,
"author": "Robert J. Walker",
"author_id": 4287,
"author_profile": "https://Stackoverflow.com/users/4287",
"pm_score": 3,
"selected": false,
"text": "<p>Since you're searching for them in ascending order, you could keep a list of the primes you've already found and only check for divisibility against them, since all non-prime numbers can be reduced to a list of lesser prime factors. Combine that with the previous tip about not checking for factors over the square root of the current number, and you'll have yourself a pretty darn efficient implementation.</p>\n"
},
{
"answer_id": 288339,
"author": "Aistina",
"author_id": 37472,
"author_profile": "https://Stackoverflow.com/users/37472",
"pm_score": 2,
"selected": false,
"text": "<p>In C#:</p>\n\n<pre><code>class Program\n{\n static void Main(string[] args)\n {\n int count = 0;\n int max = 150000;\n int i = 2;\n\n DateTime start = DateTime.Now;\n while (count < max)\n {\n if (IsPrime(i))\n {\n count++;\n }\n\n i++;\n\n }\n DateTime end = DateTime.Now;\n\n Console.WriteLine(\"Total time taken: \" + (end - start).TotalSeconds.ToString() + \" seconds\");\n Console.ReadLine();\n }\n\n static bool IsPrime(int n)\n {\n if (n < 4)\n return true;\n if (n % 2 == 0)\n return false;\n\n int s = (int)Math.Sqrt(n);\n for (int i = 2; i <= s; i++)\n if (n % i == 0)\n return false;\n\n return true;\n }\n}\n</code></pre>\n\n<p>Output:</p>\n\n<p>Total time taken: 2.087 seconds</p>\n"
},
{
"answer_id": 288437,
"author": "Adam Tegen",
"author_id": 4066,
"author_profile": "https://Stackoverflow.com/users/4066",
"pm_score": 0,
"selected": false,
"text": "<p>C#</p>\n\n<p>Enhancement to <a href=\"https://stackoverflow.com/questions/288200/prime-number-calculation-fun#288339\">Aistina's code</a>:</p>\n\n<p>This makes use of the fact that all primes greater than 3 are of the form 6n + 1 or 6n - 1.</p>\n\n<p>This was about a 4-5% speed increase over incrementing by 1 for every pass through the loop.</p>\n\n<pre><code>class Program\n{ \n static void Main(string[] args)\n {\n DateTime start = DateTime.Now;\n\n int count = 2; //once 2 and 3\n\n int i = 5;\n while (count < 150000)\n {\n if (IsPrime(i))\n {\n count++;\n }\n\n i += 2;\n\n if (IsPrime(i))\n {\n count++;\n }\n\n i += 4;\n }\n\n DateTime end = DateTime.Now;\n\n Console.WriteLine(\"Total time taken: \" + (end - start).TotalSeconds.ToString() + \" seconds\");\n Console.ReadLine();\n }\n\n static bool IsPrime(int n)\n {\n //if (n < 4)\n //return true;\n //if (n % 2 == 0)\n //return false;\n\n int s = (int)Math.Sqrt(n);\n for (int i = 2; i <= s; i++)\n if (n % i == 0)\n return false;\n\n return true;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 288495,
"author": "avgbody",
"author_id": 8737,
"author_profile": "https://Stackoverflow.com/users/8737",
"pm_score": 1,
"selected": false,
"text": "<p>Does the re-declaration of the variable prime</p>\n\n<pre><code> while (count < topPrime) {\n\n boolean prime = true;\n</code></pre>\n\n<p>within the loop make it inefficient? (I assume it doesn't matter, since I would think Java would optimize this)</p>\n\n<pre><code>boolean prime; \nwhile (count < topPrime) {\n\n prime = true;\n</code></pre>\n"
},
{
"answer_id": 288669,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 0,
"selected": false,
"text": "<p>My take at optimization, avoiding too cryptic tricks. I use the trick given by I-GIVE-TERRIBLE-ADVICE, which I knew and forgot... :-)</p>\n\n<pre><code>public class Primes\n{\n // Original code\n public static void first()\n {\n int topPrime = 150003;\n int current = 2;\n int count = 0;\n int lastPrime = 2;\n\n long start = System.currentTimeMillis();\n\n while (count < topPrime) {\n\n boolean prime = true;\n\n int top = (int)Math.sqrt(current) + 1;\n\n for (int i = 2; i < top; i++) {\n if (current % i == 0) {\n prime = false;\n break;\n }\n }\n\n if (prime) {\n count++;\n lastPrime = current;\n// System.out.print(lastPrime + \" \"); // Checking algo is correct...\n }\n if (current == 2) {\n current++;\n } else {\n current = current + 2;\n }\n }\n\n System.out.println(\"\\n-- First\");\n System.out.println(\"Last prime = \" + lastPrime);\n System.out.println(\"Total time = \" + (double)(System.currentTimeMillis() - start) / 1000);\n }\n\n // My attempt\n public static void second()\n {\n final int wantedPrimeNb = 150000;\n int count = 0;\n\n int currentNumber = 1;\n int increment = 4;\n int lastPrime = 0;\n\n long start = System.currentTimeMillis();\n\nNEXT_TESTING_NUMBER:\n while (count < wantedPrimeNb)\n {\n currentNumber += increment;\n increment = 6 - increment;\n if (currentNumber % 2 == 0) // Even number\n continue;\n if (currentNumber % 3 == 0) // Multiple of three\n continue;\n\n int top = (int) Math.sqrt(currentNumber) + 1;\n int testingNumber = 5;\n int testIncrement = 2;\n do\n {\n if (currentNumber % testingNumber == 0)\n {\n continue NEXT_TESTING_NUMBER;\n }\n testingNumber += testIncrement;\n testIncrement = 6 - testIncrement;\n } while (testingNumber < top);\n // If we got there, we have a prime\n count++;\n lastPrime = currentNumber;\n// System.out.print(lastPrime + \" \"); // Checking algo is correct...\n }\n\n System.out.println(\"\\n-- Second\");\n System.out.println(\"Last prime = \" + lastPrime);\n System.out.println(\"Total time = \" + (double) (System.currentTimeMillis() - start) / 1000);\n }\n\n public static void main(String[] args)\n {\n first();\n second();\n }\n}\n</code></pre>\n\n<p>Yes, I used a labeled continue, first time I try them in Java...<br>\nI know I skip computation of the first few primes, but they are well known, no point to recompute them. :-) I can hard-code their output if needed! Beside, it doesn't give a decisive edge anyway.</p>\n\n<p>Results:</p>\n\n<p>-- First<br>\nLast prime = 2015201<br>\nTotal time = 4.281</p>\n\n<p>-- Second<br>\nLast prime = 2015201<br>\nTotal time = 0.953</p>\n\n<p>Not bad. Might be improved a bit, I suppose, but too much optimization can kill good code.</p>\n"
},
{
"answer_id": 288709,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 0,
"selected": false,
"text": "<p>You should be able to make the inner loop twice as fast by only evaluating the odd numbers. Not sure if this is valid Java, I'm used to C++, but I'm sure it can be adapted.</p>\n\n<pre><code> if (current != 2 && current % 2 == 0)\n prime = false;\n else {\n for (int i = 3; i < top; i+=2) {\n if (current % i == 0) {\n prime = false;\n break;\n }\n }\n }\n</code></pre>\n"
},
{
"answer_id": 296214,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I decided to try this in F#, my first decent attempt at it. Using the Sieve of Eratosthenes on my 2.2Ghz Core 2 Duo it runs through 2..150,000 in about 200 milliseconds. Each time it calls it self it's eliminated the current multiples from the list, so it just gets faster as it goes along. This is one of my first tries in F# so any constructive comments would be appreciated.</p>\n\n<pre><code>let max = 150000\nlet numbers = [2..max]\nlet rec getPrimes sieve max =\n match sieve with\n | [] -> sieve\n | _ when sqrt(float(max)) < float sieve.[0] -> sieve\n | _ -> let prime = sieve.[0]\n let filtered = List.filter(fun x -> x % prime <> 0) sieve // Removes the prime as well so the recursion works correctly.\n let result = getPrimes filtered max\n prime::result // The filter removes the prime so add it back to the primes result.\n\nlet timer = System.Diagnostics.Stopwatch()\ntimer.Start()\nlet r = getPrimes numbers max\ntimer.Stop()\nprintfn \"Primes: %A\" r\nprintfn \"Elapsed: %d.%d\" timer.Elapsed.Seconds timer.Elapsed.Milliseconds\n</code></pre>\n"
},
{
"answer_id": 296271,
"author": "Brian",
"author_id": 18192,
"author_profile": "https://Stackoverflow.com/users/18192",
"pm_score": 0,
"selected": false,
"text": "<p>I bet Miller-Rabin would be faster. If you test enough contiguous numbers it becomes deterministic, but I wouldn't even bother. Once a randomized algorithm reaches the point that its failure rate is equal to the likelihood that a CPU hiccup will cause a wrong result, it just doesn't matter any more. </p>\n"
},
{
"answer_id": 392265,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 2,
"selected": false,
"text": "<p>It takes us under a second (2.4GHz) to generate the first 150000 prime numbers in Python using Sieve of Eratosthenes:</p>\n\n<pre><code>#!/usr/bin/env python\ndef iprimes_upto(limit):\n \"\"\"Generate all prime numbers less then limit.\n\n http://stackoverflow.com/questions/188425/project-euler-problem#193605\n \"\"\"\n is_prime = [True] * limit\n for n in range(2, limit):\n if is_prime[n]:\n yield n\n for i in range(n*n, limit, n): # start at ``n`` squared\n is_prime[i] = False\n\ndef sup_prime(n):\n \"\"\"Return an integer upper bound for p(n).\n\n p(n) < n (log n + log log n - 1 + 1.8 log log n / log n)\n\n where p(n) is the n-th prime. \n http://primes.utm.edu/howmany.shtml#2\n \"\"\"\n from math import ceil, log\n assert n >= 13\n pn = n * (log(n) + log(log(n)) - 1 + 1.8 * log(log(n)) / log(n))\n return int(ceil(pn))\n\nif __name__ == '__main__':\n import sys\n max_number_of_primes = int(sys.argv[1]) if len(sys.argv) == 2 else 150000\n primes = list(iprimes_upto(sup_prime(max_number_of_primes)))\n print(\"Generated %d primes\" % len(primes))\n n = 100\n print(\"The first %d primes are %s\" % (n, primes[:n]))\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>$ python primes.py\n\nGenerated 153465 primes\nThe first 100 primes are [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, \n43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, \n127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197,\n199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281,\n283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379,\n383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463,\n467, 479, 487, 491, 499, 503, 509, 521, 523, 541]\n</code></pre>\n"
},
{
"answer_id": 423344,
"author": "Giovanni Galbo",
"author_id": 4050,
"author_profile": "https://Stackoverflow.com/users/4050",
"pm_score": 0,
"selected": false,
"text": "<p>Here's my solution... its fairly fast... it calculates the primes between 1 and 10,000,000 in 3 seconds on my machine (core i7 @ 2.93Ghz) on Vista64.</p>\n\n<p>My solution is in C, but I am not a professional C programmer. Feel free to criticize the algorithm and the code itself :)</p>\n\n<pre><code>#include<stdio.h>\n#include<math.h>\n#include<stdlib.h>\n#include<time.h>\n\n//5MB... allocate a lot of memory at once each time we need it\n#define ARRAYMULT 5242880 \n\n\n//list of calculated primes\n__int64* primes; \n//number of primes calculated\n__int64 primeCount;\n//the current size of the array\n__int64 arraySize;\n\n//Prints all of the calculated primes\nvoid PrintPrimes()\n{\n __int64 i;\n for(i=0; i<primeCount; i++)\n {\n printf(\"%d \", primes[i]);\n }\n\n}\n\n//Calculates all prime numbers to max\nvoid CalcPrime(__int64 max)\n{\n register __int64 i;\n double square;\n primes = (__int64*)malloc(sizeof(__int64) * ARRAYMULT);\n primeCount = 0;\n arraySize = ARRAYMULT;\n\n //we provide the first prime because its even, and it would be convenient to start\n //at an odd number so we can skip evens.\n primes[0] = 2;\n primeCount++;\n\n\n\n for(i=3; i<max; i+=2)\n {\n int j;\n square = sqrt((double)i);\n\n //only test the current candidate against other primes.\n for(j=0; j<primeCount; j++)\n {\n //prime divides evenly into candidate, so we have a non-prime\n if(i%primes[j]==0)\n break;\n else\n {\n //if we've reached the point where the next prime is > than the square of the\n //candidate, the candidate is a prime... so we can add it to the list\n if(primes[j] > square)\n {\n //our array has run out of room, so we need to expand it\n if(primeCount >= arraySize)\n {\n int k;\n __int64* newArray = (__int64*)malloc(sizeof(__int64) * (ARRAYMULT + arraySize));\n\n for(k=0; k<primeCount; k++)\n {\n newArray[k] = primes[k];\n }\n\n arraySize += ARRAYMULT;\n free(primes);\n primes = newArray;\n }\n //add the prime to the list\n primes[primeCount] = i;\n primeCount++;\n break;\n\n }\n }\n\n }\n\n }\n\n\n}\nint main()\n{\n int max;\n time_t t1,t2;\n double elapsedTime;\n\n printf(\"Enter the max number to calculate primes for:\\n\");\n scanf_s(\"%d\",&max);\n t1 = time(0);\n CalcPrime(max);\n t2 = time(0);\n elapsedTime = difftime(t2, t1);\n printf(\"%d Primes found.\\n\", primeCount);\n printf(\"%f seconds elapsed.\\n\\n\",elapsedTime);\n //PrintPrimes();\n scanf(\"%d\");\n return 1;\n}\n</code></pre>\n"
},
{
"answer_id": 1484967,
"author": "Nicholas Jordan",
"author_id": 177505,
"author_profile": "https://Stackoverflow.com/users/177505",
"pm_score": 0,
"selected": false,
"text": "<p>@ Mark Ransom - <em>not sure if this is java code</em> </p>\n\n<p>They will moan <em>possibly</em> but I wished to rewrite using paradigm I have learned to trust in Java and they said to have some fun, please make sure they understand that spec says nothing that effects ordering on the returned result set, also you would cast result set dot values() to a list type given my one-off in Notepad before taking a short errand </p>\n\n<p>=============== begin untested code ===============</p>\n\n<pre><code>package demo;\n\nimport java.util.List;\nimport java.util.HashSet;\n\nclass Primality\n{\n int current = 0;\n int minValue;\n private static final HashSet<Integer> resultSet = new HashSet<Integer>();\n final int increment = 2;\n // An obvious optimization is to use some already known work as an internal\n // constant table of some kind, reducing approaches to boundary conditions.\n int[] alreadyKown = \n {\n 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, \n 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, \n 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197,\n 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281,\n 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379,\n 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463,\n 467, 479, 487, 491, 499, 503, 509, 521, 523, 541\n };\n // Trivial constructor.\n\n public Primality(int minValue)\n {\n this.minValue = minValue;\n }\n List calcPrimes( int startValue )\n {\n // eliminate several hundred already known primes \n // by hardcoding the first few dozen - implemented \n // from prior work by J.F. Sebastian\n if( startValue > this.minValue )\n {\n // Duh.\n current = Math.abs( start );\n do\n {\n boolean prime = true;\n int index = current;\n do\n {\n if(current % index == 0)\n {\n // here, current cannot be prime so break.\n prime = false;\n break;\n }\n while( --index > 0x00000000 );\n\n // Unreachable if not prime\n // Here for clarity\n\n if ( prime )\n { \n resultSet dot add ( or put or whatever it is )\n new Integer ( current ) ;\n }\n }\n while( ( current - increment ) > this.minValue );\n // Sanity check\n if resultSet dot size is greater that zero\n {\n for ( int anInt : alreadyKown ) { resultSet.add( new Integer ( anInt ) );}\n return resultSet;\n }\n else throw an exception ....\n }\n</code></pre>\n\n<p>=============== end untested code ===============</p>\n\n<p>Using Hash Sets allows searching results as B-Trees, thus results could be stacked up until the machine begins to fail then that starting point could be used for another block of testing == the end of one run used as a Constructor value for another run, persisting to disk work already accomplished and allowing incremental feed-forward designs. Burnt out right now, loop logic needs analysis.</p>\n\n<p>patch (plus add sqrt) :</p>\n\n<pre><code> if(current % 5 == 0 )\n if(current % 7 == 0 )\n if( ( ( ( current % 12 ) +1 ) == 0) || ( ( ( current % 12 ) -1 ) == 0) ){break;}\n if( ( ( ( current % 18 ) +1 ) == 0) || ( ( ( current % 18 ) -1 ) == 0) ){break;}\n if( ( ( ( current % 24 ) +1 ) == 0) || ( ( ( current % 24 ) -1 ) == 0) ){break;}\n if( ( ( ( current % 36 ) +1 ) == 0) || ( ( ( current % 36 ) -1 ) == 0) ){break;}\n if( ( ( ( current % 24 ) +1 ) == 0) || ( ( ( current % 42 ) -1 ) == 0) ){break;}\n\n\n// and - new work this morning:\n\n\npackage demo;\n\n/**\n *\n * Buncha stuff deleted for posting .... duh.\n *\n * @author Author\n * @version 0.2.1\n *\n * Note strings are base36\n */\npublic final class Alice extends java.util.HashSet<java.lang.String>\n{\n // prints 14551 so it's 14 Β½ seconds to get 40,000 likely primes\n // using Java built-in on amd sempron 1.8 ghz / 1600 mhz front side bus 256 k L-2\n public static void main(java.lang.String[] args)\n {\n try\n {\n final long start=System.currentTimeMillis();\n // VM exhibits spurious 16-bit pointer behaviour somewhere after 40,000\n final java.lang.Integer upperBound=new java.lang.Integer(40000);\n int index = upperBound.intValue();\n\n final java.util.HashSet<java.lang.String>hashSet\n = new java.util.HashSet<java.lang.String>(upperBound.intValue());//\n // Arbitraily chosen value, based on no idea where to start.\n java.math.BigInteger probablePrime\n = new java.math.BigInteger(16,java.security.SecureRandom.getInstance(\"SHA1PRNG\"));\n do\n {\n java.math.BigInteger nextProbablePrime = probablePrime.nextProbablePrime();\n if(hashSet.add(new java.lang.String(nextProbablePrime.toString(Character.MAX_RADIX))))\n {\n probablePrime = nextProbablePrime;\n if( ( index % 100 ) == 0x00000000 )\n {\n // System.out.println(nextProbablePrime.toString(Character.MAX_RADIX));//\n continue;\n }\n else\n {\n continue;\n }\n }\n else\n {\n throw new StackOverflowError(new String(\"hashSet.add(string) failed on iteration: \"+\n Integer.toString(upperBound.intValue() - index)));\n }\n }\n while(--index > 0x00000000);\n System.err.println(Long.toString( System.currentTimeMillis() - start));\n }\n catch(java.security.NoSuchAlgorithmException nsae)\n {\n // Never happen\n return;\n }\n catch(java.lang.StackOverflowError soe)\n {\n // Might happen\n System.out.println(soe.getMessage());//\n return;\n }\n }\n}// end class Alice\n</code></pre>\n"
},
{
"answer_id": 1485311,
"author": "Naveen",
"author_id": 43594,
"author_profile": "https://Stackoverflow.com/users/43594",
"pm_score": 0,
"selected": false,
"text": "<p>Here is my take on it. The program is writtern in C and takes 50 milliseconds on my laptop(Core 2 Duo, 1 GB Ram). I am keeping all the calculated primes in an array and trying divisibility only till sqrt of number. Of course, this doesnt work when we need very large number of primes(tried with 100000000) as array grows too big and gives seg fault.</p>\n\n<pre><code>/*Calculate the primes till TOTALPRIMES*/\n#include <stdio.h>\n#define TOTALPRIMES 15000\n\nmain(){\nint primes[TOTALPRIMES];\nint count;\nint i, j, cpr;\nchar isPrime;\n\nprimes[0] = 2;\ncount = 1;\n\nfor(i = 3; count < TOTALPRIMES; i+= 2){\n isPrime = 1;\n\n //check divisiblity only with previous primes\n for(j = 0; j < count; j++){\n cpr = primes[j];\n if(i % cpr == 0){\n isPrime = 0;\n break;\n }\n if(cpr*cpr > i){\n break;\n }\n }\n if(isPrime == 1){\n //printf(\"Prime: %d\\n\", i);\n primes[count] = i;\n count++;\n }\n\n\n}\n\nprintf(\"Last prime = %d\\n\", primes[TOTALPRIMES - 1]);\n}\n</code></pre>\n\n<pre>\n$ time ./a.out \nLast prime = 163841\nreal 0m0.045s\nuser 0m0.040s\nsys 0m0.004s\n</pre>\n"
},
{
"answer_id": 2298622,
"author": "Steph L",
"author_id": 277225,
"author_profile": "https://Stackoverflow.com/users/277225",
"pm_score": 0,
"selected": false,
"text": "<p>I found this code somewhere on my machine when I started reading this blog entry about prime numbers.\nThe code is in C# and the algorithm I used came from my head although it is probably somewhere on Wikipedia. ;)\nAnyway, it can fetch the first 150000 prime numbers in about 300ms. I discovered that the sum of the n first odd numbers is equal to n^2. Again, there is probably a proof of this somewhere on wikipedia. So knowing this, I can write an algorithm that wil never have to calculate a square root but I have to calculate incrementally to find the primes. So if you want the Nth prime, this algo will have to find the (N-1) preceding primes before! So there it is. Enjoy!</p>\n\n<pre><code>\n//\n// Finds the n first prime numbers.\n//\n//count: Number of prime numbers to find.\n//listPrimes: A reference to a list that will contain all n first prime if getLast is set to false.\n//getLast: If true, the list will only contain the nth prime number.\n//\nstatic ulong GetPrimes(ulong count, ref IList listPrimes, bool getLast)\n{\n if (count == 0)\n return 0;\n if (count == 1)\n {\n if (listPrimes != null)\n {\n if (!getLast || (count == 1))\n listPrimes.Add(2);\n }\n\n return count;\n }\n\n ulong currentSquare = 1;\n ulong nextSquare = 9;\n ulong nextSquareIndex = 3;\n ulong primesCount = 1;\n\n List dividers = new List();\n\n //Only check for odd numbers starting with 3.\n for (ulong curNumber = 3; (curNumber (nextSquareIndex % div) == 0) == false)\n dividers.Add(nextSquareIndex);\n\n //Move to next square number\n currentSquare = nextSquare;\n\n //Skip the even dividers so take the next odd square number.\n nextSquare += (4 * (nextSquareIndex + 1));\n nextSquareIndex += 2;\n\n //We may continue as a square number is never a prime number for obvious reasons :).\n continue;\n }\n\n //Check if there is at least one divider for the current number.\n //If so, this is not a prime number.\n if (dividers.Exists(div => (curNumber % div) == 0) == false)\n {\n if (listPrimes != null)\n {\n //Unless we requested only the last prime, add it to the list of found prime numbers.\n if (!getLast || (primesCount + 1 == count))\n listPrimes.Add(curNumber);\n }\n primesCount++;\n }\n }\n\n return primesCount;\n}\n</code></pre>\n"
},
{
"answer_id": 7895077,
"author": "voidlogic",
"author_id": 1013460,
"author_profile": "https://Stackoverflow.com/users/1013460",
"pm_score": 3,
"selected": false,
"text": "<p>Here is a fast and simple solution:</p>\n\n<ul>\n<li>Finding primes less than 100000; 9592 were found in 5 ms</li>\n<li>Finding primes less than 1000000; 78498 were found in 20 ms</li>\n<li>Finding primes less than 10000000; 664579 were found in 143 ms</li>\n<li>Finding primes less than 100000000; 5761455 were found in 2024 ms</li>\n<li><p>Finding primes less than 1000000000; 50847534 were found in 23839 ms</p>\n\n<pre><code>//returns number of primes less than n\nprivate static int getNumberOfPrimes(final int n)\n{\n if(n < 2) \n return 0;\n BitSet candidates = new BitSet(n - 1);\n candidates.set(0, false);\n candidates.set(1, false);\n candidates.set(2, n);\n for(int i = 2; i < n; i++)\n if(candidates.get(i))\n for(int j = i + i; j < n; j += i)\n if(candidates.get(j) && j % i == 0)\n candidates.set(j, false); \n return candidates.cardinality();\n} \n</code></pre></li>\n</ul>\n"
},
{
"answer_id": 28639828,
"author": "thephpdev",
"author_id": 2529423,
"author_profile": "https://Stackoverflow.com/users/2529423",
"pm_score": 0,
"selected": false,
"text": "<p>Here's my contribution:</p>\n\n<p>Machine: 2.4GHz Quad-Core i7 w/ 8GB RAM @ 1600MHz</p>\n\n<p>Compiler: <code>clang++ main.cpp -O3</code></p>\n\n<p>Benchmarks:</p>\n\n<pre><code>Caelans-MacBook-Pro:Primer3 Caelan$ ./a.out 100\n\nCalculated 25 prime numbers up to 100 in 2 clocks (0.000002 seconds).\nCaelans-MacBook-Pro:Primer3 Caelan$ ./a.out 1000\n\nCalculated 168 prime numbers up to 1000 in 4 clocks (0.000004 seconds).\nCaelans-MacBook-Pro:Primer3 Caelan$ ./a.out 10000\n\nCalculated 1229 prime numbers up to 10000 in 18 clocks (0.000018 seconds).\nCaelans-MacBook-Pro:Primer3 Caelan$ ./a.out 100000\n\nCalculated 9592 prime numbers up to 100000 in 237 clocks (0.000237 seconds).\nCaelans-MacBook-Pro:Primer3 Caelan$ ./a.out 1000000\n\nCalculated 78498 prime numbers up to 1000000 in 3232 clocks (0.003232 seconds).\nCaelans-MacBook-Pro:Primer3 Caelan$ ./a.out 10000000\n\nCalculated 664579 prime numbers up to 10000000 in 51620 clocks (0.051620 seconds).\nCaelans-MacBook-Pro:Primer3 Caelan$ ./a.out 100000000\n\nCalculated 5761455 prime numbers up to 100000000 in 918373 clocks (0.918373 seconds).\nCaelans-MacBook-Pro:Primer3 Caelan$ ./a.out 1000000000\n\nCalculated 50847534 prime numbers up to 1000000000 in 10978897 clocks (10.978897 seconds).\nCaelans-MacBook-Pro:Primer3 Caelan$ ./a.out 4000000000\n\nCalculated 189961812 prime numbers up to 4000000000 in 53709395 clocks (53.709396 seconds).\nCaelans-MacBook-Pro:Primer3 Caelan$ \n</code></pre>\n\n<p>Source:</p>\n\n<pre><code>#include <iostream> // cout\n#include <cmath> // sqrt\n#include <ctime> // clock/CLOCKS_PER_SEC\n#include <cstdlib> // malloc/free\n\nusing namespace std;\n\nint main(int argc, const char * argv[]) {\n if(argc == 1) {\n cout << \"Please enter a number.\" << \"\\n\";\n return 1;\n }\n long n = atol(argv[1]);\n long i;\n long j;\n long k;\n long c;\n long sr;\n bool * a = (bool*)malloc((size_t)n * sizeof(bool));\n\n for(i = 2; i < n; i++) {\n a[i] = true;\n }\n\n clock_t t = clock();\n\n sr = sqrt(n);\n for(i = 2; i <= sr; i++) {\n if(a[i]) {\n for(k = 0, j = 0; j <= n; j = (i * i) + (k * i), k++) {\n a[j] = false;\n }\n }\n }\n\n t = clock() - t;\n\n c = 0;\n for(i = 2; i < n; i++) {\n if(a[i]) {\n //cout << i << \" \";\n c++;\n }\n }\n\n cout << fixed << \"\\nCalculated \" << c << \" prime numbers up to \" << n << \" in \" << t << \" clocks (\" << ((float)t) / CLOCKS_PER_SEC << \" seconds).\\n\";\n\n free(a);\n\n return 0;\n}\n</code></pre>\n\n<p>This uses the Sieve of Erastothenes approach, I've optimised it as much as I can with my knowledge. Improvements welcome.</p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288200",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18340/"
] |
We're having a bit of fun here at work. It all started with one of the guys setting up a Hackintosh and we were wondering whether it was faster than a Windows Box of (nearly) same specs that we have. So we decided to write a little test for it. Just a simple Prime number calculator. It's written in Java and tells us the time it takes to calculate the first n Prime numbers.
Optimised version below - now takes ~6.6secs
```
public class Primes {
public static void main(String[] args) {
int topPrime = 150000;
int current = 2;
int count = 0;
int lastPrime = 2;
long start = System.currentTimeMillis();
while (count < topPrime) {
boolean prime = true;
int top = (int)Math.sqrt(current) + 1;
for (int i = 2; i < top; i++) {
if (current % i == 0) {
prime = false;
break;
}
}
if (prime) {
count++;
lastPrime = current;
}
if (current == 2) {
current++;
} else {
current = current + 2;
}
}
System.out.println("Last prime = " + lastPrime);
System.out.println("Total time = " + (double)(System.currentTimeMillis() - start) / 1000);
}
}
```
We've pretty much lost the plot of the whole Hackintosh vs PC thing and are just having some fun with optimising it. First attempt with no optimisations (the above code has a couple) ran around 52.6min to find the first 150000 prime numbers. This optimisation is running around 47.2mins.
If you want to have a go and post your results, then stick em up.
Specs for the PC I'm running it on are Pentium D 2.8GHz, 2GB RAM, running Ubuntu 8.04.
**Best Optimisation so far has been the square root of current, first mentioned by Jason Z.**
|
Well I see a couple of quick optimizations that can be done.
First you don't have to try each number up to half of the current number.
Instead you only have try up to the square root of the current number.
And the other optimization was what BP said with a twist:
Instead of
```
int count = 0;
...
for (int i = 2; i < top; i++)
...
if (current == 2)
current++;
else
current += 2;
```
use
```
int count = 1;
...
for (int i = 3; i < top; i += 2)
...
current += 2;
```
This should speed things up quite a lot.
**Edit:**
More optimization courtesy of Joe Pineda:
Remove the variable "top".
```
int count = 1;
...
for (int i = 3; i*i <= current; i += 2)
...
current += 2;
```
If this optimization indeed increases speed is up to java.
Calculating the square root takes a lot of time compared to multiplying two numbers. However since we move the multiplication into the for loop this is done every single loop. So this COULD slow things down depending on how fast the square root algorithm in java is.
|
288,210 |
<p>I used to do this:</p>
<pre><code>SELECT layerID
FROM layers
WHERE ownerID = ?
AND collectionID = ?
</code></pre>
<p>Which would give me an array of layerID's, and then I'd loop and do this for each one:</p>
<pre><code>SELECT DATA
FROM drawings
WHERE layerID = ?
</code></pre>
<p>And it all worked fine. So now I'm trying to do it in one step, so I try this:</p>
<pre><code>SELECT DATA , layerID
FROM drawings
WHERE layerID = ANY (
SELECT layerID
FROM layers
WHERE ownerID = ?
AND collectionID = ?
)
</code></pre>
<p>But for some reason, it doesn't use the index, for the main query, <code>SELECT DATA etc</code>! So this one combined query takes much much longer to complete, versus the separate queries I was doing before. (By theway, the subquery, <code>SELECT layerID etc</code> still uses the index).</p>
<p>I've determined if it's using a query or not by using the 'EXPLAIN' statement.</p>
<p>I have individual indexes on the <code>ownerID</code> and <code>collectionID</code> columns in the <code>layers</code> table, and on the <code>layerID</code> column in the <code>drawings</code> table.</p>
<p>What am I doing wrong with my query?</p>
|
[
{
"answer_id": 288237,
"author": "dkretz",
"author_id": 31641,
"author_profile": "https://Stackoverflow.com/users/31641",
"pm_score": 4,
"selected": true,
"text": "<p>Try a join. ANY ends up looking a lot like an unoptimizable UNION to the query optimizer.</p>\n\n<pre><code>SELECT d.DATA, d.layerID \nFROM drawings AS d \nINNER JOIN layers AS l ON d.layerID = l.layerID \nWHERE l.ownerID = ? AND l.collectionID = ?\n</code></pre>\n"
},
{
"answer_id": 288380,
"author": "jishi",
"author_id": 33663,
"author_profile": "https://Stackoverflow.com/users/33663",
"pm_score": 0,
"selected": false,
"text": "<p>I have never seen the ANY keyword before, but if you try </p>\n\n<pre>\nSELECT DATA , layerID\nFROM drawings\nWHERE layerID IN (\n SELECT layerID\n FROM layers\n WHERE ownerID = ?\n AND collectionID = ?\n)\n</pre>\n\n<p>will that have the same problem? I believe it shouldn't. However, the INNER JOIN is probably a little bit better.</p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14569/"
] |
I used to do this:
```
SELECT layerID
FROM layers
WHERE ownerID = ?
AND collectionID = ?
```
Which would give me an array of layerID's, and then I'd loop and do this for each one:
```
SELECT DATA
FROM drawings
WHERE layerID = ?
```
And it all worked fine. So now I'm trying to do it in one step, so I try this:
```
SELECT DATA , layerID
FROM drawings
WHERE layerID = ANY (
SELECT layerID
FROM layers
WHERE ownerID = ?
AND collectionID = ?
)
```
But for some reason, it doesn't use the index, for the main query, `SELECT DATA etc`! So this one combined query takes much much longer to complete, versus the separate queries I was doing before. (By theway, the subquery, `SELECT layerID etc` still uses the index).
I've determined if it's using a query or not by using the 'EXPLAIN' statement.
I have individual indexes on the `ownerID` and `collectionID` columns in the `layers` table, and on the `layerID` column in the `drawings` table.
What am I doing wrong with my query?
|
Try a join. ANY ends up looking a lot like an unoptimizable UNION to the query optimizer.
```
SELECT d.DATA, d.layerID
FROM drawings AS d
INNER JOIN layers AS l ON d.layerID = l.layerID
WHERE l.ownerID = ? AND l.collectionID = ?
```
|
288,222 |
<p>In SQL Server (in my case, 2005) how can I add the identity property to an existing table column using T-SQL?</p>
<p>Something like:</p>
<pre><code>alter table tblFoo
alter column bar identity(1,1)
</code></pre>
|
[
{
"answer_id": 288273,
"author": "JohnFx",
"author_id": 30018,
"author_profile": "https://Stackoverflow.com/users/30018",
"pm_score": 6,
"selected": true,
"text": "<p>I don't beleive you can do that. Your best bet is to create a new identity column and copy the data over using an identity insert command (if you indeed want to keep the old values).</p>\n\n<p>Here is a decent article describing the process in detail:\n<a href=\"http://www.mssqltips.com/tip.asp?tip=1397\" rel=\"noreferrer\">http://www.mssqltips.com/tip.asp?tip=1397</a></p>\n"
},
{
"answer_id": 289901,
"author": "Robert",
"author_id": 27412,
"author_profile": "https://Stackoverflow.com/users/27412",
"pm_score": 2,
"selected": false,
"text": "<p>Is the table populated? If not drop and recreate the table.</p>\n\n<p>If it is populated what values already exist in the column? If they are values you don't want to keep.</p>\n\n<p>Create a new table as you desire it, load the records from your old table into your new talbe and let the database populate the identity column as normal. Rename your original table and rename the new one to the correct name :).</p>\n\n<p>Finally if the column you wish to make identity currently contains primary key values and is being referenced already by other tables you will need to totally re think if you're sure this is what you want to do :)</p>\n"
},
{
"answer_id": 590913,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<pre><code>alter table tablename \nalter column columnname \nadd Identity(100,1)\n</code></pre>\n"
},
{
"answer_id": 912795,
"author": "NateJ",
"author_id": 112764,
"author_profile": "https://Stackoverflow.com/users/112764",
"pm_score": 4,
"selected": false,
"text": "<p>The solution posted by Vikash doesn't work; it produces an \"Incorrect syntax\" error in SQL Management Studio (2005, as the OP specified). The fact that the \"Compact Edition\" of SQL Server supports this kind of operation is just a shortcut, because the real process is more like what Robert & JohnFX said--creating a duplicate table, populating the data, renaming the original & new tables appropriately.</p>\n\n<p>If you want to keep the values that already exist in the field that needs to be an identity, you could do something like this:</p>\n\n<pre><code>CREATE TABLE tname2 (etc.)\nINSERT INTO tname2 FROM tname1\n\nDROP TABLE tname1\nCREATE TABLE tname1 (with IDENTITY specified)\n\nSET IDENTITY_INSERT tname1 ON\nINSERT INTO tname1 FROM tname2\nSET IDENTITY_INSERT tname1 OFF\n\nDROP tname2\n</code></pre>\n\n<p>Of course, dropping and re-creating a table (tname1) that is used by <em>live code</em> is NOT recommended! :)</p>\n"
},
{
"answer_id": 41860419,
"author": "Milan",
"author_id": 1438675,
"author_profile": "https://Stackoverflow.com/users/1438675",
"pm_score": 2,
"selected": false,
"text": "<p>There is no direct way of doing this except:</p>\n\n<p><strong>A) through SQL</strong> i.e.:</p>\n\n<pre><code>-- make sure you have the correct CREATE TABLE script ready with IDENTITY\n\nSELECT * INTO abcTable_copy FROM abcTable\n\nDROP TABLE abcTable\n\nCREATE TABLE abcTable -- this time with the IDENTITY column\n\nSET IDENTITY_INSERT abcTable ON\n\nINSERT INTO abcTable (..specify all columns!) FROM (..specify all columns!) abcTable_copy\n\nSET INDENTITY_INSERT abcTable OFF\n\nDROP TABLE abcTable_copy \n\n-- I would suggest to verify the contents of both tables \n-- before dropping the copy table\n</code></pre>\n\n<p><strong>B) Through MSSMS</strong> which will do exactly the same in the background but will less fat-fingering.</p>\n\n<ul>\n<li>In the MSSMS Object Explorer right click the table you need to modify</li>\n<li>Select \"design\" Select the column you'd like to add IDENTITY to</li>\n<li>Change the identity setting from NO -> YES (possibly seed)</li>\n<li>Ctr+S the table</li>\n</ul>\n\n<p><a href=\"https://i.stack.imgur.com/bHbp7.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/bHbp7.png\" alt=\"enter image description here\"></a></p>\n\n<p>This will drop and recreate the table with all original data in it.\nIf you get a warning:</p>\n\n<p><a href=\"https://i.stack.imgur.com/6ccsz.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/6ccsz.png\" alt=\"enter image description here\"></a></p>\n\n<p>Go to MSSMS <strong>Tools -> Options -> Designers -> Table and database Designers</strong>\nand uncheck the option <strong><em>\"Prevent saving changes that require table re-creation\"</em></strong></p>\n\n<p><strong>Things to be careful about:</strong></p>\n\n<ol>\n<li>your DB has enough disk space before you do this</li>\n<li>the DB is not in use (especially the table you are changing)</li>\n<li>make sure to backup your DB before doing it</li>\n<li>if the table has a lot of data (over 1G) try it somewhere else first\nbefore using in real DB</li>\n</ol>\n"
},
{
"answer_id": 56885743,
"author": "Anuj Kumar",
"author_id": 11739011,
"author_profile": "https://Stackoverflow.com/users/11739011",
"pm_score": 2,
"selected": false,
"text": "<ol>\n<li><p>Create a New Table</p>\n\n<pre><code>SELECT * INTO Table_New FROM Table_Current WHERE 1 = 0;\n</code></pre></li>\n<li><p>Drop Column from New Table</p>\n\n<pre><code>Alter table Table_New drop column id;\n</code></pre></li>\n<li><p>Add column with identity</p>\n\n<pre><code>Alter table Table_New add id int primary key identity; \n</code></pre></li>\n<li><p>Get All Data in New Table</p>\n\n<pre><code>SET IDENTITY_INSERT Table_New ON;\nINSERT INTO Table_New (id, Name,CreatedDate,Modified) \nSELECT id, Name,CreatedDate,Modified FROM Table_Current;\nSET IDENTITY_INSERT Table_New OFF;\n</code></pre></li>\n<li><p>Drop old Table</p>\n\n<pre><code>drop table Table_Current;\n</code></pre></li>\n<li><p>Rename New Table as old One</p>\n\n<pre><code>EXEC sp_rename 'Table_New', 'Table_Current';\n</code></pre></li>\n</ol>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288222",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30529/"
] |
In SQL Server (in my case, 2005) how can I add the identity property to an existing table column using T-SQL?
Something like:
```
alter table tblFoo
alter column bar identity(1,1)
```
|
I don't beleive you can do that. Your best bet is to create a new identity column and copy the data over using an identity insert command (if you indeed want to keep the old values).
Here is a decent article describing the process in detail:
<http://www.mssqltips.com/tip.asp?tip=1397>
|
288,256 |
<p>I need to insert 20,000 rows in a single table (SQL Server 2005) using iBatis. What's the fastest way to do it ? I'm already using batch mode, but it didn't help much:</p>
<pre><code>try {
sqlMap.startTransaction();
sqlMap.startBatch();
// ... execute statements in between
sqlMap.commitTransaction();
} finally {
sqlMap.endTransaction();
}
</code></pre>
|
[
{
"answer_id": 288281,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 1,
"selected": false,
"text": "<p>Bulk inserts are best done using the database's own bulk loader tools. For Oracle, it's SQL*Loader, for example. Often these are faster than anything you could ever write.</p>\n"
},
{
"answer_id": 288367,
"author": "benPearce",
"author_id": 4490,
"author_profile": "https://Stackoverflow.com/users/4490",
"pm_score": 2,
"selected": false,
"text": "<p>Although this is not specific to your db server, I have previously had success writing the rows out to a local file in csv format and then having the database importing the file. This was considerably faster than insert statements or even a batch insert.</p>\n"
},
{
"answer_id": 288378,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": false,
"text": "<p>In SQL Server, the fasted way to insert records in batch is using <a href=\"http://msdn.microsoft.com/en-us/library/ms188365.aspx\" rel=\"nofollow noreferrer\">BULK INSERT</a>. However, this method loads the records from a text file rather than directly from your application.</p>\n\n<p>It also doesn't take into the account the time spent creating the file. You may have to weigh if that offsets any speed gains from the actual insert. Keep in mind that even if this is a little slower overall, you'll end up tying up your database server for less time.</p>\n\n<p>The only other thing you might try is inserting (staging) the batch into a completely different table (with no indexes or anything). Then move the record from that staging table to your target table and drop the staging table. This would move the data to server first, so that the final insert could all happen with sql server itself. But again: it's a two step process, so you'll have to count the time for both steps.</p>\n"
},
{
"answer_id": 288473,
"author": "Will Hartung",
"author_id": 13663,
"author_profile": "https://Stackoverflow.com/users/13663",
"pm_score": 2,
"selected": false,
"text": "<p>Barring the bulk loaders others are referring to, let's consider how to best do it through SQL. (And the bulk loaders don't work well if you're sending intermixed data to different tables.)</p>\n\n<p>First, you shouldn't be using whatever abstraction layer you're using, in this case iBatis, as it effectively will offer you little value, but that abstraction layer will have some (not necessarily much, but some) CPU cost. You should really simply use a raw database connection.</p>\n\n<p>Next, you'll be sending in a mess of INSERT statements. The question is whether you should use a simple string for the statment, (i.e. INSERT INTO TABLE1 VALUES('x','y', 12)) vs a prepared statement (INSERT INTO TABLE1 VALUES(?, ?, ?)).</p>\n\n<p>That will depend on your database and DB drivers.</p>\n\n<p>The issue with using a simple string, is basically the conversion cost from an internal format (assuming you're inserting Java data) to the string. Converting a number or date to a String is actually a reasonably expensive CPU operation. Some databases and drivers will work with the binary data directly, rather than simply the string data. So, in that case a PreparedStatement could net some CPU savings in potentially not having to convert the data.</p>\n\n<p>The downside is that this factor will vary by DB vendor, and potentially even the JDBC vendor. For example, Postgres (I believe) only works with SQL strings, rather than binary, so using a PreparedStatement is a waste over simply building the string yourself.</p>\n\n<p>Next, once you have your statement type, you want to use the <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/sql/Statement.html#addBatch(java.lang.String)\" rel=\"nofollow noreferrer\">addBatch</a>() method of the JDBC Statement class. What addBatch does is it groups up the SQL statements in to, well, a batch. The benefit is that instead of sending several requests to the DB, you send a single LARGE request. This cuts down on network traffic, and will give some noticeable gains in throughput.</p>\n\n<p>The detail is that not all drivers/databases support addBatch (at least not well), but also the size of your batch is limited. You most likely can't addBatch for all 20,000 rows and expect it to work, though that would be the best bet. This limit, also, can vary by database. </p>\n\n<p>For Oracle, in the past, I used a buffer of 64K. Basically I wrote a wrapper function that would take a literal INSERT statement, and accumulate them in 64K batches.</p>\n\n<p>So, if you wanted to bulk insert data through SQL via JDBC, those are the ways to do it. The big improvement is the Batch mode, the Statement vs PreparedStatement is more to potentially conserve some CPU, and maybe network traffic if your driver supports a binary protocol.</p>\n\n<p>Test, rinse, and repeat until you're happy enough.</p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288256",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7111/"
] |
I need to insert 20,000 rows in a single table (SQL Server 2005) using iBatis. What's the fastest way to do it ? I'm already using batch mode, but it didn't help much:
```
try {
sqlMap.startTransaction();
sqlMap.startBatch();
// ... execute statements in between
sqlMap.commitTransaction();
} finally {
sqlMap.endTransaction();
}
```
|
Although this is not specific to your db server, I have previously had success writing the rows out to a local file in csv format and then having the database importing the file. This was considerably faster than insert statements or even a batch insert.
|
288,277 |
<p>I have a JavaScript variable which holds an HTML page and due to the setup I need to extract everything between <code><div id="LiveArea"></code> and <code></div></code> from that variable using JavaScript.</p>
<p>Any help is greatly appreciated.</p>
|
[
{
"answer_id": 288297,
"author": "mmattax",
"author_id": 1638,
"author_profile": "https://Stackoverflow.com/users/1638",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not sure I follow you when you say, \"Javascript variable which holds an html page\", but If you need to extract the HTML between such a div, you can use the element's innerHTML property.</p>\n\n<pre>\n<code>\nvar e = document.getElementById('LiveArea');\nif(e) alert(e.innerHTML);\n\n</code>\n</pre>\n"
},
{
"answer_id": 288326,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 2,
"selected": false,
"text": "<p>This should do it:</p>\n\n<pre><code>pattern = /<div id=\"LiveArea\">(.*?)<\\/div>/;\nmatches = your_html_var.match(pattern);\nthe_string = matches[0];\n\ndocument.write(the_string);\n</code></pre>\n"
},
{
"answer_id": 288354,
"author": "Peter Bailey",
"author_id": 8815,
"author_profile": "https://Stackoverflow.com/users/8815",
"pm_score": 3,
"selected": false,
"text": "<p>This will not be possible with just a regular expression <em>unless</em> the HTML inside that div contains no other divs. Because what will happen with a pattern like Jeremy's is that it will match the first closing div tag, which wouldn't necessarily be the closing tag for the div#LiveArea element.</p>\n\n<p>If you have control over the source HTML, you could insert a comment that you could use to match on for the correct \"closing\" location.</p>\n\n<p>There are other javascript-only options, but they are each very kludgy or hacky</p>\n\n<ol>\n<li>Set the innerHTML of a hidden element equal to this string of content, THEN pull the innerHTML you need using mmattax's solution. But you will probably have to perform the 2nd step here with a timeout to give the browser time to evaluate this new HTML and expose it to the DOM.</li>\n<li>Actually parse the content, keeping track of opening/closing divs as you come across them so you will then know when you're at the correct <code></div></code> tag.</li>\n</ol>\n"
},
{
"answer_id": 288373,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 2,
"selected": false,
"text": "<pre><code>var temp = document.createElement('DIV');\ntemp.innerHTML = YourVariable;\nvar liveArea;\nfor (var i = 0; i < temp.childNodes.length; i++)\n{\n if (temp.childNodes[i].id == 'LiveArea')\n {\n liveArea = temp.childNodes[i];\n break;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 288534,
"author": "Nelson Miranda",
"author_id": 1130097,
"author_profile": "https://Stackoverflow.com/users/1130097",
"pm_score": 0,
"selected": false,
"text": "<p>I found this <a href=\"http://www.codeproject.com/KB/aspnet/PrintPreview.aspx\" rel=\"nofollow noreferrer\">article</a> surfing on the web which take a DIV id and shows it on a new page to print it;</p>\n\n<pre><code>function getPrint(print_area)\n{\n//Creating new page\nvar pp = window.open();\n//Adding HTML opening tag with <HEAD> β¦ </HEAD> portion \npp.document.writeln('<HTML><HEAD><title>Print Preview</title>')\npp.document.writeln('<LINK href=Styles.css type=\"text/css\" rel=\"stylesheet\">')\npp.document.writeln('<LINK href=PrintStyle.css ' + \n 'type=\"text/css\" rel=\"stylesheet\" media=\"print\">')\npp.document.writeln('<base target=\"_self\"></HEAD>')\n\n//Adding Body Tag\npp.document.writeln('<body MS_POSITIONING=\"GridLayout\" bottomMargin=\"0\"');\npp.document.writeln(' leftMargin=\"0\" topMargin=\"0\" rightMargin=\"0\">');\n//Adding form Tag\npp.document.writeln('<form method=\"post\">');\n\n//Creating two buttons Print and Close within a HTML table\npp.document.writeln('<TABLE width=100%><TR><TD></TD></TR><TR><TD align=right>');\npp.document.writeln('<INPUT ID=\"PRINT\" type=\"button\" value=\"Print\" ');\npp.document.writeln('onclick=\"javascript:location.reload(true);window.print();\">');\npp.document.writeln('<INPUT ID=\"CLOSE\" type=\"button\" ' + \n 'value=\"Close\" onclick=\"window.close();\">');\npp.document.writeln('</TD></TR><TR><TD></TD></TR></TABLE>');\n\n//Writing print area of the calling page\npp.document.writeln(document.getElementById(print_area).innerHTML);\n//Ending Tag of </form>, </body> and </HTML>\npp.document.writeln('</form></body></HTML>'); \n</code></pre>\n\n<p>}</p>\n\n<p>You will call this script sending the DIV id you want to get;</p>\n\n<pre><code>btnGet.Attributes.Add(\"Onclick\", \"getPrint('YOURDIV');\")\n</code></pre>\n\n<p>It worked exactly as I wanted. Hope it helps</p>\n"
},
{
"answer_id": 1106399,
"author": "Victor",
"author_id": 125946,
"author_profile": "https://Stackoverflow.com/users/125946",
"pm_score": 0,
"selected": false,
"text": "<p>it seems that javascript doesn't support lookbehinds which is very disapointing, that would make this problem so much easier to solve.</p>\n\n<p><code>(?<=<div id=\"LiveArea\">).*(?=<\\/div>)</code></p>\n\n<p>here are some links that might help out tho.</p>\n\n<ul>\n<li><a href=\"http://www.pagecolumn.com/tool/all_about_html_tags.htm\" rel=\"nofollow noreferrer\">matching html tags</a></li>\n<li><a href=\"http://blog.stevenlevithan.com/archives/mimic-lookbehind-javascript\" rel=\"nofollow noreferrer\">mimicking lookbehinds in javascript</a></li>\n</ul>\n\n<p>although while discussing the issue of nested tags... that would be beyond the abilities of regex to solve so jeremy's solution is the best you can do with regex. and what is more they have to be on a single line... it won't even match if the the contents of the div are on seperate lines because there is no 's' flag for javascript. I think peter has given the answer for this one.</p>\n"
},
{
"answer_id": 2482300,
"author": "Jonas",
"author_id": 297913,
"author_profile": "https://Stackoverflow.com/users/297913",
"pm_score": -1,
"selected": false,
"text": "<p>Sorry for late reply, if someone else stumbles on this problem here is my suggestion, assuming you have access to the page you are reading from source code.</p>\n\n<p>Add a HTML-comment like this</p>\n\n<pre><code><div id=\"LiveArea\">\n<!--LiveArea-->\nContent here\n<!--EndLiveArea-->\n</div>\n</code></pre>\n\n<p>Then match it with</p>\n\n<pre><code>htmlVal.match(/<\\!\\-\\-LiveArea\"\\-\\->(.*?)<\\!\\-\\-EndLiveArea\"\\-\\->/);\n</code></pre>\n"
},
{
"answer_id": 2482315,
"author": "Magnar",
"author_id": 1123,
"author_profile": "https://Stackoverflow.com/users/1123",
"pm_score": -1,
"selected": false,
"text": "<p>Let jQuery do the parsing for you:</p>\n\n<pre><code>$(page_html).find(\"#LiveArea\").html();\n</code></pre>\n"
},
{
"answer_id": 5360895,
"author": "SoSo",
"author_id": 667105,
"author_profile": "https://Stackoverflow.com/users/667105",
"pm_score": 4,
"selected": false,
"text": "<pre><code>var html = \"<stuff><div id=\\\"LiveArea\\\">hello stackoverflow!</div></stuff>\";\n\nvar matches = html.match(/<div\\s+id=\"LiveArea\">[\\S\\s]*?<\\/div>/gi);\nvar matches = matches[0].replace(/(<\\/?[^>]+>)/gi, ''); // Strip HTML tags?\n\nalert(matches);\n</code></pre>\n"
},
{
"answer_id": 27249563,
"author": "Supriya Gopalakrishnan",
"author_id": 4302960,
"author_profile": "https://Stackoverflow.com/users/4302960",
"pm_score": 0,
"selected": false,
"text": "<p>Use the following regular expression:</p>\n\n<pre><code><div id=\"[^\"]*\">(.*?)</div>\n</code></pre>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have a JavaScript variable which holds an HTML page and due to the setup I need to extract everything between `<div id="LiveArea">` and `</div>` from that variable using JavaScript.
Any help is greatly appreciated.
|
```
var html = "<stuff><div id=\"LiveArea\">hello stackoverflow!</div></stuff>";
var matches = html.match(/<div\s+id="LiveArea">[\S\s]*?<\/div>/gi);
var matches = matches[0].replace(/(<\/?[^>]+>)/gi, ''); // Strip HTML tags?
alert(matches);
```
|
288,282 |
<p>Here's some code I have:</p>
<pre><code>MyClass* MyClass::getInstance()
{
static MyClass instance;
return &instance;
}
</code></pre>
<p>I want to look into this singleton's current values. But I'm currently paused three hours into execution, and the reason I'm paused is that I'm out of memory. So I can't put a breakpoint in this method there to see what the value is.</p>
<p>My question then is how to refer to this <code>instance</code> variable from a global scope. I've tried referring to it as <code>MyClass::getInstance::instance</code> but that doesn't work. I'm guessing <code>getInstance</code> has to be decorated somehow. Anyone know how?</p>
<p>This is in Visual Studio 2008.</p>
|
[
{
"answer_id": 288329,
"author": "Nathan Kitchen",
"author_id": 31000,
"author_profile": "https://Stackoverflow.com/users/31000",
"pm_score": 1,
"selected": false,
"text": "<p>In gdb, you can put a watchpoint on the mangled name of the variable.</p>\n\n<p>For example, with this function:</p>\n\n<pre><code>int f() {\n static int xyz = 0;\n ++xyz;\n\n return xyz;\n}\n</code></pre>\n\n<p>I can watch _ZZ1fvE3xyz (as mangled by gcc 3.2.3 or gcc 4.0.1).</p>\n"
},
{
"answer_id": 289113,
"author": "kervin",
"author_id": 16549,
"author_profile": "https://Stackoverflow.com/users/16549",
"pm_score": 1,
"selected": false,
"text": "<p>That code just looks dangerous... :-)</p>\n\n<p>But anyway, your mangled name is going to depend on your <a href=\"http://www.codeproject.com/KB/cpp/calling_conventions_demystified.aspx\" rel=\"nofollow noreferrer\">Calling Convention</a> So before you find your mangle name you need to know what your build environment is using as the calling convention. MSDN has a lot more information on calling convention.</p>\n\n<p>Besides this, one way to find out all this information about your class is to inspect your VTable, which is found in the first 4 bytes of your object. A nifty trick that reversers use is a hidden VC++ Flag <a href=\"http://blogs.msdn.com/vcblog/archive/2007/05/17/diagnosing-hidden-odr-violations-in-visual-c-and-fixing-lnk2022.aspx\" rel=\"nofollow noreferrer\">reportSingleClassLayout</a> that prints the class structure in an ASCII art manner.</p>\n"
},
{
"answer_id": 292962,
"author": "bk1e",
"author_id": 8090,
"author_profile": "https://Stackoverflow.com/users/8090",
"pm_score": 4,
"selected": true,
"text": "<p>Well, the function-scoped static <code>instance</code> variable doesn't show up in a <code>.map</code> file generated by <code>cl.exe /Fm</code>, and it doesn't show up when I use <code>x programname!*MyClass*</code> in WinDbg, so the mangled name doesn't seem to contain <code>MyClass</code> at all.</p>\n\n<p><strong>Option 1: Disassemble <code>MyClass::getInstance</code></strong></p>\n\n<p>This approach seems easier:</p>\n\n<pre>\n0:000> uf programname!MyClass::getInstance\nprogramname!MyClass::getInstance [programname.cpp @ 14]:\n 14 00401050 55 push ebp\n 14 00401051 8bec mov ebp,esp\n 15 00401053 a160b34200 mov eax,dword ptr [programname!$S1 (0042b360)]\n 15 00401058 83e001 and eax,1\n 15 0040105b 7526 jne funcstat!MyClass::getInstance+0x33 (00401083)\n\nprogramname!MyClass::getInstance+0xd [programname.cpp @ 15]:\n 15 0040105d 8b0d60b34200 mov ecx,dword ptr [programname!$S1 (0042b360)]\n 15 00401063 83c901 or ecx,1\n 15 00401066 890d60b34200 mov dword ptr [programname!$S1 (0042b360)],ecx\n 15 0040106c b9b0be4200 mov ecx,offset programname!instance (0042beb0)\n 15 00401071 e88fffffff call programname!ILT+0(??0MyClassQAEXZ) (00401005)\n 15 00401076 68e03e4200 push offset programname!`MyClass::getInstance'::`2'::`dynamic atexit destructor for 'instance'' (00423ee0)\n 15 0040107b e8f3010000 call programname!atexit (00401273)\n 15 00401080 83c404 add esp,4\n\nprogramname!MyClass::getInstance+0x33 [programname.cpp @ 16]:\n 16 00401083 b8b0be4200 mov eax,offset programname!instance (0042beb0)\n 17 00401088 5d pop ebp\n 17 00401089 c3 ret\n</pre>\n\n<p>From this we can tell that the compiler called the object <code>$S1</code>. Of course, this name will depend on how many function-scoped static variables your program has.</p>\n\n<p><strong>Option 2: Search memory for the object</strong></p>\n\n<p>To expand on @gbjbaanb's suggestion, if <code>MyClass</code> has virtual functions, you might be able to find its location the hard way:</p>\n\n<ul>\n<li>Make a full memory dump of the process.</li>\n<li>Load the full memory dump into WinDbg.</li>\n<li>Use the <code>x</code> command to find the address of MyClass's vtable:</li>\n</ul>\n\n<pre>\n 0:000> x programname!MyClass::`vftable'\n 00425c64 programname!MyClass::`vftable' = \n</pre>\n\n<ul>\n<li>Use the <code>s</code> command to search the process's virtual address space (in this example, 0-2GB) for pointers to MyClass's vtable:</li>\n</ul>\n\n<pre>\n 0:000> s -d 0 L?7fffffff 00425c64\n 004010dc 00425c64 c35de58b cccccccc cccccccc d\\B...].........\n 0040113c 00425c64 8bfc458b ccc35de5 cccccccc d\\B..E...]......\n 0042b360 00425c64 00000000 00000000 00000000 d\\B.............\n</pre>\n\n<ul>\n<li>Use the <code>dt</code> command to find the class's vtable offset, and subtract that from the addresses returned from the search. These are possible addresses for the object.</li>\n</ul>\n\n<pre>\n 0:000> dt programname!MyClass\n +0x000 __VFN_table : Ptr32 \n +0x008 x : Int4B\n +0x010 y : Float\n</pre>\n\n<ul>\n<li>Use <code>dt programname!MyClass 0042b360</code> to examine the object's member variables, testing the hypothesis that the object is located at 0042b360 (or some other address). You will probably get some false positives, as I did above, but by inspecting the member variables you may be able to figure out which one is your singleton.</li>\n</ul>\n\n<p>This is a general technique for finding C++ objects, and is kind of overkill when you could just disassemble <code>MyClass::getInstance</code>.</p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4790/"
] |
Here's some code I have:
```
MyClass* MyClass::getInstance()
{
static MyClass instance;
return &instance;
}
```
I want to look into this singleton's current values. But I'm currently paused three hours into execution, and the reason I'm paused is that I'm out of memory. So I can't put a breakpoint in this method there to see what the value is.
My question then is how to refer to this `instance` variable from a global scope. I've tried referring to it as `MyClass::getInstance::instance` but that doesn't work. I'm guessing `getInstance` has to be decorated somehow. Anyone know how?
This is in Visual Studio 2008.
|
Well, the function-scoped static `instance` variable doesn't show up in a `.map` file generated by `cl.exe /Fm`, and it doesn't show up when I use `x programname!*MyClass*` in WinDbg, so the mangled name doesn't seem to contain `MyClass` at all.
**Option 1: Disassemble `MyClass::getInstance`**
This approach seems easier:
```
0:000> uf programname!MyClass::getInstance
programname!MyClass::getInstance [programname.cpp @ 14]:
14 00401050 55 push ebp
14 00401051 8bec mov ebp,esp
15 00401053 a160b34200 mov eax,dword ptr [programname!$S1 (0042b360)]
15 00401058 83e001 and eax,1
15 0040105b 7526 jne funcstat!MyClass::getInstance+0x33 (00401083)
programname!MyClass::getInstance+0xd [programname.cpp @ 15]:
15 0040105d 8b0d60b34200 mov ecx,dword ptr [programname!$S1 (0042b360)]
15 00401063 83c901 or ecx,1
15 00401066 890d60b34200 mov dword ptr [programname!$S1 (0042b360)],ecx
15 0040106c b9b0be4200 mov ecx,offset programname!instance (0042beb0)
15 00401071 e88fffffff call programname!ILT+0(??0MyClassQAEXZ) (00401005)
15 00401076 68e03e4200 push offset programname!`MyClass::getInstance'::`2'::`dynamic atexit destructor for 'instance'' (00423ee0)
15 0040107b e8f3010000 call programname!atexit (00401273)
15 00401080 83c404 add esp,4
programname!MyClass::getInstance+0x33 [programname.cpp @ 16]:
16 00401083 b8b0be4200 mov eax,offset programname!instance (0042beb0)
17 00401088 5d pop ebp
17 00401089 c3 ret
```
From this we can tell that the compiler called the object `$S1`. Of course, this name will depend on how many function-scoped static variables your program has.
**Option 2: Search memory for the object**
To expand on @gbjbaanb's suggestion, if `MyClass` has virtual functions, you might be able to find its location the hard way:
* Make a full memory dump of the process.
* Load the full memory dump into WinDbg.
* Use the `x` command to find the address of MyClass's vtable:
```
0:000> x programname!MyClass::`vftable'
00425c64 programname!MyClass::`vftable' =
```
* Use the `s` command to search the process's virtual address space (in this example, 0-2GB) for pointers to MyClass's vtable:
```
0:000> s -d 0 L?7fffffff 00425c64
004010dc 00425c64 c35de58b cccccccc cccccccc d\B...].........
0040113c 00425c64 8bfc458b ccc35de5 cccccccc d\B..E...]......
0042b360 00425c64 00000000 00000000 00000000 d\B.............
```
* Use the `dt` command to find the class's vtable offset, and subtract that from the addresses returned from the search. These are possible addresses for the object.
```
0:000> dt programname!MyClass
+0x000 __VFN_table : Ptr32
+0x008 x : Int4B
+0x010 y : Float
```
* Use `dt programname!MyClass 0042b360` to examine the object's member variables, testing the hypothesis that the object is located at 0042b360 (or some other address). You will probably get some false positives, as I did above, but by inspecting the member variables you may be able to figure out which one is your singleton.
This is a general technique for finding C++ objects, and is kind of overkill when you could just disassemble `MyClass::getInstance`.
|
288,289 |
<p>In Websphere when you do an LDAP query using LdapContext are the transmission of credentials encrypted?</p>
<pre><code>LdapContext ctx = new InitialLdapContext (env, null);
</code></pre>
<p>Lets say I make an LdapContext for a web app to do some custom LDAP calls.</p>
<p>How do I know if my call is secure / encrypted?</p>
|
[
{
"answer_id": 492381,
"author": "Michael Sharek",
"author_id": 1958,
"author_profile": "https://Stackoverflow.com/users/1958",
"pm_score": 3,
"selected": true,
"text": "<p>In order to secure/encrypt your LDAP calls you need to issue the \"Start TLS\" operation.</p>\n\n<p>Otherwise I think transport is plain text.</p>\n\n<p>For more:</p>\n\n<p><a href=\"http://java.sun.com/products/jndi/tutorial/ldap/ext/starttls.html\" rel=\"nofollow noreferrer\">http://java.sun.com/products/jndi/tutorial/ldap/ext/starttls.html</a></p>\n\n<p>Obviously the Java API is based on LDAP itself. So you could learn more about how the protocol itself handles it...i.e.:</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Ldap#StartTLS\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Ldap#StartTLS</a></p>\n"
},
{
"answer_id": 513151,
"author": "Patrick",
"author_id": 54396,
"author_profile": "https://Stackoverflow.com/users/54396",
"pm_score": 0,
"selected": false,
"text": "<p>Use ethereal or wireshark and snoop your LDAP connection to check if it is encrypted. If its encrypted then great, if not then try Michael Sharek's suggestion.</p>\n\n<p>If you find there is absolutely no way to setup encryption with code, then you can use stunnel. With stunnel you would make a unsecured connection to a port on the localhost, stunnel is listening on that port, encrypts everything with SSL and then sends the info to the LDAP server. Is very useful when using 3rd party apps that have no notion of network security.</p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30807/"
] |
In Websphere when you do an LDAP query using LdapContext are the transmission of credentials encrypted?
```
LdapContext ctx = new InitialLdapContext (env, null);
```
Lets say I make an LdapContext for a web app to do some custom LDAP calls.
How do I know if my call is secure / encrypted?
|
In order to secure/encrypt your LDAP calls you need to issue the "Start TLS" operation.
Otherwise I think transport is plain text.
For more:
<http://java.sun.com/products/jndi/tutorial/ldap/ext/starttls.html>
Obviously the Java API is based on LDAP itself. So you could learn more about how the protocol itself handles it...i.e.:
<http://en.wikipedia.org/wiki/Ldap#StartTLS>
|
288,294 |
<p>This may be too generic a question as is but...
I am stumped by trying to move through the directories from within a shell script. I'm not a *nix power user, but I am comfortable working through the command line for most tasks. I'd like to call a script that can move 'me' to a directory instead of just the script process similar to the following:</p>
<pre><code>prompt:> goto lit
</code></pre>
<p>where <code>goto</code> is an alias -> <code>goto='./goscript'</code><br>
and<br>
<code>goscript</code> has some simple code in such as:</p>
<pre><code>cd /path to work dirs/lit/user dir
</code></pre>
<p>(assuming each user has a directory inside /lit)</p>
<p>I've avoided this issue myself by setting my personal alias' to move to the desired directory, run a script, then return to the original directory. This question was brought to me by a co-worker who uses a similar method, but wanted to make the process more generic so we don't need to create every single alias we need.
I thought this would be an easy problem to solve, but I'm stumped as I don't really have a great deal of shell scripting experience ...as of yet. </p>
|
[
{
"answer_id": 288302,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 2,
"selected": false,
"text": "<p>You can't. The script has its own copy of the environment, and so it can't change the login shell's environment.</p>\n"
},
{
"answer_id": 288308,
"author": "Magus",
"author_id": 2188,
"author_profile": "https://Stackoverflow.com/users/2188",
"pm_score": 0,
"selected": false,
"text": "<p>You can't use cd in a bash script. You could alias the cd and path though.</p>\n\n<pre><code>alias goto='cd /path_to_work/usr/dir'\n</code></pre>\n\n<p>UPDATE: you would put that line in your .bashrc file and then do</p>\n\n<pre><code>source ~/.bashrc\n</code></pre>\n\n<p>to create the alias.</p>\n"
},
{
"answer_id": 288314,
"author": "Mitch Haile",
"author_id": 28807,
"author_profile": "https://Stackoverflow.com/users/28807",
"pm_score": 0,
"selected": false,
"text": "<p>You can accomplish some simple stuff like this using an alias. For example, I have some aliases that put me into a workspace environment and configure variables for our Makefile system. Here's a real alias I am using as an example. The '&&' will continue executing the commands until one of them fails--in simple scenarios like this, no clean-up is needed, since failure isn't likely.</p>\n\n<pre><code>alias main1='cd ~/code/main1 && export TOP=`pwd` && export DEBUG=1'\n</code></pre>\n\n<p>If you want to develop a shared library of aliases amongst your co-workers, you can share them over NFS and source the file to be included.</p>\n"
},
{
"answer_id": 288316,
"author": "Andrew Stein",
"author_id": 13029,
"author_profile": "https://Stackoverflow.com/users/13029",
"pm_score": 0,
"selected": false,
"text": "<p>Each script has its own idea of the current working directory. \"cd\" is not a process but a shell build-in.</p>\n\n<p>The way to do what you want is to create an alias. In csh it will be something like:</p>\n\n<pre><code>alias goto 'cd /path_to_work/\\!*/user_dir'\n</code></pre>\n\n<p>sh/bash have similar alias facilities</p>\n"
},
{
"answer_id": 288323,
"author": "Isak Savo",
"author_id": 8521,
"author_profile": "https://Stackoverflow.com/users/8521",
"pm_score": 3,
"selected": false,
"text": "<p>You can create a function that is called goto (or whatever) and make sure it is defined in your .bashrc (or you can \"source\" it from your current shell):</p>\n\n<pre><code>function goto {\n # the \"$USER\" part will expand to the current username\n # the \"$1\" will expand to the first argument to the function (\"goto xyz\" => $1 is \"xyz\")\n cd /some-path/lit/$USER/$1\n}\n</code></pre>\n\n<p>Put this in ~/.bashrc or in a separate file and call \"source the-file\" from your prompt then you can call the function just like any other program:</p>\n\n<pre><code>prompt> goto folder\n cd /some-path/lit/your-user/folder\n</code></pre>\n"
},
{
"answer_id": 288324,
"author": "Remo.D",
"author_id": 16827,
"author_profile": "https://Stackoverflow.com/users/16827",
"pm_score": 2,
"selected": false,
"text": "<p>To execute a script in the same environment of your prompt you have to invoke it with .</p>\n\n<p>Say you have the script named up:</p>\n\n<pre><code>cd .. \n</code></pre>\n\n<p>if you invoke it with . you get:</p>\n\n<pre><code>$> pwd\n$> /home/users/rd/proj\n$> . up\n$> pwd\n$> /home/users/rd\n</code></pre>\n"
},
{
"answer_id": 288337,
"author": "Sniggerfardimungus",
"author_id": 30997,
"author_profile": "https://Stackoverflow.com/users/30997",
"pm_score": 0,
"selected": false,
"text": "<p>I tend to have a couple dozen aliases in my .rc that look like this:</p>\n\n<pre><code>alias work='cd /home/foo/work'\nalias rails='cd /home/foo/rails'\nalias assets='cd /home/foo/rails/assets'\n</code></pre>\n\n<p>etc.</p>\n\n<p>If that isn't going to work for you, you might be able to use the debug hooks in bash to replace the command line in-place before it is executed - if the 'goto' keyword is the first thing on the line. This will involve googling around for 'trap' in bash, but be forewarned, such incantations do not behave the same on all systems. I wrote up one such experience a few months ago, and you're welcome to <a href=\"http://foodini.org/permalink.cgi?link=20080816\" rel=\"nofollow noreferrer\">the results</a>.</p>\n"
},
{
"answer_id": 288363,
"author": "Scott Wegner",
"author_id": 33791,
"author_profile": "https://Stackoverflow.com/users/33791",
"pm_score": 3,
"selected": false,
"text": "<p>Even better than using an alias as others have described, check out the <code>CDPATH</code> variable! It's basically equivalent of the <code>PATH</code> functionality, but applied to the <em>cd</em> command.</p>\n\n<p>For example, if I define my <code>CDPATH</code> as <code>$CDPATH:${HOME}/subdir</code>, and <code>~/subdir</code> contains another directory, <code>subsubdir</code>, then I can simply execute:</p>\n\n<pre><code>cd subsubdir\n</code></pre>\n\n<p>from any directory, and navigate the the path as expected.</p>\n\n<p>Here's some more specifics:</p>\n\n<p><a href=\"http://www.caliban.org/bash/#bashtips\" rel=\"nofollow noreferrer\">http://www.caliban.org/bash/#bashtips</a></p>\n\n<p>To set the <code>CDPATH</code> variable, add a line to your <code>.bashrc</code>, such as</p>\n\n<pre><code>export CDPATH=$CDPATH:${HOME}/subdir\n</code></pre>\n"
},
{
"answer_id": 478807,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I wasn't a member when I asked this (ironically my anonymous login question has higher flair than my official login questions combined), so I can't close it now - But- The Remo D. et al. answer would be the one that led to the working solution we needed. If anyone with mod powers can close this & select that as the accepted answer, i'd apprediate it. </p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
This may be too generic a question as is but...
I am stumped by trying to move through the directories from within a shell script. I'm not a \*nix power user, but I am comfortable working through the command line for most tasks. I'd like to call a script that can move 'me' to a directory instead of just the script process similar to the following:
```
prompt:> goto lit
```
where `goto` is an alias -> `goto='./goscript'`
and
`goscript` has some simple code in such as:
```
cd /path to work dirs/lit/user dir
```
(assuming each user has a directory inside /lit)
I've avoided this issue myself by setting my personal alias' to move to the desired directory, run a script, then return to the original directory. This question was brought to me by a co-worker who uses a similar method, but wanted to make the process more generic so we don't need to create every single alias we need.
I thought this would be an easy problem to solve, but I'm stumped as I don't really have a great deal of shell scripting experience ...as of yet.
|
You can create a function that is called goto (or whatever) and make sure it is defined in your .bashrc (or you can "source" it from your current shell):
```
function goto {
# the "$USER" part will expand to the current username
# the "$1" will expand to the first argument to the function ("goto xyz" => $1 is "xyz")
cd /some-path/lit/$USER/$1
}
```
Put this in ~/.bashrc or in a separate file and call "source the-file" from your prompt then you can call the function just like any other program:
```
prompt> goto folder
cd /some-path/lit/your-user/folder
```
|
288,298 |
<p>How much code documentation in your .NET source is too much?</p>
<p>Some background: I inherited a large codebase that I've talked about in some of the other questions I've posted here on SO. One of the "features" of this codebase is a God Class, a single static class with >3000 lines of code encompassing several dozen static methods. It's everything from <code>Utilities.CalculateFYBasedOnMonth()</code> to <code>Utilities.GetSharePointUserInfo()</code> to <code>Utilities.IsUserIE6()</code>. It's all good code that <a href="http://www.joelonsoftware.com/printerFriendly/articles/fog0000000069.html" rel="noreferrer">doesn't need to be rewritten</a>, just refactored into an appropriate set of libraries. I have that planned out.</p>
<p>Since these methods are moving into a new business layer, and my role on this project is to prepare the system for maintenance by other developers, I'm thinking about solid code documentation. While these methods all have good inline comments, they don't all have good (or any) code doco in the form of XML comments. Using a combo of GhostDoc and Sandcastle (or Document X), I can create some pretty nice HTML documentation and post it to SharePoint, which would let developers understand more about what the code does without navigating through the code itself.</p>
<p>As the amount of documentation in the code increases, the more difficult it becomes to navigate the code. I'm beginning to wonder if the XML comments will make the code more difficult to maintain than, say, a simpler <code>//comment</code> would on each method. </p>
<p>These examples are <a href="http://www.innovasys.com/products/dx2008/overview.aspx" rel="noreferrer">from the Document X sample</a>:</p>
<pre><code> /// <summary>
/// Adds a new %Customer:CustomersLibrary.Customer% to the collection.
/// </summary>
/// <returns>A new Customer instance that represents the new customer.</returns>
/// <example>
/// The following example demonstrates adding a new customer to the customers
/// collection.
/// <code lang="CS" title="Example">
/// CustomersLibrary.Customer newCustomer = myCustomers.Add(CustomersLibrary.Title.Mr, "John", "J", "Smith");
/// </code>
/// <code lang="VB" title="Example">
/// Dim newCustomer As CustomersLibrary.Customer = myCustomers.Add(CustomersLibrary.Title.Mr, "John", "J", "Smith")
/// </code>
/// </example>
/// <seealso cref="Remove">Remove Method</seealso>
/// <param name="Title">The customers title.</param>
/// <param name="FirstName">The customers first name.</param>
/// <param name="MiddleInitial">The customers middle initial.</param>
/// <param name="LastName">The customers last name.</param>
public Customer Add(Title Title, string FirstName, string MiddleInitial, string LastName)
{
// create new customer instance
Customer newCust = new Customer(Title, FirstName, MiddleInitial, LastName);
// add to internal collection
mItems.Add(newCust);
// return ref to new customer instance
return newCust;
}
</code></pre>
<p>And:</p>
<pre><code> /// <summary>
/// Returns the number of %Customer:CustomersLibrary.Customer% instances in the collection.
/// </summary>
/// <value>
/// An Int value that specifies the number of Customer instances within the
/// collection.
/// </value>
public int Count
{
get
{
return mItems.Count;
}
}
</code></pre>
<p>So I was wondering from you: do you document <strong>all</strong> of your code with XML comments with the goal of using something like NDoc (RIP) or Sandcastle? If not, how do you decide what gets documentation and what doesn't? Something like an API would obviously have doco, but what about a codebase that you're going to hand off to another team to maintain?</p>
<p>What do you think I should do?</p>
|
[
{
"answer_id": 288312,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Jeff has a really good article about commenting (or should I say, not commenting) here...</p>\n\n<p><a href=\"http://www.codinghorror.com/blog/archives/001150.html\" rel=\"nofollow noreferrer\">http://www.codinghorror.com/blog/archives/001150.html</a></p>\n\n<p>I know it seems like I'm not answering the question, but I think it's a valid point that code should be as self-documenting as possible.</p>\n"
},
{
"answer_id": 288331,
"author": "Pierre Arnaud",
"author_id": 4597,
"author_profile": "https://Stackoverflow.com/users/4597",
"pm_score": 1,
"selected": false,
"text": "<p>I tend to document all public methods in my own code; using GhostDoc makes this trivial. And in order to reduce the clutter when I edit my source code, I generally just collapse the comments by going first into \"outline mode\" (i.e. use Visual Studio's Outline > Collapse to definitions command).</p>\n\n<p>I've never tried Sandcastle, but I really appreciate the comfort provided by Intellisense for the methods I have XML-commented.</p>\n"
},
{
"answer_id": 288336,
"author": "Scott Wegner",
"author_id": 33791,
"author_profile": "https://Stackoverflow.com/users/33791",
"pm_score": 1,
"selected": false,
"text": "<p>I always opt for the XML / Javadoc format comments, because I love being able to browse API documentation in a sensible format (HTML usually).</p>\n\n<p>It does become a problem for browsing the actual source code, but I find that this is generally a minor issue, since Visual Studio is generally pretty smart about collapsing XML comments as necessary.</p>\n"
},
{
"answer_id": 288346,
"author": "Gabriel Isenberg",
"author_id": 1473493,
"author_profile": "https://Stackoverflow.com/users/1473493",
"pm_score": 0,
"selected": false,
"text": "<p>I've seen coding standards that recommend against commenting self-commenting code and method overloads. While YMMV, it sounds like a good way to get away from the \"Field _numberOfCars is an integer that represents the number of cars\"-type comments that lead into overkill.</p>\n"
},
{
"answer_id": 288370,
"author": "Jeff Kotula",
"author_id": 1382162,
"author_profile": "https://Stackoverflow.com/users/1382162",
"pm_score": 4,
"selected": true,
"text": "<p>I think a good part of the problem here is the verbose and crufty XML documentation syntax MS has foisted on us (JavaDoc wasn't much better either). The question of how to format it is, to a large degree, independent of how much is appropriate.</p>\n\n<p>Using the XML format for comments is optional. You can use DOxygen or other tools that recognize different formats. Or write your own document extractor -- it isn't as hard as you might think to do a reasonable job and is a good learning experience.</p>\n\n<p>The question of how much is more difficult. I think the idea of self-documenting code is fine, if you are digging in to maintain some code. If you are just a client, you shouldn't need to read the code to understand how a given function works. Lots of information is implicit in the data types and names, of course, but there is a great deal that is not. For instance, passing in a reference to an object tells you what is expected, but not how a null reference will be handled. Or in the OP's code, how any whitespace at the beginning or the end of the arguments are handled. I believe there is <em>far</em> more of this type of information that ought to be documented than is usually recognized.</p>\n\n<p>To me it requires natural language documentation to describe the purpose of the function as well as any pre- and post-conditions for the function, its arguments, and return values <em>which cannot be expressed through the programming language syntax</em>.</p>\n"
},
{
"answer_id": 288379,
"author": "Jim C",
"author_id": 21706,
"author_profile": "https://Stackoverflow.com/users/21706",
"pm_score": 0,
"selected": false,
"text": "<p>Comments in a header for generating documentation is a good thing. Putting comments in code to explain why you are doing what you are doing is also usually a good thing. Putting in redundant comments paraphrasing what you did is not a good thing</p>\n"
},
{
"answer_id": 288388,
"author": "Stephan Eggermont",
"author_id": 35306,
"author_profile": "https://Stackoverflow.com/users/35306",
"pm_score": 1,
"selected": false,
"text": "<p>Don't repeat yourself. </p>\n\n<ul>\n<li>The first example should have a better method name and no comments at all. </li>\n<li>The second example should not have a comment.</li>\n</ul>\n\n<p>The name of the first method should reflect that a new object is allocated.</p>\n\n<p>If that behavior is standard throughout the framework for each add, it should be documented on a higher level, not in this method API doc. Otherwise, change the name.</p>\n\n<p>Comments should add information, not hide it in noise. And there should be comments, where necessary in XML. And where they add value.</p>\n\n<p>I do not want to see:\n\"returns the count\" for a method named count.</p>\n"
},
{
"answer_id": 288406,
"author": "Xian",
"author_id": 4642,
"author_profile": "https://Stackoverflow.com/users/4642",
"pm_score": 0,
"selected": false,
"text": "<p>What you have shown is FAR TOO MUCH. Do your self a favour and delete it!</p>\n\n<p>Code should first off be self documenting, through meaningful method and parameter names. In the example you have shown; </p>\n\n<p>public Customer Add(Title Title, string FirstName, string MiddleInitial, string LastName) is perfectly understandable to the intent of what is happening, as is 'Count'.</p>\n\n<p>Commenting such as this, as you pointed out, is purely <strong>noise</strong> around what is otherwise easy to read code. Most developers will sooner open up examine and use the code, than pile through obscure auto-generated API documentation. Everytime!</p>\n"
},
{
"answer_id": 288599,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 2,
"selected": false,
"text": "<p>You're hitting a critical divide here between those that will be maintaining the new libraries and those that will be consuming the new libraries.</p>\n\n<p>If I'm writing a new application and will be using these standard libraries, I should be getting a stable binary of the libraries and simply importing them into my application, not copying the source code down from a location and potentially causing problems if the code gets modified. In that case, I won't have access to any of the \"self documenting\" features other than the name of the method and the input/output parameters, and even those won't be exposed if I'm using some kind of IDE that doesn't have the auto complete featured turned on.</p>\n\n<p>So in your example code above, I think it looks just fine. Things are not too verbose within the code itself and the names are self documenting. On the flip side, all of the necessary summary/parameter data is there so that a solid documentation piece could be constructed to allow those consuming the library to have all the critical information at their fingertips. Sadly XML is rather bloated, but by in large I think most developers can easily browse right by all the summary content and look into the actual code within the method.</p>\n"
},
{
"answer_id": 288604,
"author": "David Frenkel",
"author_id": 28747,
"author_profile": "https://Stackoverflow.com/users/28747",
"pm_score": 1,
"selected": false,
"text": "<p>All public functions must be clearly understandable by someone who has a passing familiarity with your code base, but NOT in your specific section without having to delve into the code.</p>\n\n<p>If you need to write a short line to explain what a function does, chances are you named your function/classes poorly. The name should be self explanatory in that case</p>\n\n<p>If it requires more than 1 brief sentence to explain, that's probably a good comment</p>\n\n<p>If it takes a paragraph, your function is probably doing too much besides likely unclear names.</p>\n\n<p>It's usually better to err on the side of comments <em>IF YOU MAKE SURE THEY ARE ACCURATE</em>. Inaccurate and/or unmaintainable comments are worse than no comments</p>\n\n<p>So applying these rules:</p>\n\n<p>In your first example: \"// create new customer instance\" is redundant. The code is crystal clear. THe other comments are perfect. They clarify what the code is operating upon/what it's resuls are</p>\n\n<p>In your second example the comments are wasted effort and make it hard to read. All you need to do is give the function a proper name. Not that vague \"count\". That is poor naming.</p>\n"
},
{
"answer_id": 288607,
"author": "Uri",
"author_id": 23072,
"author_profile": "https://Stackoverflow.com/users/23072",
"pm_score": 1,
"selected": false,
"text": "<p>I recently conducted a study that shows that if you have important \"directives \"e.g., Caller must do X\" within a lot of specifications (e.g., \"this method does X which means Y and Z\"), there is a very high risk that your readers would miss the directives. In fact, when they see a long documentation, they skip reading it alltogether.</p>\n\n<p>So at the least, separate the important stuff or use tagging (ask me if you use Java).</p>\n"
},
{
"answer_id": 288678,
"author": "Uri",
"author_id": 23072,
"author_profile": "https://Stackoverflow.com/users/23072",
"pm_score": 0,
"selected": false,
"text": "<p>By the way, according to \"Clean code\" (A great book, BTW), one should avoid using HTML/XML markups within comments that are embedded in the source code. Even if your IDE can create nifty documentation when you hover, it is considered too distracting and unreadable when you just browse your sources. </p>\n"
},
{
"answer_id": 288906,
"author": "Techgration",
"author_id": 35130,
"author_profile": "https://Stackoverflow.com/users/35130",
"pm_score": 1,
"selected": false,
"text": "<p>It all depends on the standards your company is using, but for my crew, we document at the top of every function like in your second example (which by the way you can do in Visual Studio 2008 by hitting the \"/\" key 3 times in a row at the top of any sub or function!!).</p>\n\n<p>The first example is overkill, especially the bottom couple of lines where each line is commented. However, I think the stuff at the header of the function might be useful though, because we use it here a lot. And it appears to be somewhat standard from what I can tell from lots of other programmers.</p>\n"
},
{
"answer_id": 560540,
"author": "Chris S",
"author_id": 21574,
"author_profile": "https://Stackoverflow.com/users/21574",
"pm_score": 3,
"selected": false,
"text": "<p>Nobody's mentioned your code doesn't need to be bloated, the XML documentation can be in another file:</p>\n\n<pre><code>/// <include file=\"Documentation/XML/YourClass.xml\" path=\"//documentation/members[@name='YourClass']/*\"/>\n</code></pre>\n\n<p>And then your Add method can contain no extra XML/comments above it, or if you prefer just the summary (as that's merged with the separate file).</p>\n\n<p>It's far more powerful than the rubbish format that is Javadoc and derivatives you find in PHP/Javascript (though Javadoc paved the way for the XML syntax). Plus the tools available are far superior and the default look of the help docs is more readable and easier to customise (I can say that from having written doclets and comparing that process to Sandcastle/DocProject/NDoc).</p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7565/"
] |
How much code documentation in your .NET source is too much?
Some background: I inherited a large codebase that I've talked about in some of the other questions I've posted here on SO. One of the "features" of this codebase is a God Class, a single static class with >3000 lines of code encompassing several dozen static methods. It's everything from `Utilities.CalculateFYBasedOnMonth()` to `Utilities.GetSharePointUserInfo()` to `Utilities.IsUserIE6()`. It's all good code that [doesn't need to be rewritten](http://www.joelonsoftware.com/printerFriendly/articles/fog0000000069.html), just refactored into an appropriate set of libraries. I have that planned out.
Since these methods are moving into a new business layer, and my role on this project is to prepare the system for maintenance by other developers, I'm thinking about solid code documentation. While these methods all have good inline comments, they don't all have good (or any) code doco in the form of XML comments. Using a combo of GhostDoc and Sandcastle (or Document X), I can create some pretty nice HTML documentation and post it to SharePoint, which would let developers understand more about what the code does without navigating through the code itself.
As the amount of documentation in the code increases, the more difficult it becomes to navigate the code. I'm beginning to wonder if the XML comments will make the code more difficult to maintain than, say, a simpler `//comment` would on each method.
These examples are [from the Document X sample](http://www.innovasys.com/products/dx2008/overview.aspx):
```
/// <summary>
/// Adds a new %Customer:CustomersLibrary.Customer% to the collection.
/// </summary>
/// <returns>A new Customer instance that represents the new customer.</returns>
/// <example>
/// The following example demonstrates adding a new customer to the customers
/// collection.
/// <code lang="CS" title="Example">
/// CustomersLibrary.Customer newCustomer = myCustomers.Add(CustomersLibrary.Title.Mr, "John", "J", "Smith");
/// </code>
/// <code lang="VB" title="Example">
/// Dim newCustomer As CustomersLibrary.Customer = myCustomers.Add(CustomersLibrary.Title.Mr, "John", "J", "Smith")
/// </code>
/// </example>
/// <seealso cref="Remove">Remove Method</seealso>
/// <param name="Title">The customers title.</param>
/// <param name="FirstName">The customers first name.</param>
/// <param name="MiddleInitial">The customers middle initial.</param>
/// <param name="LastName">The customers last name.</param>
public Customer Add(Title Title, string FirstName, string MiddleInitial, string LastName)
{
// create new customer instance
Customer newCust = new Customer(Title, FirstName, MiddleInitial, LastName);
// add to internal collection
mItems.Add(newCust);
// return ref to new customer instance
return newCust;
}
```
And:
```
/// <summary>
/// Returns the number of %Customer:CustomersLibrary.Customer% instances in the collection.
/// </summary>
/// <value>
/// An Int value that specifies the number of Customer instances within the
/// collection.
/// </value>
public int Count
{
get
{
return mItems.Count;
}
}
```
So I was wondering from you: do you document **all** of your code with XML comments with the goal of using something like NDoc (RIP) or Sandcastle? If not, how do you decide what gets documentation and what doesn't? Something like an API would obviously have doco, but what about a codebase that you're going to hand off to another team to maintain?
What do you think I should do?
|
I think a good part of the problem here is the verbose and crufty XML documentation syntax MS has foisted on us (JavaDoc wasn't much better either). The question of how to format it is, to a large degree, independent of how much is appropriate.
Using the XML format for comments is optional. You can use DOxygen or other tools that recognize different formats. Or write your own document extractor -- it isn't as hard as you might think to do a reasonable job and is a good learning experience.
The question of how much is more difficult. I think the idea of self-documenting code is fine, if you are digging in to maintain some code. If you are just a client, you shouldn't need to read the code to understand how a given function works. Lots of information is implicit in the data types and names, of course, but there is a great deal that is not. For instance, passing in a reference to an object tells you what is expected, but not how a null reference will be handled. Or in the OP's code, how any whitespace at the beginning or the end of the arguments are handled. I believe there is *far* more of this type of information that ought to be documented than is usually recognized.
To me it requires natural language documentation to describe the purpose of the function as well as any pre- and post-conditions for the function, its arguments, and return values *which cannot be expressed through the programming language syntax*.
|
288,304 |
<p>I have some .NET remoting code where a factory method, implemented in some server side class, returns interfaces to concrete objects, also executing on the very same server. .NET remoting automagically creates proxies and allows me to pass the interfaces across to the client, which can then call them directly.</p>
<p>Example interfaces:</p>
<pre><code>public interface IFactory
{
IFoo GetFoo();
}
public interface IFoo
{
void DoSomething();
}
</code></pre>
<p>Example client code:</p>
<pre><code>...
IFactory factory = (IFactory) System.Activator.GetObject (typeof (IFactory), url);
...
IFoo foo = factory.GetFoo (); // the server returns an interface; we get a proxy to it
foo.DoSomething ();
...
</code></pre>
<p>This all works great. However, now I am trying to migrate my code to WCF. I wonder if there is a means to pass around interfaces and having WCF generate the proxies on the fly on the client, as does the original .NET remoting.</p>
<p>And I don't want to return class instances, since I don't want to expose real classes. And serializing the full instance and sending it back and forth between the server and the client is not an option either. I really just want the client to talk to the server object through an interface pointer/proxy.</p>
<p>Any ideas?</p>
|
[
{
"answer_id": 288321,
"author": "jezell",
"author_id": 27453,
"author_profile": "https://Stackoverflow.com/users/27453",
"pm_score": 0,
"selected": false,
"text": "<p>The ChannelFactory class does exactly this, generates a proxy dynamically at runtime given an interface.</p>\n"
},
{
"answer_id": 288365,
"author": "Brian",
"author_id": 19299,
"author_profile": "https://Stackoverflow.com/users/19299",
"pm_score": 3,
"selected": true,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/aa730857%28VS.80%29.aspx#netremotewcf_topic6\" rel=\"nofollow noreferrer\">Use Sessions instead of Client-Activated Objects (MSDN)</a></p>\n"
},
{
"answer_id": 288425,
"author": "Pierre Arnaud",
"author_id": 4597,
"author_profile": "https://Stackoverflow.com/users/4597",
"pm_score": 1,
"selected": false,
"text": "<p>Sorry, jezell, I don't get it.</p>\n\n<p>Yes, I can use <code>ChannelFactory</code> on the client to create a proxy to <code>IFactory</code>, since that singleton object has been \"published\" by the server through an URI on the <code>ServiceHost</code>.</p>\n\n<p>But my <code>IFoo</code> instances on the server have not been associated with any <code>ServiceHost</code>; I just want to get them back by calling my <code>IFactory</code> proxy on the client, and let WCF do the call to the server <code>IFactory</code>, which would provide some <code>IFoo</code>, which would then be marshalled back to the client and wrapped into a dynamically generated proxy. I really just want to be able to write <code>factory.GetFoo ();</code> on my client...</p>\n\n<p>In the meantime, Brian pointed me to a very interesting document I had overlooked on MSDN, which explains how to mimmick the .NET Remoting interface marshalling by using sessions and <code>EndPointAddress10</code> and ... as you wrote, <code>ChannelFactory</code> to get the client side proxies.</p>\n\n<p>So, now I know how to replicate my .NET remoting code, but paying a relatively high cost for it. The code complexity involved with WCF is quite a bit higher than with the plain old .NET remoting solution.</p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4597/"
] |
I have some .NET remoting code where a factory method, implemented in some server side class, returns interfaces to concrete objects, also executing on the very same server. .NET remoting automagically creates proxies and allows me to pass the interfaces across to the client, which can then call them directly.
Example interfaces:
```
public interface IFactory
{
IFoo GetFoo();
}
public interface IFoo
{
void DoSomething();
}
```
Example client code:
```
...
IFactory factory = (IFactory) System.Activator.GetObject (typeof (IFactory), url);
...
IFoo foo = factory.GetFoo (); // the server returns an interface; we get a proxy to it
foo.DoSomething ();
...
```
This all works great. However, now I am trying to migrate my code to WCF. I wonder if there is a means to pass around interfaces and having WCF generate the proxies on the fly on the client, as does the original .NET remoting.
And I don't want to return class instances, since I don't want to expose real classes. And serializing the full instance and sending it back and forth between the server and the client is not an option either. I really just want the client to talk to the server object through an interface pointer/proxy.
Any ideas?
|
[Use Sessions instead of Client-Activated Objects (MSDN)](http://msdn.microsoft.com/en-us/library/aa730857%28VS.80%29.aspx#netremotewcf_topic6)
|
288,319 |
<p>I realized the solution to this problem while I was creating the documentation to ASK this question...so I am posting the answer if for no other reason than to keep me from wasting time on this in the future</p>
|
[
{
"answer_id": 288328,
"author": "Jay Corbett",
"author_id": 2755,
"author_profile": "https://Stackoverflow.com/users/2755",
"pm_score": 2,
"selected": false,
"text": "<p>If the content to be TOGGLEd is displayed (visible) when the page is rendered the functions would be in the following order, if the content is hidden originally then reverse the functions</p>\n\n<pre><code><html>\n<head>\n<style>\n #upperDiv {width:200px; height:20px; text-align:center; cursor:pointer; }\n #lowerDiv {width:200px; height:20px; background-color:red; border:#206ba4 1px solid;}\n</style>\n\n<script language=\"Javascript\" src=\"javascript/jquery-1.2.6.min.js\"></script>\n<script type=\"text/JavaScript\">\n\n$(function(){\n$('#upperDiv').toggle (\n function(){ \n $(\"#lowerDiv\").hide() ; \n },\n function(){ \n $(\"#lowerDiv\").show() ; \n }\n); // End toggle\n }); // End eventlistener\n\n</script>\n</head>\n<body>\n<div id=\"upperDiv\" >Upper div</div>\n<div id=\"lowerDiv\" >Lover Div</div>\n</body>\n</html>\n</code></pre>\n"
},
{
"answer_id": 288345,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 3,
"selected": true,
"text": "<p><code>toggle()</code> is pretty buggy at times, i've had it do odd things to checkmarks (unchecking them) and other assorted issues. i'd suggest just handling it using a click event, much less minor annoyances. and this way, you don't have to worry about what state <code>#lowerDiv</code> is in in the first place:</p>\n\n<pre><code>$('#upperDiv').click(function() {\n $('#lowerDiv').animate({\n 'opacity' : 'toggle',\n });\n});\n</code></pre>\n"
},
{
"answer_id": 47716274,
"author": "thvs86",
"author_id": 6094194,
"author_profile": "https://Stackoverflow.com/users/6094194",
"pm_score": 0,
"selected": false,
"text": "<p>I know this is a really old question, but just for people that are looking for a quick fix this worked for me:</p>\n\n<p>a. in the PHP/HTML file:</p>\n\n<pre><code><script src=\"https://ajax.googleapis.com/ajax/libs/jquery/.../jquery.min.js\"></script>\n <script>\n $(document).ready(function(){\n $(\"#pClick\").click(function(){ \n $(\"#pText\").toggle();\n $(\"#pText\").text(\"...\");\n });\n });\n </script>\n</code></pre>\n\n<p>b. in the CSS file:</p>\n\n<pre><code>#pText {display: none;}\n</code></pre>\n\n<p>It now works even on the first click. It's a simple, quick answer that I hope will be useful.</p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2755/"
] |
I realized the solution to this problem while I was creating the documentation to ASK this question...so I am posting the answer if for no other reason than to keep me from wasting time on this in the future
|
`toggle()` is pretty buggy at times, i've had it do odd things to checkmarks (unchecking them) and other assorted issues. i'd suggest just handling it using a click event, much less minor annoyances. and this way, you don't have to worry about what state `#lowerDiv` is in in the first place:
```
$('#upperDiv').click(function() {
$('#lowerDiv').animate({
'opacity' : 'toggle',
});
});
```
|
288,357 |
<p>So if I have:</p>
<pre><code>public class ChildClass : BaseClass
{
public new virtual string TempProperty { get; set; }
}
public class BaseClass
{
public virtual string TempProperty { get; set; }
}
</code></pre>
<p>How can I use reflection to see that ChildClass is hiding the Base implementation of TempProperty?</p>
<p>I'd like the answer to be agnostic between c# and vb.net</p>
|
[
{
"answer_id": 288372,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": -1,
"selected": false,
"text": "<p>Correction, if you are using VB the property you are looking for is \"IsHideBySig\". This will be false in the case that the \"new\" keyword was used to define a method/property.</p>\n\n<p>In the C# case, both instances are outputted as \"hidebysig\". Thanks for pointing that out Greg. I didn't realize I only tested this in VB. Here's sample VB code that will repro this behavior. </p>\n\n<pre><code>Module Module1\n\n Class Foo\n Public Function SomeFunc() As Integer\n Return 42\n End Function\n End Class\n\n Class Bar\n Inherits Foo\n Public Shadows Function SomeFunc() As Integer\n Return 36\n End Function\n End Class\n\n Sub Main()\n Dim type = GetType(Bar)\n Dim func = type.GetMethod(\"SomeFunc\")\n Stop\n End Sub\n\nEnd Module\n</code></pre>\n"
},
{
"answer_id": 288579,
"author": "Coincoin",
"author_id": 42,
"author_profile": "https://Stackoverflow.com/users/42",
"pm_score": 0,
"selected": false,
"text": "<p>I never did what you are trying to do but MethodInfo.GetBaseDefinition() method seems to be what you are looking for.</p>\n\n<p>It returns the MethodInfo this method is overriding.</p>\n\n<p>From MSDN :</p>\n\n<blockquote>\n <p>If a given method is specified with the new keyword (as in newslot as described in Type Members), the given method is returned.</p>\n</blockquote>\n"
},
{
"answer_id": 288714,
"author": "Tinister",
"author_id": 34715,
"author_profile": "https://Stackoverflow.com/users/34715",
"pm_score": 3,
"selected": false,
"text": "<p>Doesn't look like reflection will give this to you by default so you'll have to roll your own:</p>\n\n<pre><code>public static bool IsHidingMember( this PropertyInfo self )\n{\n Type baseType = self.DeclaringType.BaseType;\n PropertyInfo baseProperty = baseType.GetProperty( self.Name, self.PropertyType );\n\n if ( baseProperty == null )\n {\n return false;\n }\n\n if ( baseProperty.DeclaringType == self.DeclaringType )\n {\n return false;\n }\n\n var baseMethodDefinition = baseProperty.GetGetMethod().GetBaseDefinition();\n var thisMethodDefinition = self.GetGetMethod().GetBaseDefinition();\n\n return baseMethodDefinition.DeclaringType != thisMethodDefinition.DeclaringType;\n}\n</code></pre>\n\n<p>Not sure how this will work with indexed properties, however!</p>\n"
},
{
"answer_id": 288928,
"author": "Greg Beech",
"author_id": 13552,
"author_profile": "https://Stackoverflow.com/users/13552",
"pm_score": 6,
"selected": true,
"text": "<p>We'll have to deal in terms of the methods of the property here rather than the property itself, because it is the get/set methods of the property that actually get overridden rather than the property itself. I'll use the get method as you should never have a property without one, though a complete solution should check for the lack of one.</p>\n\n<p>Looking at the IL emitted in a number of cases, the 'get' method of the base property will have the metadata tokens (this is from the C# compiler; others may not emit the <code>hidebysig</code> depending on their method hiding semantics, in which case the method would be hide-by-name):</p>\n\n<pre><code>non-virtual : .method public hidebysig specialname instance\nvirtual : .method public hidebysig specialname newslot virtual instance \n</code></pre>\n\n<p>The derived one will have the following tokens:</p>\n\n<pre><code>override : .method public hidebysig specialname virtual instance \nnew : .method public hidebysig specialname instance\nnew virtual : .method public hidebysig specialname newslot virtual instance \n</code></pre>\n\n<p>So we can see from this that it isn't possible to tell purely from the method's metadata tokens whether it is <code>new</code> because the non-virtual base method has the same tokens as the non-virtual <code>new</code> method, and the virtual base method has the same tokens as the <code>new virtual</code> method.</p>\n\n<p>What we <em>can</em> say is that if the method has the <code>virtual</code> token but not the <code>newslot</code> token then it overrides a base method rather than shadows it, i.e.</p>\n\n<pre><code>var prop = typeof(ChildClass).GetProperty(\"TempProperty\");\nvar getMethod = prop.GetGetMethod();\nif ((getMethod.Attributes & MethodAttributes.Virtual) != 0 &&\n (getMethod.Attributes & MethodAttributes.NewSlot) == 0)\n{\n // the property's 'get' method is an override\n}\n</code></pre>\n\n<p>Assuming, then, that we find the 'get' method is not an override, we want to know whether there is a property in the base class that it is shadowing. The problem is that because the method is in a different method table slot, it doesn't actually have any direct relationship to the method it is shadowing. So what we're actually saying is \"does the base type have any method which meets the criteria for shadowing\", which varies depending on whether the method is <code>hidebysig</code> or hide-by-name. </p>\n\n<p>For the former we need to check whether the base class has any method which matches the signature exactly, whereas for the latter we need to check whether it has any method with the same name, so continuing the code from above:</p>\n\n<pre><code>else \n{\n if (getMethod.IsHideBySig)\n {\n var flags = getMethod.IsPublic ? BindingFlags.Public : BindingFlags.NonPublic;\n flags |= getMethod.IsStatic ? BindingFlags.Static : BindingFlags.Instance;\n var paramTypes = getMethod.GetParameters().Select(p => p.ParameterType).ToArray();\n if (getMethod.DeclaringType.BaseType.GetMethod(getMethod.Name, flags, null, paramTypes, null) != null)\n {\n // the property's 'get' method shadows by signature\n }\n }\n else\n {\n var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance;\n if (getMethod.DeclaringType.BaseType.GetMethods(flags).Any(m => m.Name == getMethod.Name))\n {\n // the property's 'get' method shadows by name\n }\n }\n}\n</code></pre>\n\n<p>I think this is most of the way there, but I still don't think it's exactly right. For a start I'm not totally familiar with hiding by name as C# doesn't support it and that's pretty much all I use, so I may be wrong in the code here that indicates an instance method could shadow a static one. I also don't know about the case sensitivity issue (e.g. in VB could a method called <code>Foo</code> shadow a method called <code>foo</code> if they both had the same signature and were both <code>hidebysig</code> - in C# the answer is no but if the answer is yes in VB then it means the answer to this question is actually nondeterministic).</p>\n\n<p>Well, I'm not sure how much help all this is, other than to illustrate that it's actually a much harder problem than I thought it would be (or I've missed something really obvious in which case I'd like to know!). But hopefully it's got sufficient content that it helps you achieve what you're trying to do.</p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1946/"
] |
So if I have:
```
public class ChildClass : BaseClass
{
public new virtual string TempProperty { get; set; }
}
public class BaseClass
{
public virtual string TempProperty { get; set; }
}
```
How can I use reflection to see that ChildClass is hiding the Base implementation of TempProperty?
I'd like the answer to be agnostic between c# and vb.net
|
We'll have to deal in terms of the methods of the property here rather than the property itself, because it is the get/set methods of the property that actually get overridden rather than the property itself. I'll use the get method as you should never have a property without one, though a complete solution should check for the lack of one.
Looking at the IL emitted in a number of cases, the 'get' method of the base property will have the metadata tokens (this is from the C# compiler; others may not emit the `hidebysig` depending on their method hiding semantics, in which case the method would be hide-by-name):
```
non-virtual : .method public hidebysig specialname instance
virtual : .method public hidebysig specialname newslot virtual instance
```
The derived one will have the following tokens:
```
override : .method public hidebysig specialname virtual instance
new : .method public hidebysig specialname instance
new virtual : .method public hidebysig specialname newslot virtual instance
```
So we can see from this that it isn't possible to tell purely from the method's metadata tokens whether it is `new` because the non-virtual base method has the same tokens as the non-virtual `new` method, and the virtual base method has the same tokens as the `new virtual` method.
What we *can* say is that if the method has the `virtual` token but not the `newslot` token then it overrides a base method rather than shadows it, i.e.
```
var prop = typeof(ChildClass).GetProperty("TempProperty");
var getMethod = prop.GetGetMethod();
if ((getMethod.Attributes & MethodAttributes.Virtual) != 0 &&
(getMethod.Attributes & MethodAttributes.NewSlot) == 0)
{
// the property's 'get' method is an override
}
```
Assuming, then, that we find the 'get' method is not an override, we want to know whether there is a property in the base class that it is shadowing. The problem is that because the method is in a different method table slot, it doesn't actually have any direct relationship to the method it is shadowing. So what we're actually saying is "does the base type have any method which meets the criteria for shadowing", which varies depending on whether the method is `hidebysig` or hide-by-name.
For the former we need to check whether the base class has any method which matches the signature exactly, whereas for the latter we need to check whether it has any method with the same name, so continuing the code from above:
```
else
{
if (getMethod.IsHideBySig)
{
var flags = getMethod.IsPublic ? BindingFlags.Public : BindingFlags.NonPublic;
flags |= getMethod.IsStatic ? BindingFlags.Static : BindingFlags.Instance;
var paramTypes = getMethod.GetParameters().Select(p => p.ParameterType).ToArray();
if (getMethod.DeclaringType.BaseType.GetMethod(getMethod.Name, flags, null, paramTypes, null) != null)
{
// the property's 'get' method shadows by signature
}
}
else
{
var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance;
if (getMethod.DeclaringType.BaseType.GetMethods(flags).Any(m => m.Name == getMethod.Name))
{
// the property's 'get' method shadows by name
}
}
}
```
I think this is most of the way there, but I still don't think it's exactly right. For a start I'm not totally familiar with hiding by name as C# doesn't support it and that's pretty much all I use, so I may be wrong in the code here that indicates an instance method could shadow a static one. I also don't know about the case sensitivity issue (e.g. in VB could a method called `Foo` shadow a method called `foo` if they both had the same signature and were both `hidebysig` - in C# the answer is no but if the answer is yes in VB then it means the answer to this question is actually nondeterministic).
Well, I'm not sure how much help all this is, other than to illustrate that it's actually a much harder problem than I thought it would be (or I've missed something really obvious in which case I'd like to know!). But hopefully it's got sufficient content that it helps you achieve what you're trying to do.
|
288,368 |
<p>Do any of the existing JavaScript frameworks have a non-regex <code>replace()</code> function,
or has this already been posted on the web somewhere as a one-off function?</p>
<p>For example I want to replace <code>"@!#$123=%"</code> and I don't want to worry about which characters to escape. Most languages seem to have both methods of doing replacements. I would like to see this simple thing added.</p>
|
[
{
"answer_id": 288384,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 6,
"selected": true,
"text": "<p>i may be misunderstanding your question, but javascript does have a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace\" rel=\"noreferrer\"><code>replace()</code></a></p>\n\n<pre><code>var string = '@!#$123=%';\nvar newstring = string.replace('@!#$123=%', 'hi');\n</code></pre>\n\n<p><strong>edit</strong>: (see comments) the 5th edition does seem to have this info in it, although it doesn't show up when i <a href=\"http://safari.informit.com/0596101996/jscript5-CHP-11-SECT-2\" rel=\"noreferrer\">link directly</a> to it. here's the relevant part:</p>\n\n<blockquote>\n <p>The replace( ) method performs a search-and-replace operation. It takes a regular expression as its first argument and a replacement string as its second argument. It searches the string on which it is called for matches with the specified pattern. If the regular expression has the g flag set, the replace( ) method replaces all matches in the string with the replacement string; otherwise, it replaces only the first match it finds. <strong>If the first argument to replace( ) is a string rather than a regular expression, the method searches for that string literally rather than converting it to a regular expression with the RegExp( ) constructor, as search( ) does.</strong></p>\n</blockquote>\n"
},
{
"answer_id": 6724957,
"author": "Nick Ager",
"author_id": 848808,
"author_profile": "https://Stackoverflow.com/users/848808",
"pm_score": 5,
"selected": false,
"text": "<p>I had exactly the same problem searching for a non-regex javascript string replace() method. My solution was to use a combination of split() and join():</p>\n\n<pre><code>\"some text containing regex interpreted characters: $1.00\".split(\"$\").join(\"Β£\");\n</code></pre>\n\n<p>which gives:</p>\n\n<blockquote>\n <p>\"some text containing regex interpreted characters: Β£1.00\"</p>\n</blockquote>\n\n<p>compare with replace():</p>\n\n<pre><code>\"some text containing regex interpreted characters: $1.00\".replace(new RegExp(\"$\"),\"Β£\")\n</code></pre>\n\n<p>which bizarrely gives:</p>\n\n<blockquote>\n <p>\"some text containing regex interpreted characters: $1.00Β£\"</p>\n</blockquote>\n"
},
{
"answer_id": 18675737,
"author": "Steven Lizarazo",
"author_id": 589132,
"author_profile": "https://Stackoverflow.com/users/589132",
"pm_score": 2,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>function replaceAllTemp(str,find, replace) { \nvar ignoreCase=true;\nvar _token;\nvar token=find;\nvar newToken=replace;\nvar i = -1;\n\nif ( typeof token === \"string\" ) {\n\n if ( ignoreCase ) {\n\n _token = token.toLowerCase();\n\n while( (\n i = str.toLowerCase().indexOf(\n token, i >= 0 ? i + newToken.length : 0\n ) ) !== -1\n ) {\n str = str.substring( 0, i ) +\n newToken +\n str.substring( i + token.length );\n }\n\n } else {\n return this.split( token ).join( newToken );\n }\n\n}\nreturn str;\n};\n</code></pre>\n"
},
{
"answer_id": 56989647,
"author": "Stefan Steiger",
"author_id": 155077,
"author_profile": "https://Stackoverflow.com/users/155077",
"pm_score": 1,
"selected": false,
"text": "<p>You can do it with or without ignoring case sensitivity. <br />\nSadly, JavaScript's indexOf doesn't take locale vs. invariant as argument, so you'll have to replace <code>toLowerCase</code> with <code>toLocaleLowerCase</code> if you want to preserve culture-specifity. </p>\n\n<pre><code>function replaceAll(str, find, newToken, ignoreCase)\n{\n var i = -1;\n\n if (!str)\n {\n // Instead of throwing, act as COALESCE if find == null/empty and str == null\n if ((str == null) && (find == null))\n return newToken;\n\n return str;\n }\n\n if (!find) // sanity check \n return str;\n\n ignoreCase = ignoreCase || false;\n find = ignoreCase ? find.toLowerCase() : find;\n\n while ((\n i = (ignoreCase ? str.toLowerCase() : str).indexOf(\n find, i >= 0 ? i + newToken.length : 0\n )) !== -1\n )\n {\n str = str.substring(0, i) +\n newToken +\n str.substring(i + find.length);\n } // Whend \n\n return str;\n}\n</code></pre>\n\n<p>or as prototype:</p>\n\n<pre><code>if (!String.prototype.replaceAll ) { \nString.prototype.replaceAll = function (find, replace) {\n var str = this, i = -1;\n\n if (!str)\n {\n // Instead of throwing, act as COALESCE if find == null/empty and str == null\n if ((str == null) && (find == null))\n return newToken;\n\n return str;\n }\n\n if (!find) // sanity check \n return str;\n\n ignoreCase = ignoreCase || false;\n find = ignoreCase ? find.toLowerCase() : find;\n\n while ((\n i = (ignoreCase ? str.toLowerCase() : str).indexOf(\n find, i >= 0 ? i + newToken.length : 0\n )) !== -1\n )\n {\n str = str.substring(0, i) +\n newToken +\n str.substring(i + find.length);\n } // Whend \n\n return str;\n};\n}\n</code></pre>\n"
},
{
"answer_id": 71562813,
"author": "Mordechai",
"author_id": 1751640,
"author_profile": "https://Stackoverflow.com/users/1751640",
"pm_score": 2,
"selected": false,
"text": "<p>You'll still need to replace a few dollar sign combinations as specified on <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter\" rel=\"nofollow noreferrer\">MDN</a>.</p>\n<p>This produces <code>$bc</code> not <code>$$bc</code></p>\n<pre class=\"lang-js prettyprint-override\"><code>'abc'.replace('a', '$$')\n</code></pre>\n<p>The best way to not worry about this is to use the function replace:</p>\n<pre class=\"lang-js prettyprint-override\"><code>'abc'.replace('a', () => '$$')\n</code></pre>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36590/"
] |
Do any of the existing JavaScript frameworks have a non-regex `replace()` function,
or has this already been posted on the web somewhere as a one-off function?
For example I want to replace `"@!#$123=%"` and I don't want to worry about which characters to escape. Most languages seem to have both methods of doing replacements. I would like to see this simple thing added.
|
i may be misunderstanding your question, but javascript does have a [`replace()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace)
```
var string = '@!#$123=%';
var newstring = string.replace('@!#$123=%', 'hi');
```
**edit**: (see comments) the 5th edition does seem to have this info in it, although it doesn't show up when i [link directly](http://safari.informit.com/0596101996/jscript5-CHP-11-SECT-2) to it. here's the relevant part:
>
> The replace( ) method performs a search-and-replace operation. It takes a regular expression as its first argument and a replacement string as its second argument. It searches the string on which it is called for matches with the specified pattern. If the regular expression has the g flag set, the replace( ) method replaces all matches in the string with the replacement string; otherwise, it replaces only the first match it finds. **If the first argument to replace( ) is a string rather than a regular expression, the method searches for that string literally rather than converting it to a regular expression with the RegExp( ) constructor, as search( ) does.**
>
>
>
|
288,374 |
<p>A method I work with that is called tens of thousands of times started throwing exceptions recently. In most debugging circumstances I would set a breakpoint at the top of this method and run through until I reach the call I'm interested in with a parameter value that triggers the exception. In this case that would be impractical, so I tried setting a breakpoint with a condition that will only break when that parameter value appears. I created a breakpoint at the position indicated below and gave it a condition <code>str == "OffendingValue"</code>. </p>
<pre><code>class Foo
{
// Bar() is called many, many times
void Bar(string str)
{
try
{
// Breakpoint inserted here
...
}
catch (Exception ex)
{
...
}
}
}
</code></pre>
<p>To my surprise, doing this caused Visual Studio and my application to stop functioning in Debug mode. My application started and output some simple logging messages but then stopped responding entirely. Thinking Visual Studio might just be performing a little slower due to the extra work it has to do to monitor the breakpoint condition, I stepped away from my desk for 15 mintues to give it some time to run. When I returned there was no change. I can reproduce the condition by deleting the breakpoint and recreating it with the same condition. Strangest of all, the Break All debugging command, which will usually break program execution on the statement that's currently execting whether it's a breakpoint or not, does nothing at all when I have this problematic breakpoint enabled. </p>
<p>Has anyone encountered similar behavior with Visual Studio breakpoint conditions? I am able to use Hit Count conditions without problem. </p>
|
[
{
"answer_id": 288408,
"author": "Dana the Sane",
"author_id": 2567,
"author_profile": "https://Stackoverflow.com/users/2567",
"pm_score": 0,
"selected": false,
"text": "<p>I wonder if you are getting a stack overflow. Does VS track all the values for str or anything to do with each state of Bar? If so, the thousands of copies might add up.</p>\n\n<p>I wonder if you could eliminate the problem monitoring the value via a global variable instead, rather than one within the function.</p>\n"
},
{
"answer_id": 288483,
"author": "Rob Prouse",
"author_id": 30827,
"author_profile": "https://Stackoverflow.com/users/30827",
"pm_score": 2,
"selected": false,
"text": "<p>If you know what the offending value is, can you not just write a unit test for that method and debug it that way?</p>\n\n<p>If not, if you know the exception, you could set up your debugger to break when that exception is thrown. Go to Debug | Exceptions and check Thrown for the exception in question.</p>\n"
},
{
"answer_id": 288521,
"author": "asponge",
"author_id": 19449,
"author_profile": "https://Stackoverflow.com/users/19449",
"pm_score": 4,
"selected": true,
"text": "<p>Anytime that I have tried to use conditional breakpoints in Visual Studio I've had the same problem. The debugger runs so slowly that it becomes useless. Instead I end up temporarily adding an if statement to the code and adding my breakpoint inside of that. This isn't as convenient, but the code executes at a normal pace and it does get the job done.</p>\n\n<pre><code>class Foo\n{\n // Bar() is called many, many times\n void Bar(string str)\n {\n try\n {\n\n if(str == \"condition\")\n {\n int i = 0; // Breakpoint inserted here\n }\n ...\n }\n catch (Exception ex)\n {\n ...\n }\n }\n}\n</code></pre>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28350/"
] |
A method I work with that is called tens of thousands of times started throwing exceptions recently. In most debugging circumstances I would set a breakpoint at the top of this method and run through until I reach the call I'm interested in with a parameter value that triggers the exception. In this case that would be impractical, so I tried setting a breakpoint with a condition that will only break when that parameter value appears. I created a breakpoint at the position indicated below and gave it a condition `str == "OffendingValue"`.
```
class Foo
{
// Bar() is called many, many times
void Bar(string str)
{
try
{
// Breakpoint inserted here
...
}
catch (Exception ex)
{
...
}
}
}
```
To my surprise, doing this caused Visual Studio and my application to stop functioning in Debug mode. My application started and output some simple logging messages but then stopped responding entirely. Thinking Visual Studio might just be performing a little slower due to the extra work it has to do to monitor the breakpoint condition, I stepped away from my desk for 15 mintues to give it some time to run. When I returned there was no change. I can reproduce the condition by deleting the breakpoint and recreating it with the same condition. Strangest of all, the Break All debugging command, which will usually break program execution on the statement that's currently execting whether it's a breakpoint or not, does nothing at all when I have this problematic breakpoint enabled.
Has anyone encountered similar behavior with Visual Studio breakpoint conditions? I am able to use Hit Count conditions without problem.
|
Anytime that I have tried to use conditional breakpoints in Visual Studio I've had the same problem. The debugger runs so slowly that it becomes useless. Instead I end up temporarily adding an if statement to the code and adding my breakpoint inside of that. This isn't as convenient, but the code executes at a normal pace and it does get the job done.
```
class Foo
{
// Bar() is called many, many times
void Bar(string str)
{
try
{
if(str == "condition")
{
int i = 0; // Breakpoint inserted here
}
...
}
catch (Exception ex)
{
...
}
}
}
```
|
288,402 |
<p>if you</p>
<pre><code>Describe dbms_transform
PROCEDURE COMPUTE_TRANSFORMATION
Argument Name Type In/Out
------------------------------ ----------------------- ------
MESSAGE STANDARD IN
TRANSFORMATION_SCHEMA VARCHAR2 IN
TRANSFORMATION_NAME VARCHAR2 IN
TRANSFORMED_MESSAGE STANDARD OUT
</code></pre>
<p>What does the STANDARD mean there?</p>
|
[
{
"answer_id": 288471,
"author": "cagcowboy",
"author_id": 19629,
"author_profile": "https://Stackoverflow.com/users/19629",
"pm_score": 0,
"selected": false,
"text": "<p>Abstract Data Type?</p>\n\n<p><a href=\"http://www.psoug.org/reference/dbms_transform.html\" rel=\"nofollow noreferrer\">http://www.psoug.org/reference/dbms_transform.html</a></p>\n"
},
{
"answer_id": 314725,
"author": "Peter Lang",
"author_id": 17343,
"author_profile": "https://Stackoverflow.com/users/17343",
"pm_score": 2,
"selected": true,
"text": "<p>The type is \"<ADT_1>\" which is defined in package <em>standard</em>.</p>\n\n<p>According to the <a href=\"http://www.psoug.org/reference/standard.html\" rel=\"nofollow noreferrer\">reference</a> these </p>\n\n<blockquote>\n <p>data types are generics, used\n specially within package STANDARD and\n some other Oracle packages. They are\n protected against other use; sorry.\n True generic types are not yet part of\n the language.</p>\n</blockquote>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
if you
```
Describe dbms_transform
PROCEDURE COMPUTE_TRANSFORMATION
Argument Name Type In/Out
------------------------------ ----------------------- ------
MESSAGE STANDARD IN
TRANSFORMATION_SCHEMA VARCHAR2 IN
TRANSFORMATION_NAME VARCHAR2 IN
TRANSFORMED_MESSAGE STANDARD OUT
```
What does the STANDARD mean there?
|
The type is "<ADT\_1>" which is defined in package *standard*.
According to the [reference](http://www.psoug.org/reference/standard.html) these
>
> data types are generics, used
> specially within package STANDARD and
> some other Oracle packages. They are
> protected against other use; sorry.
> True generic types are not yet part of
> the language.
>
>
>
|
288,409 |
<p>If I create a UserControl and add some objects to it, how can I grab the HTML it would render?</p>
<p>ex.</p>
<pre><code>UserControl myControl = new UserControl();
myControl.Controls.Add(new TextBox());
// ...something happens
return strHTMLofControl;
</code></pre>
<p>I'd like to just convert a newly built UserControl to a string of HTML.</p>
|
[
{
"answer_id": 288414,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 1,
"selected": false,
"text": "<p>Call its <code>.RenderControl()</code> method.</p>\n"
},
{
"answer_id": 288419,
"author": "azamsharp",
"author_id": 3797,
"author_profile": "https://Stackoverflow.com/users/3797",
"pm_score": 7,
"selected": true,
"text": "<p>You can render the control using <code>Control.RenderControl(HtmlTextWriter)</code>.</p>\n<p>Feed <code>StringWriter</code> to the <code>HtmlTextWriter</code>.</p>\n<p>Feed <code>StringBuilder</code> to the <code>StringWriter</code>.</p>\n<p>Your generated string will be inside the <code>StringBuilder</code> object.</p>\n<p>Here's a code example for this solution:</p>\n<pre><code>string html = String.Empty;\nusing (TextWriter myTextWriter = new StringWriter(new StringBuilder()))\n{\n using (HtmlTextWriter myWriter = new HtmlTextWriter(myTextWriter))\n {\n myControl.RenderControl(myWriter);\n html = myTextWriter.ToString();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 288427,
"author": "Xian",
"author_id": 4642,
"author_profile": "https://Stackoverflow.com/users/4642",
"pm_score": 2,
"selected": false,
"text": "<p>override the RenderControl method</p>\n<pre><code>protected override void Render(HtmlTextWriter output)\n{ \n output.Write("<br>Message from Control : " + Message); \n output.Write("Showing Custom controls created in reverse" +\n "order"); \n // Render Controls.\n RenderChildren(output);\n}\n</code></pre>\n<p>This will give you access to the writer which the HTML will be written to.</p>\n<p>You may also want to look into the adaptive control architecture of asp.net\n<a href=\"http://msdn.microsoft.com/en-us/library/67276kc5.aspx\" rel=\"nofollow noreferrer\">adaptive control architecture of asp.net</a> where you can 'shape' the default html output from controls.</p>\n"
},
{
"answer_id": 832696,
"author": "Ben Aston",
"author_id": 38522,
"author_profile": "https://Stackoverflow.com/users/38522",
"pm_score": 5,
"selected": false,
"text": "<pre><code>//render control to string\nStringBuilder b = new StringBuilder();\nHtmlTextWriter h = new HtmlTextWriter(new StringWriter(b));\nthis.LoadControl(\"~/path_to_control.ascx\").RenderControl(h);\nstring controlAsString = b.ToString();\n</code></pre>\n"
},
{
"answer_id": 4777200,
"author": "theJerm",
"author_id": 118191,
"author_profile": "https://Stackoverflow.com/users/118191",
"pm_score": 4,
"selected": false,
"text": "<pre><code>UserControl uc = new UserControl();\nMyCustomUserControl mu = (MyCustomUserControl)uc.LoadControl(\"~/Controls/MyCustomUserControl.ascx\");\n\nTextWriter tw = new StringWriter();\nHtmlTextWriter hw = new HtmlTextWriter(tw);\n\nmu.RenderControl(hw);\n\nreturn tw.ToString();\n</code></pre>\n"
},
{
"answer_id": 31619749,
"author": "Reikim",
"author_id": 4271595,
"author_profile": "https://Stackoverflow.com/users/4271595",
"pm_score": 3,
"selected": false,
"text": "\n\n<p>Seven years late, but this deserves to be shared.</p>\n\n<p>The generally accepted solution - <code>StringBuilder</code> into <code>StringWriter</code> into <code>HtmlWriter</code> into <code>RenderControl</code> - is good. But there are some gotchas, which I unfortunately ran across while trying to do the same thing. Some controls will throw errors if they're not inside of a <code>Page</code>, and some will throw errors if they're not inside of a <code><form></code> with <code>runat=\"server\"</code>. The ScriptManager control exhibits both of these behaviours.</p>\n\n<p><a href=\"http://harouny.com/2012/10/15/render-asp-net-controls-user-controls-to-html-by-code/\" rel=\"noreferrer\">I eventually found a workaround here.</a> The gist of it is basically just instantiating a new Page and Form before doing the writer work:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>Page page = new Page();\npage.EnableEventValidation = false;\n\nHtmlForm form = new HtmlForm();\nform.Name = \"form1\";\npage.Controls.Add(form1);\n\nMyControl mc = new MyControl();\nform.Controls.Add(mc);\n\nStringBuilder sb = new StringBuilder();\nStringWriter sw = new StringWriter(sb);\nHtmlTextWriter writer = new HtmlTextWriter(sw);\n\npage.RenderControl(writer);\n\nreturn sb.ToString();\n</code></pre>\n\n<p>Unfortunately, this gives you more markup than you actually need (since it includes the dummy form). And the ScriptManager will still fail for some arcane reason I haven't puzzled out yet. Honestly, it's a whole lot of trouble and not worth doing; the whole point of generating controls in the code-behind is so that you don't have to fiddle around with the markup, after all.</p>\n"
},
{
"answer_id": 41982072,
"author": "Carl in 't Veld",
"author_id": 1585847,
"author_profile": "https://Stackoverflow.com/users/1585847",
"pm_score": 1,
"selected": false,
"text": "<p>You could utilize the <code>HttpServerUtility.Execute</code> Method, available through <code>HttpContext.Current.Server.Execute</code>:</p>\n\n<pre><code>var page = new Page();\nvar myControl = (MyControl)page.LoadControl(\"mycontrol.ascx\");\nmyControl.SetSomeProperty = true;\npage.Controls.Add(myControl);\nvar sw = new StringWriter();\nHttpContext.Current.Server.Execute(page, sw, preserveForm: false);\n</code></pre>\n\n<p>The benefit would be that you also trigger the Page_Load event of your user control. </p>\n\n<p>MSDN documentation can be found here: <a href=\"https://msdn.microsoft.com/en-us/library/fb04e8f7(v=vs.110).aspx\" rel=\"nofollow noreferrer\">https://msdn.microsoft.com/en-us/library/fb04e8f7(v=vs.110).aspx</a>. </p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25538/"
] |
If I create a UserControl and add some objects to it, how can I grab the HTML it would render?
ex.
```
UserControl myControl = new UserControl();
myControl.Controls.Add(new TextBox());
// ...something happens
return strHTMLofControl;
```
I'd like to just convert a newly built UserControl to a string of HTML.
|
You can render the control using `Control.RenderControl(HtmlTextWriter)`.
Feed `StringWriter` to the `HtmlTextWriter`.
Feed `StringBuilder` to the `StringWriter`.
Your generated string will be inside the `StringBuilder` object.
Here's a code example for this solution:
```
string html = String.Empty;
using (TextWriter myTextWriter = new StringWriter(new StringBuilder()))
{
using (HtmlTextWriter myWriter = new HtmlTextWriter(myTextWriter))
{
myControl.RenderControl(myWriter);
html = myTextWriter.ToString();
}
}
```
|
288,412 |
<p>I did a few tests with TouchJSON last night and it worked pretty well in general for simple cases. I'm using the following code to read some JSON content from a file, and deserialize it:</p>
<pre><code>NSString *jsonString = [[NSString alloc] initWithContentsOfFile:@"data.json"];
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF32BigEndianStringEncoding];
NSError *error = nil;
NSDictionary *items = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error];
NSLog(@"total items: %d", [items count]);
NSLog(@"error: %@", [error localizedDescription]);
</code></pre>
<p>That works fine if I have a very simple JSON object in the file (i.e. a dictionary):</p>
<pre><code>{"id": "54354", "name": "boohoo"}
</code></pre>
<p>This way I was able to get access to the array of values, as I wanted to get the item based on its index within the list:</p>
<pre><code>NSArray *items_list = [items allValues];
NSString *name = [items_list objectAtIndex:1];
</code></pre>
<p><em>(I understand that I could have fetched the name with the dictionary API)</em></p>
<p>Now I would like to deserialize a semi-complex JSON string, which represents an array of dictionaries. An example of such a JSON string is below:</p>
<pre><code>[{"id": "123456", "name": "touchjson"}, {"id": "3456", "name": "bleh"}]
</code></pre>
<p>When I try to run the same code above against this new content in the data.json file, I don't get any results back. My NSLog() call says "total items: 0", and no error is coming back in the NSError object.</p>
<p>Any clues on what is going on? I'm completely lost on what to do, as there isn't much documentation available for TouchJSON, and much less usage examples.</p>
|
[
{
"answer_id": 288855,
"author": "rpj",
"author_id": 23498,
"author_profile": "https://Stackoverflow.com/users/23498",
"pm_score": 4,
"selected": true,
"text": "<p>This isn't an answer, but a pointer to a different framework:</p>\n\n<p><a href=\"http://code.google.com/p/json-framework/\" rel=\"nofollow noreferrer\">http://code.google.com/p/json-framework/</a></p>\n\n<p>I've been using it quite a bit lately, serializing and de-serializing complex data structures from third-party services such as Google Local and between my own Objective-C and Perl code with absolutely no problems. Not to mention that the API is ridiculously easy to deal with.</p>\n\n<p>Good luck!</p>\n"
},
{
"answer_id": 289175,
"author": "wisequark",
"author_id": 33159,
"author_profile": "https://Stackoverflow.com/users/33159",
"pm_score": 0,
"selected": false,
"text": "<p>At it's heart JSON deals with objects, your code to de-serialize should be as follows</p>\n\n<pre><code>{\n \"objects\": [{\n \"id\": \"123456\",\n \"name\": \"touchjson\"\n }, {\n \"id\": \"3456\",\n \"name\": \"bleh\"\n }]\n}\n</code></pre>\n\n<p>which does work with the latest checkout.</p>\n"
},
{
"answer_id": 289193,
"author": "schwa",
"author_id": 23113,
"author_profile": "https://Stackoverflow.com/users/23113",
"pm_score": 4,
"selected": false,
"text": "<p>I'm the author of TouchJSON.</p>\n\n<p>Your outermost object should be a dictionary and NOT an array. Anything other than a dictionary is not legal. If you have to have an array as the outermost object then use the method (which is technically deprecated, but isn't going any where soon)</p>\n\n<pre><code>- (id)deserialize:(NSData *)inData error:(NSError **)outError;\n</code></pre>\n\n<p>See: <a href=\"http://www.json.com/json-schema-proposal/\" rel=\"nofollow noreferrer\">http://www.json.com/json-schema-proposal/</a> for more information abotu what is and is not legal JSON.</p>\n"
},
{
"answer_id": 954728,
"author": "gene tsai",
"author_id": 82174,
"author_profile": "https://Stackoverflow.com/users/82174",
"pm_score": 0,
"selected": false,
"text": "<p>@Mathieu - I think this is what you are looking for (6 months late, I know :), but I just ran into the same problem)</p>\n\n<p>Copy and pasted from here: <a href=\"http://groups.google.com/group/touchcode-dev/browse_thread/thread/ada885832019f45b\" rel=\"nofollow noreferrer\">http://groups.google.com/group/touchcode-dev/browse_thread/thread/ada885832019f45b</a></p>\n\n<pre><code>NSArray *tweetsArray = [resultsDictionary objectForKey:@\"results\"]; \nfor (NSDictionary *tweetDictionary in tweetsArray) { \n NSString *tweetText = [tweetDictionary objectForKey:@\"text\"]; \n [tweets addObject:tweetText]; \n} \n</code></pre>\n\n<p>To give more context, the JSON that I'm parsing is in the general form<br>\nof: </p>\n\n<pre><code>{\"results\": \n [ \n {\"text\":\"tweet1\"}, \n {\"text\":\"tweet2\"}, \n {\"text\":\"tweet3\"} \n ] \n} \n</code></pre>\n"
},
{
"answer_id": 2799605,
"author": "alecnash",
"author_id": 335561,
"author_profile": "https://Stackoverflow.com/users/335561",
"pm_score": 0,
"selected": false,
"text": "<p>Not sure if it helps you but check this out\n<a href=\"http://tempered.mobi/%20\" rel=\"nofollow noreferrer\">http://tempered.mobi/%20</a></p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35478/"
] |
I did a few tests with TouchJSON last night and it worked pretty well in general for simple cases. I'm using the following code to read some JSON content from a file, and deserialize it:
```
NSString *jsonString = [[NSString alloc] initWithContentsOfFile:@"data.json"];
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF32BigEndianStringEncoding];
NSError *error = nil;
NSDictionary *items = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error];
NSLog(@"total items: %d", [items count]);
NSLog(@"error: %@", [error localizedDescription]);
```
That works fine if I have a very simple JSON object in the file (i.e. a dictionary):
```
{"id": "54354", "name": "boohoo"}
```
This way I was able to get access to the array of values, as I wanted to get the item based on its index within the list:
```
NSArray *items_list = [items allValues];
NSString *name = [items_list objectAtIndex:1];
```
*(I understand that I could have fetched the name with the dictionary API)*
Now I would like to deserialize a semi-complex JSON string, which represents an array of dictionaries. An example of such a JSON string is below:
```
[{"id": "123456", "name": "touchjson"}, {"id": "3456", "name": "bleh"}]
```
When I try to run the same code above against this new content in the data.json file, I don't get any results back. My NSLog() call says "total items: 0", and no error is coming back in the NSError object.
Any clues on what is going on? I'm completely lost on what to do, as there isn't much documentation available for TouchJSON, and much less usage examples.
|
This isn't an answer, but a pointer to a different framework:
<http://code.google.com/p/json-framework/>
I've been using it quite a bit lately, serializing and de-serializing complex data structures from third-party services such as Google Local and between my own Objective-C and Perl code with absolutely no problems. Not to mention that the API is ridiculously easy to deal with.
Good luck!
|
288,413 |
<p>I am using this code to verify a behavior of a method I am testing:</p>
<pre><code> _repository.Expect(f => f.FindAll(t => t.STATUS_CD == "A"))
.Returns(new List<JSOFile>())
.AtMostOnce()
.Verifiable();
</code></pre>
<p>_repository is defined as:</p>
<pre><code>private Mock<IRepository<JSOFile>> _repository;
</code></pre>
<p>When my test is run, I get this exception:</p>
<p><strong>Expression t => (t.STATUS_CD = "A") is not supported.</strong></p>
<p>Can someone please tell me how I can test this behavior if I can't pass an expression into the Expect method?</p>
<p>Thanks!!</p>
|
[
{
"answer_id": 288509,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>In Rhino Mocks you would do something like this...</p>\n\n<p>Instead of using an Expect, use a Stub and Ignore the arguments. Then have --</p>\n\n<pre><code>Func<JSOFile, bool> _myDelegate;\n\n_repository.Stub(f => FindAll(null)).IgnoreArguments()\n .Do( (Func<Func<JSOFile, bool>, IEnumerable<JSOFile>>) (del => { _myDelegate = del; return new List<JSOFile>();});\n</code></pre>\n\n<p><em>Call Real Code</em></p>\n\n<p>*Setup a fake JSOFile object with STATUS_CD set to \"A\" *</p>\n\n<pre><code>Assert.IsTrue(_myDelegate.Invoke(fakeJSO));\n</code></pre>\n"
},
{
"answer_id": 288649,
"author": "flukus",
"author_id": 407256,
"author_profile": "https://Stackoverflow.com/users/407256",
"pm_score": 0,
"selected": false,
"text": "<p>Try This</p>\n\n<pre><code> _repository.Expect(f => f.FindAll(It.Is<SomeType>(t => t.STATUS_CD == \"A\")))\n</code></pre>\n\n<p>An easy way to check for errors is to make sure at the end of an expect call you always have three ')'s.</p>\n"
},
{
"answer_id": 289297,
"author": "flukus",
"author_id": 407256,
"author_profile": "https://Stackoverflow.com/users/407256",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to test the correct parameter is passed you could always \"abuse\" the returns statement:</p>\n\n<blockquote>\n <p>bool correctParamters = true;</p>\n \n <p>_repository.Expect(f => f.FindAll(It.IsAny>()))</p>\n \n <p>.Returns((Func func) => {correctParamters = func(fakeJSOFile); return new List-JSOFile-(); })</p>\n \n <p>.AtMostOnce()</p>\n \n <p>.Verifiable();</p>\n \n <p>Assert.IsTrue(correctParamters);</p>\n</blockquote>\n\n<p>This will invoke the function passed in with the arguments you want.</p>\n"
},
{
"answer_id": 290126,
"author": "Steve Horn",
"author_id": 10589,
"author_profile": "https://Stackoverflow.com/users/10589",
"pm_score": 1,
"selected": false,
"text": "<p>Browsing the Moq discussion list, I think I found the answer:</p>\n\n<p><a href=\"http://groups.google.com/group/moqdisc/browse_thread/thread/20f5a2ceefcba0e/8f477c1f5c4b5321?lnk=gst&q=func#8f477c1f5c4b5321\" rel=\"nofollow noreferrer\">Moq Discussion</a></p>\n\n<p>It appears I have run into a limitation of the Moq framework.</p>\n\n<p>Edit, I've found another way to test the expression:</p>\n\n<p><a href=\"https://web.archive.org/web/20100105203531/http://blog.stevehorn.cc/2008/11/testing-expressions-with-moq.html\" rel=\"nofollow noreferrer\">http://blog.stevehorn.cc/2008/11/testing-expressions-with-moq.html</a></p>\n"
},
{
"answer_id": 1120836,
"author": "mcintyre321",
"author_id": 2086,
"author_profile": "https://Stackoverflow.com/users/2086",
"pm_score": 2,
"selected": false,
"text": "<p>This is a bit of a cheaty way. I do a .ToString() on the expressions and compare them. This means you have to write the lambda the same way in the class under test. If you wanted, you could do some parsing at this point</p>\n\n<pre><code> [Test]\n public void MoqTests()\n {\n var mockedRepo = new Mock<IRepository<Meeting>>();\n mockedRepo.Setup(r => r.FindWhere(MatchLambda<Meeting>(m => m.ID == 500))).Returns(new List<Meeting>());\n Assert.IsNull(mockedRepo.Object.FindWhere(m => m.ID == 400));\n Assert.AreEqual(0, mockedRepo.Object.FindWhere(m => m.ID == 500).Count);\n }\n\n //I broke this out into a helper as its a bit ugly\n Expression<Func<Meeting, bool>> MatchLambda<T>(Expression<Func<Meeting, bool>> exp)\n {\n return It.Is<Expression<Func<Meeting, bool>>>(e => e.ToString() == exp.ToString());\n }\n</code></pre>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10589/"
] |
I am using this code to verify a behavior of a method I am testing:
```
_repository.Expect(f => f.FindAll(t => t.STATUS_CD == "A"))
.Returns(new List<JSOFile>())
.AtMostOnce()
.Verifiable();
```
\_repository is defined as:
```
private Mock<IRepository<JSOFile>> _repository;
```
When my test is run, I get this exception:
**Expression t => (t.STATUS\_CD = "A") is not supported.**
Can someone please tell me how I can test this behavior if I can't pass an expression into the Expect method?
Thanks!!
|
This is a bit of a cheaty way. I do a .ToString() on the expressions and compare them. This means you have to write the lambda the same way in the class under test. If you wanted, you could do some parsing at this point
```
[Test]
public void MoqTests()
{
var mockedRepo = new Mock<IRepository<Meeting>>();
mockedRepo.Setup(r => r.FindWhere(MatchLambda<Meeting>(m => m.ID == 500))).Returns(new List<Meeting>());
Assert.IsNull(mockedRepo.Object.FindWhere(m => m.ID == 400));
Assert.AreEqual(0, mockedRepo.Object.FindWhere(m => m.ID == 500).Count);
}
//I broke this out into a helper as its a bit ugly
Expression<Func<Meeting, bool>> MatchLambda<T>(Expression<Func<Meeting, bool>> exp)
{
return It.Is<Expression<Func<Meeting, bool>>>(e => e.ToString() == exp.ToString());
}
```
|
288,430 |
<p>How Can I put information in a outputstream from tapestry5 ?</p>
<p>I need a page when a user enters it open a dialog for save or open the file with the outputstream information.</p>
<p>I write the next code:</p>
<p>public class Index {</p>
<pre><code>@Inject
private RequestGlobals requestGlobals;
@OnEvent("activate")
public void onActivate() {
try {
HttpServletResponse response = requestGlobals.getHTTPServletResponse();
response.setContentType("text/txt");
PrintWriter out = response.getWriter();
out.println("hellooooooo");
out.flush();
} catch (IOException ex) {
Logger.getLogger(Index.class.getName()).log(Level.SEVERE, null, ex);
}
}
</code></pre>
<p>}</p>
<p>I hope that the result is only "helloooooooo" but is ("helloooooooo" + my html raw page)</p>
|
[
{
"answer_id": 296682,
"author": "Chochos",
"author_id": 10165,
"author_profile": "https://Stackoverflow.com/users/10165",
"pm_score": 3,
"selected": true,
"text": "<p>Your method should have a return type of StreamResponse. You return an implementation of the interface StreamResponse, which simply returns the data you want with the content type you want.</p>\n\n<p>Look it up here:</p>\n\n<p><a href=\"http://tapestry.apache.org/tapestry5/apidocs/\" rel=\"nofollow noreferrer\">http://tapestry.apache.org/tapestry5/apidocs/</a></p>\n\n<p>more info here:</p>\n\n<p><a href=\"http://tapestry.formos.com/nightly/tapestry5/tapestry-core/guide/pagenav.html\" rel=\"nofollow noreferrer\">http://tapestry.formos.com/nightly/tapestry5/tapestry-core/guide/pagenav.html</a></p>\n"
},
{
"answer_id": 7947726,
"author": "Neeme Praks",
"author_id": 74694,
"author_profile": "https://Stackoverflow.com/users/74694",
"pm_score": 2,
"selected": false,
"text": "<p>If you are dealing with large response streams, using <a href=\"http://tapestry.apache.org/tapestry5/apidocs/org/apache/tapestry5/StreamResponse.html\" rel=\"nofollow\">StreamResponse</a> can be somewhat inconvenient and inefficient (because you have to return an <a href=\"http://download.oracle.com/javase/6/docs/api/java/io/InputStream.html\" rel=\"nofollow\">InputStream</a>). Better would be to write response directly to <a href=\"http://download.oracle.com/javase/6/docs/api/java/io/OutputStream.html\" rel=\"nofollow\">OutputStream</a>.</p>\n\n<p>Fortunately, in Tapestry Wiki, there is a page for solving exactly this: <a href=\"http://wiki.apache.org/tapestry/Tapestry5HowToCreateAComponentEventResultProcessor\" rel=\"nofollow\">Tapestry5: How To Create A Component Event Result Processor</a>.</p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34768/"
] |
How Can I put information in a outputstream from tapestry5 ?
I need a page when a user enters it open a dialog for save or open the file with the outputstream information.
I write the next code:
public class Index {
```
@Inject
private RequestGlobals requestGlobals;
@OnEvent("activate")
public void onActivate() {
try {
HttpServletResponse response = requestGlobals.getHTTPServletResponse();
response.setContentType("text/txt");
PrintWriter out = response.getWriter();
out.println("hellooooooo");
out.flush();
} catch (IOException ex) {
Logger.getLogger(Index.class.getName()).log(Level.SEVERE, null, ex);
}
}
```
}
I hope that the result is only "helloooooooo" but is ("helloooooooo" + my html raw page)
|
Your method should have a return type of StreamResponse. You return an implementation of the interface StreamResponse, which simply returns the data you want with the content type you want.
Look it up here:
<http://tapestry.apache.org/tapestry5/apidocs/>
more info here:
<http://tapestry.formos.com/nightly/tapestry5/tapestry-core/guide/pagenav.html>
|
288,441 |
<p>I long thought that in C, all variables had to be declared at the beginning of the function. I know that in C99, the rules are the same as in C++, but what are the variable declaration placement rules for C89/ANSI C?</p>
<p>The following code compiles successfully with <code>gcc -std=c89</code> and <code>gcc -ansi</code>:</p>
<pre><code>#include <stdio.h>
int main() {
int i;
for (i = 0; i < 10; i++) {
char c = (i % 95) + 32;
printf("%i: %c\n", i, c);
char *s;
s = "some string";
puts(s);
}
return 0;
}
</code></pre>
<p>Shouldn't the declarations of <code>c</code> and <code>s</code> cause an error in C89/ANSI mode?</p>
|
[
{
"answer_id": 288455,
"author": "mipadi",
"author_id": 28804,
"author_profile": "https://Stackoverflow.com/users/28804",
"pm_score": 8,
"selected": true,
"text": "<p>It compiles successfully because GCC allows the declaration of <code>s</code> as a GNU extension, even though it's not part of the C89 or ANSI standard. If you want to adhere strictly to those standards, you must pass the <code>-pedantic</code> flag.</p>\n\n<p>The declaration of <code>c</code> at the start of a <code>{ }</code> block is part of the C89 standard; the block doesn't have to be a function.</p>\n"
},
{
"answer_id": 288479,
"author": "Kiley Hykawy",
"author_id": 22727,
"author_profile": "https://Stackoverflow.com/users/22727",
"pm_score": 6,
"selected": false,
"text": "<p>For C89, you must declare all of your variables at the beginning of a <em>scope block</em>.</p>\n\n<p>So, your <code>char c</code> declaration is valid as it is at the top of the for loop scope block. But, the <code>char *s</code> declaration should be an error. </p>\n"
},
{
"answer_id": 288515,
"author": "Adam Liss",
"author_id": 29157,
"author_profile": "https://Stackoverflow.com/users/29157",
"pm_score": 5,
"selected": false,
"text": "<p>From a maintainability, rather than syntactic, standpoint, there are at least three trains of thought:</p>\n\n<ol>\n<li><p>Declare all variables at the beginning of the function so they'll be in one place and you'll be able to see the comprehensive list at a glance.</p></li>\n<li><p>Declare all variables as close as possible to the place they're first used, so you'll know <em>why</em> each is needed.</p></li>\n<li><p>Declare all variables at the beginning of the innermost scope block, so they'll go out of scope as soon as possible and allow the compiler to optimize memory and tell you if you accidentally use them where you hadn't intended.</p></li>\n</ol>\n\n<p>I generally prefer the first option, as I find the others often force me to hunt through code for the declarations. Defining all variables up front also makes it easier to initialize and watch them from a debugger.</p>\n\n<p>I'll sometimes declare variables within a smaller scope block, but only for a Good Reason, of which I have very few. One example might be after a <code>fork()</code>, to declare variables needed only by the child process. To me, this visual indicator is a helpful reminder of their purpose.</p>\n"
},
{
"answer_id": 4105334,
"author": "MarcH",
"author_id": 317623,
"author_profile": "https://Stackoverflow.com/users/317623",
"pm_score": 6,
"selected": false,
"text": "<p>Grouping variable declarations at the top of the block is a legacy likely due to limitations of old, primitive C compilers. All modern languages recommend and sometimes even enforce the declaration of local variables at the latest point: where they're first initialized. Because this gets rid of the risk of using a random value by mistake. Separating declaration and initialization also prevents you from using \"const\" (or \"final\") when you could.</p>\n\n<p>C++ unfortunately keeps accepting the old, top declaration way for backward compatibility with C (one C compatibility drag out of many others...) But C++ tries to move away from it:</p>\n\n<ul>\n<li>The design of C++ references does not even allow such top of the block grouping.</li>\n<li>If you separate declaration and initialization of a C++ local <em>object</em> then you pay the cost of an extra constructor for nothing. If the no-arg constructor does not exist then again you are not even allowed to separate both!</li>\n</ul>\n\n<p>C99 starts to move C in this same direction.</p>\n\n<p>If you are worried of not finding where local variables are declared then it means you have a much bigger problem: the enclosing block is too long and should be split.</p>\n\n<p><a href=\"https://wiki.sei.cmu.edu/confluence/display/c/DCL19-C.+Minimize+the+scope+of+variables+and+functions\" rel=\"noreferrer\">https://wiki.sei.cmu.edu/confluence/display/c/DCL19-C.+Minimize+the+scope+of+variables+and+functions</a></p>\n"
},
{
"answer_id": 6016499,
"author": "Gaidheal",
"author_id": 755529,
"author_profile": "https://Stackoverflow.com/users/755529",
"pm_score": 3,
"selected": false,
"text": "<p>As noted by others, GCC is permissive in this regard (and possibly other compilers, depending on the arguments they're called with) even when in 'C89' mode, unless you use 'pedantic' checking. To be honest, there are not many good reasons to not have pedantic on; quality modern code should always compile without warnings (or very few where you know you are doing something specific that is suspicious to the compiler as a possible mistake), so if you cannot make your code compile with a pedantic setup it probably needs some attention.</p>\n\n<p>C89 requires that variables be declared before any other statements within each scope, later standards permit declaration closer to use (which can be both more intuitive and more efficient), especially the simultaneous declaration and initialization of a loop control variable in 'for' loops.</p>\n"
},
{
"answer_id": 11920286,
"author": "junwanghe",
"author_id": 1548476,
"author_profile": "https://Stackoverflow.com/users/1548476",
"pm_score": 0,
"selected": false,
"text": "<p>I will quote some statements from the manual for gcc version 4.7.0 for a clear explanation.</p>\n\n<p>\"The compiler can accept several base standards, such as βc90β or βc++98β, and GNU dialects of those standards, such as βgnu90β or βgnu++98β. By specifying a base standard, the compiler will accept all programs following that standard and those using GNU extensions that do not contradict it. For example, β-std=c90β turns off certain features of GCC that are incompatible with ISO C90, such as the asm and typeof keywords, but not other GNU extensions that do not have a meaning in ISO C90, such as omitting the middle term of a ?: expression.\"</p>\n\n<p>I think the key point of your question is that why does not gcc conform to C89 even if the option \"-std=c89\" is used. I don't know the version of your gcc, but I think that there won't be big difference. The developer of gcc has told us that the option \"-std=c89\" just means the extensions which contradict C89 are turned off. So, it has nothing to do with some extensions that do not have a meaning in C89. And the extension that don't restrict the placement of variable declaration belongs to the extensions that do not contradict C89.</p>\n\n<p>To be honest, everyone will think that it should conform C89 totally at the first sight of the option \"-std=c89\". But it doesn't.\nAs for the problem that declare all variables at the beginning is better or worse is just A matter of habit.</p>\n"
},
{
"answer_id": 50822486,
"author": "Philippe Carphin",
"author_id": 5795941,
"author_profile": "https://Stackoverflow.com/users/5795941",
"pm_score": 2,
"selected": false,
"text": "<p>As has been noted, there are two schools of thought on this.</p>\n\n<p>1) Declare everything at the top of functions because the year is 1987.</p>\n\n<p>2) Declare closest to first use and in the smallest scope possible.</p>\n\n<p>My answer to this is DO BOTH! Let me explain:</p>\n\n<p>For long functions, 1) makes refactoring very hard. If you work in a codebase where the developers are against the idea of subroutines, then you'll have 50 variable declarations at the start of the function and some of them might just be an \"i\" for a for-loop that's at the very bottom of the function.</p>\n\n<p>I therefore developed declaration-at-the-top-PTSD from this and tried to do option 2) religiously.</p>\n\n<p>I came back around to option one because of one thing: short functions. If your functions are short enough, then you will have few local variables and since the function is short, if you put them at the top of the function, they will still be close to the first use.</p>\n\n<p>Also, the anti-pattern of \"declare and set to NULL\" when you want to declare at the top but you haven't made some calculations necessary for initialization is resolved because the things you need to initialize will likely be received as arguments.</p>\n\n<p>So now my thinking is that you should declare at the top of functions and as close as possible to first use. So BOTH! And the way to do that is with well divided subroutines.</p>\n\n<p>But if you're working on a long function, then put things closest to first use because that way it will be easier to extract methods.</p>\n\n<p>My recipe is this. For all local variables, take the variable and move it's declaration to the bottom, compile, then move the declaration to just before the compilation error. That's the first use. Do this for all local variables.</p>\n\n<pre><code>int foo = 0;\n<code that uses foo>\n\nint bar = 1;\n<code that uses bar>\n\n<code that uses foo>\n</code></pre>\n\n<p>Now, define a scope block that starts before the declaration and move the end until the program compiles</p>\n\n<pre><code>{\n int foo = 0;\n <code that uses foo>\n}\n\nint bar = 1;\n<code that uses bar>\n\n>>> First compilation error here\n<code that uses foo>\n</code></pre>\n\n<p>This doesn't compile because there is some more code that uses foo. We can notice that the compiler was able to go through the code that uses bar because it doesn't use foo. At this point, there are two choices. The mechanical one is to just move the \"}\" downwards until it compiles, and the other choice is to inspect the code and determine if the order can be changed to:</p>\n\n<pre><code>{\n int foo = 0;\n <code that uses foo>\n}\n\n<code that uses foo>\n\nint bar = 1;\n<code that uses bar>\n</code></pre>\n\n<p>If the order can be switched, that's probably what you want because it shortens the lifespan of temporary values.</p>\n\n<p>Another thing to note, does the value of foo need to be preserved between the blocks of code that use it, or could it just be a different foo in both. For example</p>\n\n<pre><code>int i;\n\nfor(i = 0; i < 8; ++i){\n ...\n}\n\n<some stuff>\n\nfor(i = 3; i < 32; ++i){\n ...\n}\n</code></pre>\n\n<p>These situations need more than my procedure. The developer will have to analyse the code to determine what to do.</p>\n\n<p>But the first step is finding the first use. You can do it visually but sometimes, it's just easier to delete the declaration, try to compile and just put it back above the first use. If that first use is inside an if statement, put it there and check if it compiles. The compiler will then identify other uses. Try to make a scope block that encompasses both uses.</p>\n\n<p>After this mechanical part is done, then it becomes easier to analyse where the data is. If a variable is used in a big scope block, analyse the situation and see if you're just using the same variable for two different things (like an \"i\" that gets used for two for loops). If the uses are unrelated, create new variables for each of these unrelated uses.</p>\n"
},
{
"answer_id": 59818934,
"author": "Dang_Ho",
"author_id": 6560845,
"author_profile": "https://Stackoverflow.com/users/6560845",
"pm_score": -1,
"selected": false,
"text": "<p>You should declare all variable at the top or \"locally\" in the function. The answer is: </p>\n\n<p><strong>It depends</strong> on what kind you system you are using:</p>\n\n<p>1/ Embedded System (especially related to lives like Airplane or Car):\nIt does allow you to use dynamic memory (eg: calloc, malloc, new...). Imagine you are working in a very big project, with 1000 engineers. What if they allocate new dynamic memory and forgot to remove it (when it does not use anymore)? If the embedded system run for a long time, it will lead to stack overflow and software will corrupt. Not easy to make sure the quality (the best way is ban dynamic memory).</p>\n\n<p>If an Airplane run in 30days and doesnot turnoff, what happens if software is corrupted (when the airplane still in the air)? </p>\n\n<p>2/ The others system like web, PC (have large memory space):</p>\n\n<p>You should declare variable \"locally\" to optimize the memory using. If these system run for a long time and stack overflow happen (because someone forgot to remove dynamic memory). Just do the simple thing to reset the PC :P Its no impact on lives </p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30323/"
] |
I long thought that in C, all variables had to be declared at the beginning of the function. I know that in C99, the rules are the same as in C++, but what are the variable declaration placement rules for C89/ANSI C?
The following code compiles successfully with `gcc -std=c89` and `gcc -ansi`:
```
#include <stdio.h>
int main() {
int i;
for (i = 0; i < 10; i++) {
char c = (i % 95) + 32;
printf("%i: %c\n", i, c);
char *s;
s = "some string";
puts(s);
}
return 0;
}
```
Shouldn't the declarations of `c` and `s` cause an error in C89/ANSI mode?
|
It compiles successfully because GCC allows the declaration of `s` as a GNU extension, even though it's not part of the C89 or ANSI standard. If you want to adhere strictly to those standards, you must pass the `-pedantic` flag.
The declaration of `c` at the start of a `{ }` block is part of the C89 standard; the block doesn't have to be a function.
|
288,445 |
<p>I have a swf file that's embedded in a html page, and I have a close button in the swf page, I want the swf to disappear when I click on the button, what is the best way to do that? Thanks.</p>
|
[
{
"answer_id": 288468,
"author": "Steve Paulo",
"author_id": 9414,
"author_profile": "https://Stackoverflow.com/users/9414",
"pm_score": 1,
"selected": false,
"text": "<p>Write a JavaScript function that will hide the swf or its containing element, and call that function via the \"close button\" in the swf itself.</p>\n"
},
{
"answer_id": 288549,
"author": "Andrew Bullock",
"author_id": 28543,
"author_profile": "https://Stackoverflow.com/users/28543",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://www.communitymx.com/content/article.cfm?cid=0922A\" rel=\"nofollow noreferrer\">Heres</a> an article on how to get flash to call some JS on your page. If you never want it back (after hiding) i suggest you <a href=\"http://www.dustindiaz.com/add-and-remove-html-elements-dynamically-with-javascript/\" rel=\"nofollow noreferrer\">remove it from the DOM</a> to release resources, as flash is expensive in client environments.</p>\n"
},
{
"answer_id": 1176547,
"author": "Yens",
"author_id": 71772,
"author_profile": "https://Stackoverflow.com/users/71772",
"pm_score": 3,
"selected": true,
"text": "<p>If your ursing swfobject 2.1 to embed the swf you can use this built-in javascript swfobject.removeSWF() function: </p>\n\n<pre><code>function removeFlashFromHTML() \n{\n swfobject.removeSWF(\"id_of_your_html_object\");\n}\n</code></pre>\n\n<p>now you call the javascript function from flash using ExternalInterface:</p>\n\n<pre><code>function buttonClicked(evt:MouseEvent) \n{\n if (ExternalInterface.available) {\n ExternalInterface.call(\"removeFlashFromHTML()\");\n }\n}\n</code></pre>\n\n<p>for more information about SWFObject check <a href=\"http://code.google.com/p/swfobject/\" rel=\"nofollow noreferrer\">this</a> website </p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34797/"
] |
I have a swf file that's embedded in a html page, and I have a close button in the swf page, I want the swf to disappear when I click on the button, what is the best way to do that? Thanks.
|
If your ursing swfobject 2.1 to embed the swf you can use this built-in javascript swfobject.removeSWF() function:
```
function removeFlashFromHTML()
{
swfobject.removeSWF("id_of_your_html_object");
}
```
now you call the javascript function from flash using ExternalInterface:
```
function buttonClicked(evt:MouseEvent)
{
if (ExternalInterface.available) {
ExternalInterface.call("removeFlashFromHTML()");
}
}
```
for more information about SWFObject check [this](http://code.google.com/p/swfobject/) website
|
288,465 |
<p>I'm building an XML DOM document in C++. My problem is this: I execute an XPATH query from an Element in my Document, which I know will return another Element. The elementPtr->selectSingleNode call returns an IXMLDOMNode. How can I gain access to the attributes of this node?</p>
<p>Part of me wants to downcast the Node to an Element, but I couldn't get the cast to work.</p>
<p>I tried</p>
<pre><code>MSXML2::IXMLDOMElementPtr pParentElement;
pParentNode->QueryInterface(__uuidof(MSXML2::IXMLDOMElement),
(void**) &pParentElement);
</code></pre>
<p>Which results in the following runtime error: </p>
<pre><code>0x0057cc58 _com_error::`scalar deleting destructor'(unsigned int)
</code></pre>
<p>The other route I tried was to just use nodes:</p>
<pre><code>MSXML2::IXMLDOMNodePtr pParentNode =
pParameterElement->selectSingleNode("parent");
MSXML2::IXMLDOMNamedNodeMap* pParentAttributes;
pParentNode->get_attributes(&pParentAttributes);
MSXML2::IXMLDOMNodePtr pCategoryNameNode =
pParentAttributes->getNamedItem("Category");
VARIANT value;
pCategoryNameNode->get_nodeValue(&value);
CString categoryName = value;
</code></pre>
<p>This fails at "parentNode->get_attributes()".</p>
<p>It seems like I'm missing something; the API should not be this hard to use.</p>
<p>--edit--</p>
<p>What I was missing was that the selectSingleNode call was failing, leaving me with a NULL pointer. You can't call QueryInterface on that, neither can you call get_attributes on it :P</p>
<p>I've selected the answer that fits the question that I asked, not the answer that helped me to realise that I asked the wrong question.</p>
|
[
{
"answer_id": 288518,
"author": "DavidK",
"author_id": 31394,
"author_profile": "https://Stackoverflow.com/users/31394",
"pm_score": 1,
"selected": false,
"text": "<p>How did you try to do the downcast from IXMLDOMNode to IXMLDOMElement? You can't just use a C++ cast for that, as it's a COM object: you've got to use QueryInterface().</p>\n\n<hr>\n\n<p>Looking at your QueryInterface() code, some thoughts:</p>\n\n<ul>\n<li>Is pParentNode definitely not null? I don't think that this is the problem, given what you get, but it's worth checking.</li>\n<li><p>The QueryInterface() call isn't quite right, I think: you've got to call AddRef() one way or another on the returned interface, and your code won't. As another poster noted, you can get _com_ptr_t<> to do this for you:</p>\n\n<pre><code>MSXML2::IXMLDOMElementPtr pParentElement(pParentNode);\n</code></pre></li>\n</ul>\n\n<p>Doing this will, I hope, stop that \"scalar deleting destructor\" error that's probably caused by an AddRef()/Release() mis-match.</p>\n\n<p>Anyway, try the above and see if pParentElement is null or not. If it is, the next thing I'd suggest is calling get_nodeType() on pParentNode to see what sort of node it really is. This might give a clue as to whether the XPath is not returning what you expect.</p>\n"
},
{
"answer_id": 289207,
"author": "Greg Domjan",
"author_id": 37558,
"author_profile": "https://Stackoverflow.com/users/37558",
"pm_score": 4,
"selected": true,
"text": "<p>I don't see anything wrong with what you have written.</p>\n\n<p>The smart com pointers will help you convert if they can, you don't have to write the query interface yourself.</p>\n\n<pre><code>MSXML2::IXMLDOMNodePtr pParentNode = pParameterElement->selectSingleNode(\"parent\");\nMSXML2::IXMLDOMElementPtr pParentElement( pParentNode );\n</code></pre>\n\n<p>Using the Ptr types is a bit painfull in my opinion, though the MSXML interface favours them.\nHere is an equivelant example using ATL</p>\n\n<pre><code>CComPtr<IXMLDOMNode> node = ...;\nCComQIPtr<IXMLDOMElement> elementNode( node );\n\nif( elementNode ) { \n// it was an element!\n} else { \n// it's something else try again? \n}\n</code></pre>\n\n<p>The other attempt would look like...</p>\n\n<pre><code>CComPtr<IXMLDOMNamedNodeMap> attributes;\nnode->get_attributes( &attributes );\nif( attributes ) {\n _bstr_t name( L\"category\" );\n attributes->getNamedItem(name);\n}\n</code></pre>\n\n<p>And it's COM, it's always hard to use in C++ :(</p>\n"
},
{
"answer_id": 67619504,
"author": "xianzhi gao",
"author_id": 15150609,
"author_profile": "https://Stackoverflow.com/users/15150609",
"pm_score": 0,
"selected": false,
"text": "<p><code>CComPtr</code> is necessary for <code>IXMLDOMNamedNodeMap</code>, otherwise there would be a exception:</p>\n<p>object of abstract class type <code>IXMLDOMNamedNodeMap</code> is not allowed</p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288465",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37481/"
] |
I'm building an XML DOM document in C++. My problem is this: I execute an XPATH query from an Element in my Document, which I know will return another Element. The elementPtr->selectSingleNode call returns an IXMLDOMNode. How can I gain access to the attributes of this node?
Part of me wants to downcast the Node to an Element, but I couldn't get the cast to work.
I tried
```
MSXML2::IXMLDOMElementPtr pParentElement;
pParentNode->QueryInterface(__uuidof(MSXML2::IXMLDOMElement),
(void**) &pParentElement);
```
Which results in the following runtime error:
```
0x0057cc58 _com_error::`scalar deleting destructor'(unsigned int)
```
The other route I tried was to just use nodes:
```
MSXML2::IXMLDOMNodePtr pParentNode =
pParameterElement->selectSingleNode("parent");
MSXML2::IXMLDOMNamedNodeMap* pParentAttributes;
pParentNode->get_attributes(&pParentAttributes);
MSXML2::IXMLDOMNodePtr pCategoryNameNode =
pParentAttributes->getNamedItem("Category");
VARIANT value;
pCategoryNameNode->get_nodeValue(&value);
CString categoryName = value;
```
This fails at "parentNode->get\_attributes()".
It seems like I'm missing something; the API should not be this hard to use.
--edit--
What I was missing was that the selectSingleNode call was failing, leaving me with a NULL pointer. You can't call QueryInterface on that, neither can you call get\_attributes on it :P
I've selected the answer that fits the question that I asked, not the answer that helped me to realise that I asked the wrong question.
|
I don't see anything wrong with what you have written.
The smart com pointers will help you convert if they can, you don't have to write the query interface yourself.
```
MSXML2::IXMLDOMNodePtr pParentNode = pParameterElement->selectSingleNode("parent");
MSXML2::IXMLDOMElementPtr pParentElement( pParentNode );
```
Using the Ptr types is a bit painfull in my opinion, though the MSXML interface favours them.
Here is an equivelant example using ATL
```
CComPtr<IXMLDOMNode> node = ...;
CComQIPtr<IXMLDOMElement> elementNode( node );
if( elementNode ) {
// it was an element!
} else {
// it's something else try again?
}
```
The other attempt would look like...
```
CComPtr<IXMLDOMNamedNodeMap> attributes;
node->get_attributes( &attributes );
if( attributes ) {
_bstr_t name( L"category" );
attributes->getNamedItem(name);
}
```
And it's COM, it's always hard to use in C++ :(
|
288,467 |
<p>I am trying to link the as3corelib library to use their JSON functionality following <a href="http://www.mikechambers.com/blog/2006/03/28/tutorial-using-json-with-flex-2-and-actionscript-3/" rel="nofollow noreferrer">this tutorial</a>. But am having trouble compiling it. My command looks like:</p>
<pre>
mxmlc --strict=true -library-path+=as3corelib.swc --file-specs myapp.mxml
</pre>
<p>But I am getting this error:</p>
<pre>
_divided_mx_managers_SystemManager.as(13): col: 14 Error: Interface method getVisibleApplicationRect in namespace mx.managers:ISystemManager not implemented by
class _divided_mx_managers_SystemManager.
public class _divided_mx_managers_SystemManager
</pre>
<p>What is the problem?</p>
<p><em>Update: Is this because I am using Flex 3? The tutorial seems to be for Flex 2. If so, what do I need to do for Flex 3?</em></p>
|
[
{
"answer_id": 288576,
"author": "jdoklovic",
"author_id": 34336,
"author_profile": "https://Stackoverflow.com/users/34336",
"pm_score": 0,
"selected": false,
"text": "<p>Are you using the flex Gubmo sdk?\nLooks like the method it's complaining about is in an interface that's part of Gumbo.\nIf so, then as3corelib probably won't work with it.</p>\n"
},
{
"answer_id": 288765,
"author": "airportyh",
"author_id": 5304,
"author_profile": "https://Stackoverflow.com/users/5304",
"pm_score": 1,
"selected": false,
"text": "<p>I found an older version of the library bundled with some tutorial which worked. Submitted a bug report to as3corelib, of course I am not entirely sure how valid the bug is.</p>\n"
},
{
"answer_id": 291307,
"author": "Ryan Guill",
"author_id": 7186,
"author_profile": "https://Stackoverflow.com/users/7186",
"pm_score": 1,
"selected": false,
"text": "<p>If you are using Flex Builder 3 you can actually just take the swc file and put it in the libs directory. This will automatically add it to your classpath and you should be able to use it from then on. You may need to subsequently do a clean on the project to make sure it takes it in though.</p>\n"
},
{
"answer_id": 4989042,
"author": "Savio Sebastian",
"author_id": 614902,
"author_profile": "https://Stackoverflow.com/users/614902",
"pm_score": 1,
"selected": false,
"text": "<p>I faced a similar issue in Flex builder 4. I had to put the as3corelib sources into my source code for it to work alright.</p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5304/"
] |
I am trying to link the as3corelib library to use their JSON functionality following [this tutorial](http://www.mikechambers.com/blog/2006/03/28/tutorial-using-json-with-flex-2-and-actionscript-3/). But am having trouble compiling it. My command looks like:
```
mxmlc --strict=true -library-path+=as3corelib.swc --file-specs myapp.mxml
```
But I am getting this error:
```
_divided_mx_managers_SystemManager.as(13): col: 14 Error: Interface method getVisibleApplicationRect in namespace mx.managers:ISystemManager not implemented by
class _divided_mx_managers_SystemManager.
public class _divided_mx_managers_SystemManager
```
What is the problem?
*Update: Is this because I am using Flex 3? The tutorial seems to be for Flex 2. If so, what do I need to do for Flex 3?*
|
I found an older version of the library bundled with some tutorial which worked. Submitted a bug report to as3corelib, of course I am not entirely sure how valid the bug is.
|
288,508 |
<p>Does Xcode support anything akin to Visual Studio style <code>#region</code> directives for arbitrary code folding?</p>
|
[
{
"answer_id": 288530,
"author": "Jason Coco",
"author_id": 34218,
"author_profile": "https://Stackoverflow.com/users/34218",
"pm_score": 7,
"selected": true,
"text": "<p>No, you can only fold code on various defined scoping levels in Xcode.</p>\n\n<p>You can use little tricks to make navigating via the function menu easier, though.</p>\n\n<pre><code>#pragma mark\n</code></pre>\n\n<p>Allows you to create a grouping where the label following mark will show up in the function menu. If the label is a hyphen, a separator is inserted into the function menu.</p>\n\n<p>Also, the following labels in comments will show up in the function menu:</p>\n\n<pre><code>// MARK:\n// TODO:\n// FIXME:\n// !!!:\n// ???:\n</code></pre>\n\n<p>Obviously since #pragma mark is not really portable, if you're building a portable application and need it to work with a compiler that doesn't just ignore #pragma directives that it doesn't understand, the comment-style mark is a decent alternative.</p>\n"
},
{
"answer_id": 716751,
"author": "willc2",
"author_id": 23973,
"author_profile": "https://Stackoverflow.com/users/23973",
"pm_score": 4,
"selected": false,
"text": "<p>I am going to hell for this but here goes:</p>\n\n<p>At the top of a given file, put</p>\n\n<pre><code>#define FOLD 1\n</code></pre>\n\n<p>Wherever you want to fold something, wrap it in an if block like so:</p>\n\n<pre><code>if(FOLD) {\n // your code to hide\n // more code\n}\n</code></pre>\n\n<p>That will let you fold it away out of sight.</p>\n"
},
{
"answer_id": 717413,
"author": "cdespinosa",
"author_id": 25972,
"author_profile": "https://Stackoverflow.com/users/25972",
"pm_score": 2,
"selected": false,
"text": "<p>That won't work in the place you want it most, that is, around groups of functions or methods. </p>\n\n<p>It may be useful inside a long, linear method with no internal conditionals or loops, but such methods aren't common in general Mac OS X UI code, though if you're writing some big numeric or graphics-crunching code it could help group things.</p>\n\n<p>And the if(fold) is entirely superfluous. Just use the braces inside a method or function and Xcode will fold them.</p>\n"
},
{
"answer_id": 11116240,
"author": "Norbert Nemec",
"author_id": 295690,
"author_profile": "https://Stackoverflow.com/users/295690",
"pm_score": -1,
"selected": false,
"text": "<p>One nice solution I just found:</p>\n\n<p>Put your project into one big namespace.\nClose and reopen this namespace for the individual sections of your source file:</p>\n\n<pre><code>namespace myproj { // members of class MyClassA\n\nvoid MyClassA::dosomething()\n{\n}\n\nvoid MyClassA::dosomethingelse()\n{\n}\n\n} // members of class MyClassA\nnamespace myproj { // members of MyClassB\n\nvoid MyClassB::dosomething()\n{\n}\n\nvoid MyClassB::dosomethingelse()\n{\n}\n\n} // members of MyClassB\n</code></pre>\n"
},
{
"answer_id": 15727411,
"author": "Kibernetik",
"author_id": 1256878,
"author_profile": "https://Stackoverflow.com/users/1256878",
"pm_score": 0,
"selected": false,
"text": "<p>Put your desired code inside brackets { }, and it will become a folding zone.</p>\n\n<p>But you have to keep in mind that brackets also define variables scope, so this code should not have variables declarations which will be used outside these brackets.</p>\n"
},
{
"answer_id": 23259651,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Try this way :</p>\n\n<pre><code>//region title1\n{\n //region Subtitl1\n {\n\n }\n //region Subtitl2\n {\n\n }\n}\n</code></pre>\n\n<p>It can do like that :</p>\n\n<p><img src=\"https://i.stack.imgur.com/xqlWN.png\" alt=\"It can do like that :\"></p>\n"
},
{
"answer_id": 39415847,
"author": "Carter Medlin",
"author_id": 324479,
"author_profile": "https://Stackoverflow.com/users/324479",
"pm_score": 1,
"selected": false,
"text": "<p>Without support for .Net style regions, being able to collapse all your functions at the same time is the next best thing.</p>\n\n<p><kbd>command</kbd>-<kbd>option</kbd>-<kbd>shift</kbd>-<kbd>left arrow</kbd>\nto collapse all.</p>\n\n<p><kbd>command</kbd>-<kbd>option</kbd>-<kbd>shift</kbd>-<kbd>right arrow</kbd>\nto expand all.</p>\n\n<p>Xcode will remember the last state of collapsed functions.</p>\n"
},
{
"answer_id": 64884108,
"author": "Yaman",
"author_id": 847769,
"author_profile": "https://Stackoverflow.com/users/847769",
"pm_score": 1,
"selected": false,
"text": "<p>A useful option in XCode 12 (maybe before), is an option in preferences "Code Folding Ribbon"</p>\n<p><a href=\"https://i.stack.imgur.com/i842c.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/i842c.jpg\" alt=\"Code folding ribbon\" /></a></p>\n<p>When you check it, the source code looks like this</p>\n<p><a href=\"https://i.stack.imgur.com/745Hw.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/745Hw.jpg\" alt=\"Ribbon in code\" /></a></p>\n<p>When you hover the mouse over this ribbon, you get foldable regions based on brackets, like this</p>\n<p><a href=\"https://i.stack.imgur.com/0qX71.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/0qX71.jpg\" alt=\"Foldable ribbon\" /></a></p>\n<p>When you click the Ribbon, it folds the bracket region, like this</p>\n<p><a href=\"https://i.stack.imgur.com/IirfE.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/IirfE.jpg\" alt=\"Folded ribbon\" /></a></p>\n<p>Its not as the regions in Visual Studio, where you can place them wherever you want, but they're good enough to tidy up your code files.</p>\n"
},
{
"answer_id": 71515421,
"author": "Rob Barber",
"author_id": 4313998,
"author_profile": "https://Stackoverflow.com/users/4313998",
"pm_score": 1,
"selected": false,
"text": "<p>To answer your question...No. And It drives me nuts.</p>\n<p>If you have the opportunity/ability you can use <a href=\"https://www.jetbrains.com/objc/\" rel=\"nofollow noreferrer\">AppCode</a> for this. I've been using it for a few years and it usually beats Xcode in many areas.</p>\n<p>Also I specifically use AppCode because of these features:</p>\n<ul>\n<li>Ability to use regions</li>\n<li>Searching classes, text and usages is MUCH faster.</li>\n<li>Refactoring is also faster.</li>\n<li>Cleaner and more customizable UI.</li>\n<li>Tabs are handled (in my opinion) much better than in Xcode.</li>\n<li>FOLDING. You can actually change what levels of folding you want. Why Apple thought there should be no quick-key to fold extensions is beyond me. And fold ribbons? Really Apple? Yes they're pretty and all but most professionals use hotkeys for everything.</li>\n<li>Better GIT integration.</li>\n<li>Support for live updates in SwiftUI</li>\n<li>If you use other Jetbrains IDE's like PyCharm or Android Studio the UI is exactly the same.</li>\n</ul>\n<p>Some downsides of AppCode:</p>\n<ul>\n<li>Some things that work in Xcode aren't supported\n<ul>\n<li>Visual <code>#colorLiteral()</code>. When using them they don't show a color picker.</li>\n<li>No Storyboard support. Annoying to have to open up Xcode. If you write your UI in code this is a moot point.</li>\n</ul>\n</li>\n<li>Editing .plist files isn't as nice. Doable, but not nice.</li>\n<li>Initial indexing can take a while.</li>\n<li>Cost. But I would argue the time savings in just navigation will compensate for this.</li>\n</ul>\n<p>Kind of a lot for a simple question but I think it's nice having alternatives.</p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13932/"
] |
Does Xcode support anything akin to Visual Studio style `#region` directives for arbitrary code folding?
|
No, you can only fold code on various defined scoping levels in Xcode.
You can use little tricks to make navigating via the function menu easier, though.
```
#pragma mark
```
Allows you to create a grouping where the label following mark will show up in the function menu. If the label is a hyphen, a separator is inserted into the function menu.
Also, the following labels in comments will show up in the function menu:
```
// MARK:
// TODO:
// FIXME:
// !!!:
// ???:
```
Obviously since #pragma mark is not really portable, if you're building a portable application and need it to work with a compiler that doesn't just ignore #pragma directives that it doesn't understand, the comment-style mark is a decent alternative.
|
288,511 |
<p>The idea is to move all of the right elements into the left and the left into the right with an empty space in the middle. The elements can either jump over one or two pieces into an empty space. </p>
<pre><code>LLL[ ]RRR
</code></pre>
<p>I'm trying to think of a heuristic for this task. Is the heuristic meant to aid in finding a possible solution, or actually return a number of moves as the solution? How would I express such a heuristic?</p>
|
[
{
"answer_id": 288522,
"author": "EBGreen",
"author_id": 1358,
"author_profile": "https://Stackoverflow.com/users/1358",
"pm_score": 1,
"selected": false,
"text": "<p>Are you looking for a heuristic or an algorithm? A heuristic may or may not solve a given problem. It is really just intended to point you in the direction that the solution probably lies in. An algorithm really should solve a given problem.</p>\n"
},
{
"answer_id": 288554,
"author": "SquareCog",
"author_id": 15962,
"author_profile": "https://Stackoverflow.com/users/15962",
"pm_score": 4,
"selected": true,
"text": "<p>Sounds like you are a bit confused about what a heuristic is.</p>\n\n<p>A rough definition is \"a simplifying assumption\" or \"a decent guess\"</p>\n\n<p>For example, let's say you have to put together a basketball team, and you have fact sheets on people who want to play that list their contact info, birth date, and height. You could hold tryouts where you test each candidate's specific skills; that would require bringing in all the candidates, though, and that could take a long time. You use a heuristic to narrow the search -- only call people who are at least 6'2\" tall. This might ignore some great basketball players, but it's a pretty decent guess.</p>\n\n<p>Another example of a heuristic: you are trying to use the smallest number of coins to pay a bill. The heuristic (a simplifying approach) is to pick the coin with the biggest value (which is less than the remaining bill) first, subtract the value from the bill, and repeat. This is not guaranteed to work every time, but it'll get you to the right neighborhood most of the time.</p>\n\n<p>A heuristic for your problem might be \"never move Ls to the right, and never move Rs to the left\" -- it narrows the \"search space\" of all possible moves by eliminating some of the possibilities from the outset.</p>\n"
},
{
"answer_id": 391663,
"author": "Wartin",
"author_id": 48778,
"author_profile": "https://Stackoverflow.com/users/48778",
"pm_score": 0,
"selected": false,
"text": "<p>A heuristic is generally a \"hint\" which usually (but not always) will guide your procedure to the correct direction. Using heuristics speeds up your procedures (your algorithms), again, <strong>usually</strong>, but not always. It's like an \"advice\" to the algorithm which is correct more often than not.</p>\n\n<p>I'm not sure what you are looking for, as the description is a little vague. If you want the algorithm, you will need to study what effect a particular move will have to the current situation and a way to step forward for all possible moves each time, in effect traversing a tree of states (ie. states that will evolve if you make a particular sequence of moves).</p>\n\n<p>You can also see that it possibly matters <strong>how close</strong> the current position is to what you want to achieve (your desired final position).So instead of calculating all the possible paths from your initial state until you find the final state, you can guide your algorithm based on the heuristic \"how close is the current state to the desired one\" and only traverse a part of the tree.</p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
The idea is to move all of the right elements into the left and the left into the right with an empty space in the middle. The elements can either jump over one or two pieces into an empty space.
```
LLL[ ]RRR
```
I'm trying to think of a heuristic for this task. Is the heuristic meant to aid in finding a possible solution, or actually return a number of moves as the solution? How would I express such a heuristic?
|
Sounds like you are a bit confused about what a heuristic is.
A rough definition is "a simplifying assumption" or "a decent guess"
For example, let's say you have to put together a basketball team, and you have fact sheets on people who want to play that list their contact info, birth date, and height. You could hold tryouts where you test each candidate's specific skills; that would require bringing in all the candidates, though, and that could take a long time. You use a heuristic to narrow the search -- only call people who are at least 6'2" tall. This might ignore some great basketball players, but it's a pretty decent guess.
Another example of a heuristic: you are trying to use the smallest number of coins to pay a bill. The heuristic (a simplifying approach) is to pick the coin with the biggest value (which is less than the remaining bill) first, subtract the value from the bill, and repeat. This is not guaranteed to work every time, but it'll get you to the right neighborhood most of the time.
A heuristic for your problem might be "never move Ls to the right, and never move Rs to the left" -- it narrows the "search space" of all possible moves by eliminating some of the possibilities from the outset.
|
288,512 |
<p>Anyone knows a good way to resize any window to for example 640x480?</p>
<p>Reason is, of course, screencasting.</p>
<p>Under windows I've used ZoneSize from donationcoder. (Btw: For Firefox it's easy, just use the web developer toolbar.)</p>
|
[
{
"answer_id": 288537,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 7,
"selected": true,
"text": "<p>Use the <a href=\"http://www.sweb.cz/tripie/utils/wmctrl/\" rel=\"noreferrer\">wmctrl</a> command:</p>\n\n<p>To list the windows:</p>\n\n<pre><code>$ wmctrl -l\n0x00c00003 -1 rgamble-desktop Bottom Expanded Edge Panel\n0x00c00031 -1 rgamble-desktop Top Expanded Edge Panel\n0x00e00022 -1 rgamble-desktop Desktop\n0x0260007c 0 rgamble-desktop Google - Mozilla Firefox\n</code></pre>\n\n<p>To resize a window based on its title:</p>\n\n<pre><code>wmctrl -r Firefox -e 0,0,0,640,480\n</code></pre>\n\n<p>The arguments to the resize option are <code>gravity,X,Y,width,height</code> so this will place the window at the top-left corner of the screen and resize it to 640X480.</p>\n"
},
{
"answer_id": 59234259,
"author": "NVRM",
"author_id": 2494754,
"author_profile": "https://Stackoverflow.com/users/2494754",
"pm_score": 2,
"selected": false,
"text": "<p>Using wmctrl, there is also some pre defined states:</p>\n\n<p>If a window is currently in the state <code>maximized</code>, it won't respond to a resizing in pixels using the <code>-e</code> parameter^. This is where the <code>-b</code> param is useful.</p>\n\n<blockquote>\n <p>The -b option expects a list of comma separated parameters:\n \"(remove|add|toggle),PROP1,PROP2]\"</p>\n</blockquote>\n\n<p>Example:</p>\n\n<pre><code>wmctrl -r Firefox -b toggle,maximized_horz\n</code></pre>\n\n<p>States available:</p>\n\n<pre><code>wmctrl -r Firefox -b toggle,maximized_vert\n ----- ---------------\n remove modal\n add sticky\n toggle maximized_vert\n maximized_horz\n shaded\n skip_taskbar\n skip_pager\n hidden\n fullscreen\n above\n below\n</code></pre>\n\n<hr>\n\n<p>About the precise question, the -e param allow resizing by values as follow:</p>\n\n<p>Gravity, position X, position Y, window width, window height </p>\n\n<pre><code>// gravity,x,y,w,h\nwmctrl -r \"Resizing\" -e 0,0,0,640,480\n</code></pre>\n"
},
{
"answer_id": 63075575,
"author": "BZZZZ",
"author_id": 13989171,
"author_profile": "https://Stackoverflow.com/users/13989171",
"pm_score": 1,
"selected": false,
"text": "<p>sh script that uses wmctrl to resize windows:</p>\n<pre><code>#!/usr/bin/sh\nwmctrl -l\necho ""\nread -p "window id -> " wid\nread -p "width -> " ww\nread -p "height -> " wh\nwmctrl -i -r $wid -e 0,0,0,$ww,$wh\necho "Done!"\n</code></pre>\n"
},
{
"answer_id": 71535848,
"author": "user18510353",
"author_id": 18510353,
"author_profile": "https://Stackoverflow.com/users/18510353",
"pm_score": 2,
"selected": false,
"text": "<p><code>wmctrl -r ":ACTIVE:" -e "0,$(xdotool getactivewindow getwindowgeometry|egrep -o '[0-9]+,[^ ]+'),970,600"</code></p>\n<p>targets an <strong>active</strong> window (i.e, the terminal used for the command)\nresizes to 970 (<strong>width</strong>) and 600 (<strong>height</strong>)</p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9987/"
] |
Anyone knows a good way to resize any window to for example 640x480?
Reason is, of course, screencasting.
Under windows I've used ZoneSize from donationcoder. (Btw: For Firefox it's easy, just use the web developer toolbar.)
|
Use the [wmctrl](http://www.sweb.cz/tripie/utils/wmctrl/) command:
To list the windows:
```
$ wmctrl -l
0x00c00003 -1 rgamble-desktop Bottom Expanded Edge Panel
0x00c00031 -1 rgamble-desktop Top Expanded Edge Panel
0x00e00022 -1 rgamble-desktop Desktop
0x0260007c 0 rgamble-desktop Google - Mozilla Firefox
```
To resize a window based on its title:
```
wmctrl -r Firefox -e 0,0,0,640,480
```
The arguments to the resize option are `gravity,X,Y,width,height` so this will place the window at the top-left corner of the screen and resize it to 640X480.
|
288,513 |
<p>Here is what I am trying to do:
Given a date, a day of the week, and an integer <code>n</code>, determine whether the date is the <code>n</code>th day of the month.</p>
<p>For example:</p>
<ul>
<li><p>input of <code>1/1/2009,Monday,2</code>
would be false because <code>1/1/2009</code> is not the second Monday</p></li>
<li><p>input of
<code>11/13/2008,Thursday,2</code>
would return true because it is the second Thursday</p></li>
</ul>
<p>How can I improve this implementation?</p>
<pre><code>private bool NthDayOfMonth(DateTime date, DayOfWeek dow, int n)
{
int d = date.Day;
return date.DayOfWeek == dow && (d/ 7 == n || (d/ 7 == (n - 1) && d % 7 > 0));
}
</code></pre>
|
[
{
"answer_id": 288529,
"author": "Robert Wagner",
"author_id": 10784,
"author_profile": "https://Stackoverflow.com/users/10784",
"pm_score": 5,
"selected": true,
"text": "<p>You could change the check of the week so the function would read:</p>\n\n<pre><code>private bool NthDayOfMonth(DateTime date, DayOfWeek dow, int n){\n int d = date.Day;\n return date.DayOfWeek == dow && (d-1)/7 == (n-1);\n}\n</code></pre>\n\n<p>Other than that, it looks pretty good and efficient.</p>\n"
},
{
"answer_id": 288535,
"author": "Andrew Bullock",
"author_id": 28543,
"author_profile": "https://Stackoverflow.com/users/28543",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/aa227532(VS.60).aspx\" rel=\"nofollow noreferrer\">Here</a> is what the MSDN have to say. Its VB, but it translates easily.</p>\n"
},
{
"answer_id": 288542,
"author": "George Stocker",
"author_id": 16587,
"author_profile": "https://Stackoverflow.com/users/16587",
"pm_score": 3,
"selected": false,
"text": "<p>The answer is from <a href=\"http://blog.lab49.com/archives/206\" rel=\"nofollow noreferrer\">this website</a>. Copy/pasted here in case that site is ever lost.</p>\n\n<pre><code>public static DateTime FindTheNthSpecificWeekday(int year, int month,int nth, System.DayOfWeek day_of_the_week)\n{\n // validate month value\n if(month < 1 || month > 12)\n {\n throw new ArgumentOutOfRangeException(\"Invalid month value.\");\n }\n\n // validate the nth value\n if(nth < 0 || nth > 5)\n {\n throw new ArgumentOutOfRangeException(\"Invalid nth value.\");\n }\n\n // start from the first day of the month\n DateTime dt = new DateTime(year, month, 1);\n\n // loop until we find our first match day of the week\n while(dt.DayOfWeek != day_of_the_week)\n {\n dt = dt.AddDays(1);\n }\n\n if(dt.Month != month)\n {\n // we skip to the next month, we throw an exception\n throw new ArgumentOutOfRangeException(string.Format(\"The given month has less than {0} {1}s\", nth, day_of_the_week));\n }\n\n // Complete the gap to the nth week\n dt = dt.AddDays((nth - 1) * 7);\n\n return dt;\n}\n</code></pre>\n"
},
{
"answer_id": 291797,
"author": "waynecolvin",
"author_id": 35658,
"author_profile": "https://Stackoverflow.com/users/35658",
"pm_score": 1,
"selected": false,
"text": "<p>It looks like the language supplies date/day methods for a given date. If anybody was interested you can read about <a href=\"http://en.wikipedia.org/wiki/Zeller%27s_congruence\" rel=\"nofollow noreferrer\" title=\"Calender Algorithm\">Zeller's congruence</a>.</p>\n\n<p>I don't think that's what they wanted you to do but you could find the day of week of the first day of a month from that. Now that I thought about it you could find the day of week for the given day as <code>N</code> and get that modulo 7.</p>\n\n<p>Oh wait, is that the Nth occurance of a day of the week (like Sunday) or like the Nth <strong>weekday</strong> of the month! Okay I see the examples.</p>\n\n<p>Maybe it would make a difference if you could construct a date such as the 1st of a month..</p>\n\n<p>Given that it is <em>Nth occurance of a day of the week</em>, and that you can't fiddle with whatever datetime datatype, and that you have access to both a get day of week and get day of month functions. Would Sunday be a zero? </p>\n\n<p>1) First, the day of the week would have to match the day of the week given.<br>\n2) N would have to be at least 1 and at most 4.<br>\n3) The day of the month would range between n*7*dayOfWeek + 1 and n*7*dayOfWeek + 6 for the same n.<br>\n - Let me think about that. If Sunday was the first.. 0*7*0+1 = 1 and Saturday the 6th would be 0*7*0+6. </p>\n\n<p>Think 1 and 3 above are sufficient since a get day of month function shouldn't violate 2.</p>\n\n<pre><code>(* first try, this code sucks *)\n\nfunction isNthGivenDayInMonth(date : dateTime;\n dow : dayOfWeek;\n N : integer) : boolean;\n var B, A : integer (* on or before and after day of month *)\n var Day : integer (* day of month *)\n begin\n B := (N-1)*7 + 1; A := (N-1)*7 + 6;\n D := getDayOfMonth(date);\n if (dow <> getDayOfWeek(date) \n then return(false)\n else return( (B <= Day) and (A >= Day) );\n end; (* function *)\n</code></pre>\n\n<p>Hope there isn't a bug in that lol!<br>\n<strong>[edit: Saturday would have been the 7th, and the upper bound above <code>(N-1)*7 + 7</code>.]</strong><br>\n Your solution looks like it would match 2 different weeks? Looks like it would always return zero for Sundays? Should have done pseudocode in C#.. short circuit && is like my if.. \nhey shouldn't Sunday the first match for N = 1 in months that start on Sunday? </p>\n\n<pre><code> d/ 7 == n\n</code></pre>\n\n<p>That would result in <code>(either 0 or 1)/7 == 1</code>, that can't be right! Your <code>||</code> catches the <code>(n-1)</code> also, Robert has that. Go with Robert Wagner's answer! It's only 2 lines, short is good! Having <code>(Day-1) mod 7</code><br>\n<strong>[edit: <code>(Day-1) div 7</code>]</strong> \n eliminates my unnecessary variables and 2 lines of setup. </p>\n\n<p>For the record this should be checked for boundary cases and so forth like what if August 31st was a Sunday or Saturday.<br>\n<strong>[edit: Should have checked the end of week case too. Sorry!]</strong></p>\n"
},
{
"answer_id": 520728,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>In <a href=\"https://stackoverflow.com/questions/288513/how-do-i-determine-if-a-given-date-is-nth-weekday-of-the-month/288542#288542\">this answer</a>, the following code needs to be flipped:</p>\n\n<pre><code>// Complete the gap to the nth week\ndt = dt.AddDays((nth - 1) * 7);\n\nif(dt.Month != month)\n{\n// we skip to the next month, we throw an exception\nthrow new ArgumentOutOfRangeException(βThe given month has less than β nth.ToString() β β\nday_of_the_week.ToString() βsβ);\n}\n</code></pre>\n"
},
{
"answer_id": 3547011,
"author": "Chirag Darji",
"author_id": 428346,
"author_profile": "https://Stackoverflow.com/users/428346",
"pm_score": 1,
"selected": false,
"text": "<p>You can find a function which returns a date for the nth occurrence of particular week day in any month.</p>\n\n<p>See <a href=\"http://chiragrdarji.wordpress.com/2010/08/23/find-second-saturday-and-fourth-saturday-of-month/\" rel=\"nofollow noreferrer\">http://chiragrdarji.wordpress.com/2010/08/23/find-second-saturday-and-fourth-saturday-of-month/</a></p>\n"
},
{
"answer_id": 26392656,
"author": "reexmonkey",
"author_id": 914512,
"author_profile": "https://Stackoverflow.com/users/914512",
"pm_score": 0,
"selected": false,
"text": "<p>Most of the answers above are partially accurate or unnecessarily complex.\nYou could try this simpler function, which also checks if the given date is the last but Nth day of the month.</p>\n\n<pre><code> public static bool IsNthDayofMonth(this DateTime date, DayOfWeek weekday, int N)\n {\n if (N > 0)\n {\n var first = new DateTime(date.Year, date.Month, 1);\n return (date.Day - first.Day)/ 7 == N - 1 && date.DayOfWeek == weekday;\n }\n else\n {\n\n var last = new DateTime(date.Year, date.Month, 1).AddMonths(1).AddDays(-1);\n return (last.Day - date.Day) / 7 == (Math.Abs(N) - 1) && date.DayOfWeek == weekday;\n }\n</code></pre>\n"
},
{
"answer_id": 35584324,
"author": "B. Clay Shannon-B. Crow Raven",
"author_id": 875317,
"author_profile": "https://Stackoverflow.com/users/875317",
"pm_score": 0,
"selected": false,
"text": "<p>In case you want a list of dates for a span of time (not just one) for the Nth DayOfWeek of a Month, you can use this:</p>\n\n<pre><code>internal static List<DateTime> GetDatesForNthDOWOfMonth(int weekNum, DayOfWeek DOW, DateTime beginDate, DateTime endDate)\n{\n List<DateTime> datesForNthDOWOfMonth = new List<DateTime>();\n int earliestDayOfMonth = 1;\n int latestDayOfMonth = 7;\n DateTime currentDate = beginDate;\n\n switch (weekNum)\n {\n case 1:\n earliestDayOfMonth = 1;\n latestDayOfMonth = 7;\n break;\n case 2:\n earliestDayOfMonth = 8;\n latestDayOfMonth = 14;\n break;\n case 3:\n earliestDayOfMonth = 15;\n latestDayOfMonth = 21;\n break;\n case 4:\n earliestDayOfMonth = 22;\n latestDayOfMonth = 28;\n break;\n }\n\n while (currentDate < endDate)\n {\n DateTime dateToInc = currentDate;\n DateTime endOfMonth = new DateTime(dateToInc.Year, dateToInc.Month, DateTime.DaysInMonth(dateToInc.Year, dateToInc.Month));\n bool dateFound = false;\n while (!dateFound)\n {\n dateFound = dateToInc.DayOfWeek.Equals(DOW);\n if (dateFound)\n {\n if ((dateToInc.Day >= earliestDayOfMonth) && \n (dateToInc.Day <= latestDayOfMonth))\n {\n datesForNthDOWOfMonth.Add(dateToInc);\n }\n }\n if (dateToInc.Date.Equals(endOfMonth.Date)) continue;\n dateToInc = dateToInc.AddDays(1);\n }\n currentDate = new DateTime(currentDate.Year, currentDate.Month, 1);\n currentDate = currentDate.AddMonths(1);\n }\n return datesForNthDOWOfMonth;\n}\n</code></pre>\n\n<p>...and call it this way:</p>\n\n<pre><code>// This is to get the 1st Monday in each month from today through one year from today\nDateTime beg = DateTime.Now;\nDateTime end = DateTime.Now.AddYears(1);\nList<DateTime> dates = GetDatesForNthDOWOfMonth(1, DayOfWeek.Monday, beg, end);\n// To see the list of dateTimes, for verification\nforeach (DateTime d in dates)\n{\n MessageBox.Show(string.Format(\"Found {0}\", d.ToString()));\n}\n</code></pre>\n\n<p>You could get the 2nd Friday of each month like so:</p>\n\n<pre><code>List<DateTime> dates = GetDatesForNthDOWOfMonth(2, DayOfWeek.Friday, beg, end);\n</code></pre>\n\n<p>...etc.</p>\n"
},
{
"answer_id": 72108598,
"author": "Darrel K.",
"author_id": 2746057,
"author_profile": "https://Stackoverflow.com/users/2746057",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a simple DateTime extension method to get the nth occurrence in a month.</p>\n<pre><code>/// <summary>\n/// Gets the Nth occurrence of the specified weekday in the month.\n/// </summary>\npublic static DateTime GetNthOfWeekDayInMonth(this DateTime dt, DayOfWeek dayOfWeek, int n)\n{\n //Get the first day of the month\n DateTime fd = dt.AddDays(-dt.Day).AddDays(1);\n // Get the FIRST occurrence of the specified weekday in the month.\n fd = dayOfWeek >= fd.DayOfWeek ? fd.AddDays(dayOfWeek - fd.DayOfWeek) : fd.AddDays((7 + ((int)dayOfWeek)) - ((int)fd.DayOfWeek));\n // Get the nth occurrence by adding the weeks\n fd = fd.AddDays((n-1) * 7);\n //Throw exception if you do not want to go past the specified month?\n if (fd.Month != dt.Month) throw new Exception($"There is no {n} week in this month");\n return fd;\n}\n</code></pre>\n<p>Sample:</p>\n<pre><code>new DateTime(2022, 05, 12).GetNthOfWeekDayInMonth(DayOfWeek.Tuesday, 2);\n// Output: [2022/05/10 00:00:00]\n</code></pre>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19038/"
] |
Here is what I am trying to do:
Given a date, a day of the week, and an integer `n`, determine whether the date is the `n`th day of the month.
For example:
* input of `1/1/2009,Monday,2`
would be false because `1/1/2009` is not the second Monday
* input of
`11/13/2008,Thursday,2`
would return true because it is the second Thursday
How can I improve this implementation?
```
private bool NthDayOfMonth(DateTime date, DayOfWeek dow, int n)
{
int d = date.Day;
return date.DayOfWeek == dow && (d/ 7 == n || (d/ 7 == (n - 1) && d % 7 > 0));
}
```
|
You could change the check of the week so the function would read:
```
private bool NthDayOfMonth(DateTime date, DayOfWeek dow, int n){
int d = date.Day;
return date.DayOfWeek == dow && (d-1)/7 == (n-1);
}
```
Other than that, it looks pretty good and efficient.
|
288,540 |
<p>C#: How do you tell which item index is selected in ListView?</p>
|
[
{
"answer_id": 288548,
"author": "Tim Merrifield",
"author_id": 36706,
"author_profile": "https://Stackoverflow.com/users/36706",
"pm_score": 1,
"selected": false,
"text": "<p>Use the SelectedIndex property of the class.</p>\n"
},
{
"answer_id": 288551,
"author": "Cristian Libardo",
"author_id": 16526,
"author_profile": "https://Stackoverflow.com/users/16526",
"pm_score": 2,
"selected": false,
"text": "<p>Have you tried SelectedIndices?</p>\n\n<pre><code>myListView.SelectedIndices\n</code></pre>\n"
},
{
"answer_id": 288555,
"author": "Nathan W",
"author_id": 6335,
"author_profile": "https://Stackoverflow.com/users/6335",
"pm_score": 3,
"selected": true,
"text": "<pre><code>ListView mylistv = new ListView();\nvar index = mylistv.SelectedIndices();\n</code></pre>\n\n<p>That should do it.</p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
C#: How do you tell which item index is selected in ListView?
|
```
ListView mylistv = new ListView();
var index = mylistv.SelectedIndices();
```
That should do it.
|
288,559 |
<p>Even though error_reporting is set to 0, database errors are still being printed to screen. Is there a setting somewhere I can change to disable database error reporting? This is for CodeIgniter v1.6.x</p>
<p><strong>EDIT</strong>: Re: Fixing errors - Um, yes. I want to fix the errors. I get error notices from my error log, not from what my visitors see printed to their screen. That helps no one, and hurts my system's security.</p>
<p><strong>EDIT 2</strong>: Setting error_reporting to 0 does not affect CodeIgniter's built-in error logging class from writing to the error log.</p>
|
[
{
"answer_id": 288641,
"author": "Tom Haigh",
"author_id": 22224,
"author_profile": "https://Stackoverflow.com/users/22224",
"pm_score": 3,
"selected": false,
"text": "<ul>\n<li><p>You don't want to change\nerror_reporting to 0, because that will\nalso suppress errors from being\nlogged.</p></li>\n<li><p>instead you should change\n display_errors to 0</p></li>\n</ul>\n\n<p>This doesn't explain why you are\n getting errors displayed though,\n assuming error_reporting is actually\n 0. Maybe the framework handles these errors</p>\n"
},
{
"answer_id": 288659,
"author": "Eli",
"author_id": 27580,
"author_profile": "https://Stackoverflow.com/users/27580",
"pm_score": 2,
"selected": false,
"text": "<p>You can edit the /errors/db_error.php file under the application directory - that is the template included for DB errors.</p>\n\n<p>However, you should really just fix the errors.</p>\n"
},
{
"answer_id": 288748,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "<p>Found the answer:</p>\n\n<p>In <code>config/database.php:</code></p>\n\n<pre><code>// ['db_debug'] TRUE/FALSE - Whether database errors should be displayed.\n</code></pre>\n\n<p>so: </p>\n\n<pre><code>$db['default']['db_debug'] = FALSE;\n</code></pre>\n\n<p>... should disable.</p>\n"
},
{
"answer_id": 15292463,
"author": "NaturalBornCamper",
"author_id": 1046013,
"author_profile": "https://Stackoverflow.com/users/1046013",
"pm_score": 4,
"selected": false,
"text": "<p>In addition to Ian's answer, to temporarily disable the error messages:</p>\n\n<pre><code>$db_debug = $this->db->db_debug;\n$this->db->db_debug = false;\n\n// Do your sketchy stuff here\n\n$this->db->db_debug = $db_debug;\n</code></pre>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Even though error\_reporting is set to 0, database errors are still being printed to screen. Is there a setting somewhere I can change to disable database error reporting? This is for CodeIgniter v1.6.x
**EDIT**: Re: Fixing errors - Um, yes. I want to fix the errors. I get error notices from my error log, not from what my visitors see printed to their screen. That helps no one, and hurts my system's security.
**EDIT 2**: Setting error\_reporting to 0 does not affect CodeIgniter's built-in error logging class from writing to the error log.
|
Found the answer:
In `config/database.php:`
```
// ['db_debug'] TRUE/FALSE - Whether database errors should be displayed.
```
so:
```
$db['default']['db_debug'] = FALSE;
```
... should disable.
|
288,560 |
<p>I have the following structure:</p>
<pre><code> <StructLayout(LayoutKind.Sequential)> _
Public Structure _WTS_CLIENT_ADDRESS
Public AddressFamily As Integer
<MarshalAs(UnmanagedType.ByValArray, SizeConst:=20)> _
Public Address() As Byte
End Structure
</code></pre>
<p>Which is populated by the following call:</p>
<pre><code> Dim _ClientIPAddress As New _WTS_CLIENT_ADDRESS
Dim rtnPtr As IntPtr
Dim rtncount As Int32
NativeMethods.WTSQuerySessionInformation(CInt(NativeMethods.WTS_CURRENT_SERVER_HANDLE), NativeMethods.WTS_CURRENT_SESSION, NativeMethods.WTS_INFO_CLASS.WTSClientAddress, rtnPtr, rtncount)
'_ClientIPAddress()
_ClientIPAddress = _
CType(System.Runtime.InteropServices.Marshal.PtrToStructure(rtnPtr, GetType(_WTS_CLIENT_ADDRESS)), _WTS_CLIENT_ADDRESS)
</code></pre>
<p>The address byte array is being populated, but I have no idea how to convert it into a useful string or integer values. The MDSN documentation is sparse: <a href="http://msdn.microsoft.com/en-us/library/aa383857(VS.85).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa383857(VS.85).aspx</a></p>
|
[
{
"answer_id": 311934,
"author": "JΓ©rΓ΄me Laban",
"author_id": 26346,
"author_profile": "https://Stackoverflow.com/users/26346",
"pm_score": 3,
"selected": true,
"text": "<p>You're almost there with your code. I agree with you, the MSDN is not quite explicit on what's inside that byte array, but here's what you can do :</p>\n\n<pre><code>IPAddress address = new IPAddress(_ClientIPAddress.Address.Skip(2).Take(4).ToArray());\n</code></pre>\n\n<p>The first two bytes do not seem to be used, but in the case of AF_INET (which is IPv4, or 2) the next four bytes are the IPv4 address of the client.</p>\n\n<p>You might also want to make sure that your code will handle IPv6 (AF_INET6) properly, or handle the fact that AF_INET6 is a likely value. You'll probably need to read 16 bytes instead of 4 for this protocol.</p>\n"
},
{
"answer_id": 1910921,
"author": "Corey",
"author_id": 232499,
"author_profile": "https://Stackoverflow.com/users/232499",
"pm_score": 1,
"selected": false,
"text": "<p>The real answer can be found here. <a href=\"http://www.tech-archive.net/Archive/Windows/microsoft.public.windows.terminal_services/2007-03/msg00474.html\" rel=\"nofollow noreferrer\">http://www.tech-archive.net/Archive/Windows/microsoft.public.windows.terminal_services/2007-03/msg00474.html</a></p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13338/"
] |
I have the following structure:
```
<StructLayout(LayoutKind.Sequential)> _
Public Structure _WTS_CLIENT_ADDRESS
Public AddressFamily As Integer
<MarshalAs(UnmanagedType.ByValArray, SizeConst:=20)> _
Public Address() As Byte
End Structure
```
Which is populated by the following call:
```
Dim _ClientIPAddress As New _WTS_CLIENT_ADDRESS
Dim rtnPtr As IntPtr
Dim rtncount As Int32
NativeMethods.WTSQuerySessionInformation(CInt(NativeMethods.WTS_CURRENT_SERVER_HANDLE), NativeMethods.WTS_CURRENT_SESSION, NativeMethods.WTS_INFO_CLASS.WTSClientAddress, rtnPtr, rtncount)
'_ClientIPAddress()
_ClientIPAddress = _
CType(System.Runtime.InteropServices.Marshal.PtrToStructure(rtnPtr, GetType(_WTS_CLIENT_ADDRESS)), _WTS_CLIENT_ADDRESS)
```
The address byte array is being populated, but I have no idea how to convert it into a useful string or integer values. The MDSN documentation is sparse: <http://msdn.microsoft.com/en-us/library/aa383857(VS.85).aspx>
|
You're almost there with your code. I agree with you, the MSDN is not quite explicit on what's inside that byte array, but here's what you can do :
```
IPAddress address = new IPAddress(_ClientIPAddress.Address.Skip(2).Take(4).ToArray());
```
The first two bytes do not seem to be used, but in the case of AF\_INET (which is IPv4, or 2) the next four bytes are the IPv4 address of the client.
You might also want to make sure that your code will handle IPv6 (AF\_INET6) properly, or handle the fact that AF\_INET6 is a likely value. You'll probably need to read 16 bytes instead of 4 for this protocol.
|
288,564 |
<p>I have a web application project (wap) that is successfully being deployed to a development server by our tfsbuild server.</p>
<p>I'd like the build server to run our collection of webtests after deployment.</p>
<p>What is a best practice (or ANY practice) for doing this?</p>
|
[
{
"answer_id": 311934,
"author": "JΓ©rΓ΄me Laban",
"author_id": 26346,
"author_profile": "https://Stackoverflow.com/users/26346",
"pm_score": 3,
"selected": true,
"text": "<p>You're almost there with your code. I agree with you, the MSDN is not quite explicit on what's inside that byte array, but here's what you can do :</p>\n\n<pre><code>IPAddress address = new IPAddress(_ClientIPAddress.Address.Skip(2).Take(4).ToArray());\n</code></pre>\n\n<p>The first two bytes do not seem to be used, but in the case of AF_INET (which is IPv4, or 2) the next four bytes are the IPv4 address of the client.</p>\n\n<p>You might also want to make sure that your code will handle IPv6 (AF_INET6) properly, or handle the fact that AF_INET6 is a likely value. You'll probably need to read 16 bytes instead of 4 for this protocol.</p>\n"
},
{
"answer_id": 1910921,
"author": "Corey",
"author_id": 232499,
"author_profile": "https://Stackoverflow.com/users/232499",
"pm_score": 1,
"selected": false,
"text": "<p>The real answer can be found here. <a href=\"http://www.tech-archive.net/Archive/Windows/microsoft.public.windows.terminal_services/2007-03/msg00474.html\" rel=\"nofollow noreferrer\">http://www.tech-archive.net/Archive/Windows/microsoft.public.windows.terminal_services/2007-03/msg00474.html</a></p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2424/"
] |
I have a web application project (wap) that is successfully being deployed to a development server by our tfsbuild server.
I'd like the build server to run our collection of webtests after deployment.
What is a best practice (or ANY practice) for doing this?
|
You're almost there with your code. I agree with you, the MSDN is not quite explicit on what's inside that byte array, but here's what you can do :
```
IPAddress address = new IPAddress(_ClientIPAddress.Address.Skip(2).Take(4).ToArray());
```
The first two bytes do not seem to be used, but in the case of AF\_INET (which is IPv4, or 2) the next four bytes are the IPv4 address of the client.
You might also want to make sure that your code will handle IPv6 (AF\_INET6) properly, or handle the fact that AF\_INET6 is a likely value. You'll probably need to read 16 bytes instead of 4 for this protocol.
|
288,573 |
<p>When using regular expressions in Ruby, what is the difference between $1 and \1?</p>
|
[
{
"answer_id": 288595,
"author": "Avdi",
"author_id": 20487,
"author_profile": "https://Stackoverflow.com/users/20487",
"pm_score": 7,
"selected": true,
"text": "<p>\\1 is a backreference which will only work in the same <code>sub</code> or <code>gsub</code> method call, e.g.:</p>\n\n<pre><code>\"foobar\".sub(/foo(.*)/, '\\1\\1') # => \"barbar\"\n</code></pre>\n\n<p>$1 is a global variable which can be used in later code:</p>\n\n<pre><code>if \"foobar\" =~ /foo(.*)/ then \n puts \"The matching word was #{$1}\"\nend\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>\"The matching word was bar\"\n# => nil\n</code></pre>\n"
},
{
"answer_id": 288685,
"author": "Brian Carper",
"author_id": 23070,
"author_profile": "https://Stackoverflow.com/users/23070",
"pm_score": 5,
"selected": false,
"text": "<p>Keep in mind there's a third option, the block form of <code>sub</code>. Sometimes you need it. Say you want to replace some text with the reverse of that text. You can't use $1 because it's not bound quickly enough:</p>\n\n<pre><code>\"foobar\".sub(/(.*)/, $1.reverse) # WRONG: either uses a PREVIOUS value of $1, \n # or gives an error if $1 is unbound\n</code></pre>\n\n<p>You also can't use <code>\\1</code>, because the <code>sub</code> method just does a simple text-substitution of <code>\\1</code> with the appropriate captured text, there's no magic taking place here:</p>\n\n<pre><code>\"foobar\".sub(/(.*)/, '\\1'.reverse) # WRONG: returns '1\\'\n</code></pre>\n\n<p>So if you want to do anything fancy, you should use the block form of <code>sub</code> ($1, $2, $`, $' etc. will be available):</p>\n\n<pre><code>\"foobar\".sub(/.*/){|m| m.reverse} # => returns 'raboof'\n\"foobar\".sub(/(...)(...)/){$1.reverse + $2.reverse} # => returns 'oofrab'\n</code></pre>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288573",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
] |
When using regular expressions in Ruby, what is the difference between $1 and \1?
|
\1 is a backreference which will only work in the same `sub` or `gsub` method call, e.g.:
```
"foobar".sub(/foo(.*)/, '\1\1') # => "barbar"
```
$1 is a global variable which can be used in later code:
```
if "foobar" =~ /foo(.*)/ then
puts "The matching word was #{$1}"
end
```
Output:
```
"The matching word was bar"
# => nil
```
|
288,575 |
<p>I inherited a project that uses SQL Server 200x, wherein a column that stores a value that is always considered as a percentage in the problem domain is stored as its greater than 1 decimal equivalent. For example, <em>70%</em> (0.7, literally) is stored as <em>70</em>, <em>100%</em> as <em>100</em>, etc. Aside from the need to remember to * 0.01 on retrieved values and * 100 before persisting values, it doesn't seem to be a problem in and of itself. <strike>It does make my head explode though</strike>... so is there a good reason for it that I'm missing? Are there compelling reasons to fix it, given that there is a fair amount of code written to work with the pseudo-percentages?</p>
<p>There are a few cases where greater than 100% occurs, but I don't see why the value wouldn't just be stored as 1.05, for example, in those cases.</p>
<p>EDIT: Head feeling better, and slightly smarter. Thanks for all the insights.</p>
|
[
{
"answer_id": 288578,
"author": "Andrew Bullock",
"author_id": 28543,
"author_profile": "https://Stackoverflow.com/users/28543",
"pm_score": 3,
"selected": false,
"text": "<p>If its a byte field then it takes up less room in the db than floating point numbers, but unless you have millions and millions of records, you'll hardly see a difference.</p>\n"
},
{
"answer_id": 288585,
"author": "dkretz",
"author_id": 31641,
"author_profile": "https://Stackoverflow.com/users/31641",
"pm_score": 2,
"selected": false,
"text": "<p>A good guess is because anything you do with integers (storing, calculating, stuffing into an edit for for a user, etc.) is marginally easier and more efficient than doing the same with floating point numbers. And the rounding issues aren't so obvious when you look at the data.</p>\n"
},
{
"answer_id": 288594,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": false,
"text": "<p>Floating point numbers are prone to rounding errors and, therefore, can act \"funny\" in comparisons. If you always want to deal with it as fixed decimal, you could either choose a decimal type, say decimal(5,2), or do the convert and store as int thing that your db does. I'd probably go the decimal route, even though the int would take up less space.</p>\n"
},
{
"answer_id": 288643,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 2,
"selected": false,
"text": "<p>Since floating-point values can't be compared for equality, an integer may have been used to make the SQL simpler.</p>\n\n<p>For example</p>\n\n<pre><code>(0.3==3*.1)\n</code></pre>\n\n<p>is usually False.</p>\n\n<p>However</p>\n\n<pre><code>abs( 0.3 - 3*.1 )\n</code></pre>\n\n<p>Is a tiny number (5.55e-17). But it's pain to have to do everything with <code>(column-SomeValue) BETWEEN -0.0001 AND 0.0001</code> or <code>ABS(column-SomeValue) < 0.0001</code>. You'd rather do <code>column = SomeValue</code> in your WHERE clause.</p>\n"
},
{
"answer_id": 288658,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 1,
"selected": false,
"text": "<p>If these are numbers that end users are likely to see and interact with, percentages are easier to understand than decimals.</p>\n\n<p>This is one of those situations where a notation aid can help; in the program, be consistent in using a prefix (Hungarian) or postfix to specify values that are percentages vs. those that are decimal. If you can extend a naming convention to the database fields themselves, so much the better.</p>\n"
},
{
"answer_id": 288694,
"author": "Charles Bretana",
"author_id": 32632,
"author_profile": "https://Stackoverflow.com/users/32632",
"pm_score": 0,
"selected": false,
"text": "<p>And to add to the data storage issue, if you can use integer arithmetic for whatever processing you are doing, the performance is much better than when doing floating point arithmetic... So storing ther percetages as integer values may allow the processing logic to itilize integer arithmetic </p>\n"
},
{
"answer_id": 288696,
"author": "ConcernedOfTunbridgeWells",
"author_id": 15401,
"author_profile": "https://Stackoverflow.com/users/15401",
"pm_score": 0,
"selected": false,
"text": "<p>If you're actually using them as a coefficient (or expect users of the database to do this sort of thing in reports), there's a case for storing them as a coefficient - particularly if there's a reason to do calculations involving more than one.</p>\n\n<p>However, if you do this you should be consistent - either all percentages or all coefficients.</p>\n"
},
{
"answer_id": 288727,
"author": "P Daddy",
"author_id": 36388,
"author_profile": "https://Stackoverflow.com/users/36388",
"pm_score": 4,
"selected": true,
"text": "<p>There are actually four good reasons I can think of that you might want to storeβand calculate withβwhole-number percentage values rather than floating-point equivalents:</p>\n\n<ol>\n<li>Depending on the data types chosen, the integer value may take up less space.</li>\n<li>Depending on the data type, the floating-point value may lose precision (remember that not all languages have a data type equivalent to SQL Server's <code>decimal</code> type).</li>\n<li>If the value will be input from or output to the user very frequently, it may be more convenient to keep it in a more user-friendly format (decision between convert when you display and convert when you calculate ... but see the next point).</li>\n<li><p>If the principle values are also integers, then</p>\n\n<pre><code>principle * integerPercentage / 100\n</code></pre>\n\n<p>which uses all integer arithmetic is usually faster than its floating-point equivalent (likely <em>significantly</em> faster in the case of a floating-point type equivalent to T-SQL's <code>decimal</code> type).</p></li>\n</ol>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4296/"
] |
I inherited a project that uses SQL Server 200x, wherein a column that stores a value that is always considered as a percentage in the problem domain is stored as its greater than 1 decimal equivalent. For example, *70%* (0.7, literally) is stored as *70*, *100%* as *100*, etc. Aside from the need to remember to \* 0.01 on retrieved values and \* 100 before persisting values, it doesn't seem to be a problem in and of itself. It does make my head explode though... so is there a good reason for it that I'm missing? Are there compelling reasons to fix it, given that there is a fair amount of code written to work with the pseudo-percentages?
There are a few cases where greater than 100% occurs, but I don't see why the value wouldn't just be stored as 1.05, for example, in those cases.
EDIT: Head feeling better, and slightly smarter. Thanks for all the insights.
|
There are actually four good reasons I can think of that you might want to storeβand calculate withβwhole-number percentage values rather than floating-point equivalents:
1. Depending on the data types chosen, the integer value may take up less space.
2. Depending on the data type, the floating-point value may lose precision (remember that not all languages have a data type equivalent to SQL Server's `decimal` type).
3. If the value will be input from or output to the user very frequently, it may be more convenient to keep it in a more user-friendly format (decision between convert when you display and convert when you calculate ... but see the next point).
4. If the principle values are also integers, then
```
principle * integerPercentage / 100
```
which uses all integer arithmetic is usually faster than its floating-point equivalent (likely *significantly* faster in the case of a floating-point type equivalent to T-SQL's `decimal` type).
|
288,582 |
<p>Here's the scenario - a client uploads a Sybase dump file to (gzipped) to our local FTP server. We have an automated process which picks these up and then moves them to different server within the network where the database server resides. Unfortunately, this transfer is over a WAN, which for large files takes a long time, and sometimes our clients forget to FTP in binary mode, which results in 10GB of transfer over our WAN all for nothing as the dump file can't be loaded at the other end. What I'd like to do, is verify the integrity of the dump file on the local server before sending it out over the WAN, but I can't just try and "load" the dump file, as we don't have Sybase installed (and can't install it). Are there any tools or bits of code that I can use to do this?</p>
|
[
{
"answer_id": 554300,
"author": "Vincent",
"author_id": 66697,
"author_profile": "https://Stackoverflow.com/users/66697",
"pm_score": 0,
"selected": false,
"text": "<p>There is no way to really verify the integrity of the dump file without loading it in some way by a backup server. The client should know whether the dump is successful or not via the backup log or output during the dump.</p>\n\n<p>But to solve your problem you should use to SFTP or SCP, all transfers are done in binary, alleviating your problem. </p>\n\n<p>Ensure that they are also using compression in the dump a value of 1-3 is more than enough, this should reduce your network traffic also.</p>\n"
},
{
"answer_id": 555574,
"author": "brianegge",
"author_id": 14139,
"author_profile": "https://Stackoverflow.com/users/14139",
"pm_score": 3,
"selected": true,
"text": "<p>There are a few things you can do from the command line. The first, on the sending side, is to generate md5sum's of the files.</p>\n\n<pre><code>$ md5sum *.dmp\n2bddf3cd8b04010183dd3295ce7594ff pubs_1.dmp\n7510e0250c8d68bae3e0e794c211e60b pubs_2.dmp\n091fe54fa5fd81d8c109cc7835d37f4a pubs_3.dmp\n</code></pre>\n\n<p>On the client side, they can run the same. Secondly, usually Sybase dumps are done with the compress option. If this option is used, you can also test the file integrity by uncompressing the files via the command line. This isn't as complete, but it will verify the 8 byte CRC-32 checksum which is part of the compress algorithm. </p>\n\n<pre><code>$ gunzip --test *.dmp\ngunzip: pubs_3.dmp: unexpected end of file\n</code></pre>\n\n<p>Neither of these methods validate that Sybase will be able to load the file, but it does help ensure the file isn't corrupt.</p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1030/"
] |
Here's the scenario - a client uploads a Sybase dump file to (gzipped) to our local FTP server. We have an automated process which picks these up and then moves them to different server within the network where the database server resides. Unfortunately, this transfer is over a WAN, which for large files takes a long time, and sometimes our clients forget to FTP in binary mode, which results in 10GB of transfer over our WAN all for nothing as the dump file can't be loaded at the other end. What I'd like to do, is verify the integrity of the dump file on the local server before sending it out over the WAN, but I can't just try and "load" the dump file, as we don't have Sybase installed (and can't install it). Are there any tools or bits of code that I can use to do this?
|
There are a few things you can do from the command line. The first, on the sending side, is to generate md5sum's of the files.
```
$ md5sum *.dmp
2bddf3cd8b04010183dd3295ce7594ff pubs_1.dmp
7510e0250c8d68bae3e0e794c211e60b pubs_2.dmp
091fe54fa5fd81d8c109cc7835d37f4a pubs_3.dmp
```
On the client side, they can run the same. Secondly, usually Sybase dumps are done with the compress option. If this option is used, you can also test the file integrity by uncompressing the files via the command line. This isn't as complete, but it will verify the 8 byte CRC-32 checksum which is part of the compress algorithm.
```
$ gunzip --test *.dmp
gunzip: pubs_3.dmp: unexpected end of file
```
Neither of these methods validate that Sybase will be able to load the file, but it does help ensure the file isn't corrupt.
|
288,603 |
<p>I am getting </p>
<pre><code>Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result
resource in *filename* on line 81
</code></pre>
<p>While running a query to build a chart. The query gets data from the mysql db and uses it to build the chart.</p>
<p>Usually, I get this error and go to the code and find where I've screwed up, fix it, and move on. The tricky part about this problem is that the query is actually running and the chart is being built and displayed accurately. Why is my server (localhost on xampp) telling me that the query result is bad when it can utilize the resource just fine?</p>
<p>Here is the full query:</p>
<pre><code>$chart=array();
$roll=array();
//select used terms
$rosh=mysql_query("select distinct term from search_terms");
while($roshrow=mysql_fetch_assoc($rosh)){
extract($roshrow);
$roll[]=$term;
}
//select term_number for each term
foreach($roll as $sterm){
$termarray=array();
**//following is line 81**
$bashq="select term_number from search_terms where term ='$sterm'";
$bash=mysql_query($bashq);
while($brow=mysql_fetch_assoc($bash)){
extract($brow);
//put results into array to sum
$termarray[]=$term_number;
}
$termsum=array_sum($termarray);
//put term=>number array for chart script
$chart[$sterm]=$termsum;
}
//sort array so high numbers at beginning
arsort($chart);
//slice top 10 terms
$chart=array_slice($chart,0,10);
</code></pre>
|
[
{
"answer_id": 288610,
"author": "mercutio",
"author_id": 1951,
"author_profile": "https://Stackoverflow.com/users/1951",
"pm_score": 3,
"selected": true,
"text": "<p>Do this:</p>\n\n<pre><code>$rosh=mysql_query(\"select distinct term from search_terms\")\n or die(\"Error with query: \" . mysql_error());\n</code></pre>\n\n<p>and this: </p>\n\n<pre><code>$bash=mysql_query($bashq)\n or die(\"Error with query: \" . mysql_error();\n</code></pre>\n\n<p>That will tell you when it fails. You are correct though, you're getting that message because mysql_query has returned \"false\" and isn't a valid result resource.</p>\n"
},
{
"answer_id": 288665,
"author": "jishi",
"author_id": 33663,
"author_profile": "https://Stackoverflow.com/users/33663",
"pm_score": 1,
"selected": false,
"text": "<p>Because your querying within a loop, one of the terms isn't processed (probably because search_terms is missing rows for that specific turn. Which is odd, since you're querying the same table.</p>\n\n<p>However, since it's a Warning, and not a fatal Error, it will still continue.</p>\n\n<p>Either way, it's seems like wrong way to pulling your data, you can probably do taht with one query, adequate sorting (ORDER BY) directly in the SQL server, GROUP BY and SUM() for getting the sum of your terms.</p>\n\n<p>You should read up on your SQL instead :)</p>\n\n<pre>\n\nSELECT term, SUM(term_number) as term_sum\nFROM search_terms \nGROUP BY terms \nORDER BY term_sum DESC\nLIMIT 10\n\n</pre>\n\n<p>then just copy it to your hashtable and it should already be sorted, aswell as limited to 10 entries.</p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288603",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1149/"
] |
I am getting
```
Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result
resource in *filename* on line 81
```
While running a query to build a chart. The query gets data from the mysql db and uses it to build the chart.
Usually, I get this error and go to the code and find where I've screwed up, fix it, and move on. The tricky part about this problem is that the query is actually running and the chart is being built and displayed accurately. Why is my server (localhost on xampp) telling me that the query result is bad when it can utilize the resource just fine?
Here is the full query:
```
$chart=array();
$roll=array();
//select used terms
$rosh=mysql_query("select distinct term from search_terms");
while($roshrow=mysql_fetch_assoc($rosh)){
extract($roshrow);
$roll[]=$term;
}
//select term_number for each term
foreach($roll as $sterm){
$termarray=array();
**//following is line 81**
$bashq="select term_number from search_terms where term ='$sterm'";
$bash=mysql_query($bashq);
while($brow=mysql_fetch_assoc($bash)){
extract($brow);
//put results into array to sum
$termarray[]=$term_number;
}
$termsum=array_sum($termarray);
//put term=>number array for chart script
$chart[$sterm]=$termsum;
}
//sort array so high numbers at beginning
arsort($chart);
//slice top 10 terms
$chart=array_slice($chart,0,10);
```
|
Do this:
```
$rosh=mysql_query("select distinct term from search_terms")
or die("Error with query: " . mysql_error());
```
and this:
```
$bash=mysql_query($bashq)
or die("Error with query: " . mysql_error();
```
That will tell you when it fails. You are correct though, you're getting that message because mysql\_query has returned "false" and isn't a valid result resource.
|
288,612 |
<p>I have a form that excepts a file upload in ASP.NET. I need to increase the max upload size to above the 4 MB default.</p>
<p>I have found in certain places referencing the below code at <a href="http://msdn.microsoft.com/en-us/library/system.web.configuration.httpruntimesection.maxrequestlength.aspx" rel="noreferrer">msdn</a>. </p>
<pre><code>[ConfigurationPropertyAttribute("maxRequestLength", DefaultValue = )]
</code></pre>
<p>None of the references actually describe how to use it, and I have tried several things with no success. I only want to modify this attribute for certain pages that are asking for file upload.</p>
<p>Is this the correct route to take? And how do I use this?</p>
|
[
{
"answer_id": 288644,
"author": "Stefan",
"author_id": 19307,
"author_profile": "https://Stackoverflow.com/users/19307",
"pm_score": 3,
"selected": false,
"text": "<p>If its windows 2003 / IIS 6.0 then check out AspMaxRequestEntityAllowed = \"204800\" in the file <strong>metabase.xml</strong> located in folder C:\\windows\\system32\\inetsrv\\ </p>\n\n<p>The default value of \"204800\" (~205Kb) is in my opinion too low for most users. Just change the value to what you think should be max. </p>\n\n<p>If you cant save the file after editing it you have to either stop the ISS-server or enable the server to allow editing of the file:</p>\n\n<p><a href=\"https://i.stack.imgur.com/V8Udl.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/V8Udl.png\" alt=\"alt text\"></a><br>\n<sub>(source: <a href=\"http://blogs.itmaskinen.se/image.axd?picture=WindowsLiveWriter/Request.BinaryReadFailedwindows2003IIS.0_BC5A/image_2.png\" rel=\"nofollow noreferrer\">itmaskinen.se</a>)</sub> </p>\n\n<p>Edit: I did not read the question correct (how to set the maxrequest in webconfig). But this informatin may be of interrest for other people, many people who move their sites from win2000-server to win2003 and had a working upload-function and suddenly got the <strong>Request.BinaryRead Failed</strong> error will have use of it. So I leave the answer here.</p>\n"
},
{
"answer_id": 288667,
"author": "ben",
"author_id": 7561,
"author_profile": "https://Stackoverflow.com/users/7561",
"pm_score": 4,
"selected": false,
"text": "<p>I believe this line in the <code>Web.config</code> will set the max upload size:</p>\n<pre><code><system.web>\n\n <httpRuntime maxRequestLength="600000"/>\n</system.web>\n</code></pre>\n"
},
{
"answer_id": 288675,
"author": "Eric Rosenberger",
"author_id": 36979,
"author_profile": "https://Stackoverflow.com/users/36979",
"pm_score": 10,
"selected": true,
"text": "<p>This setting goes in your web.config file. It affects the entire application, though... I don't think you can set it per page.</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code><configuration>\n <system.web>\n <httpRuntime maxRequestLength=\"xxx\" />\n </system.web>\n</configuration>\n</code></pre>\n\n<p>\"xxx\" is in KB. The default is 4096 (= 4 MB).</p>\n"
},
{
"answer_id": 4712240,
"author": "Quiz",
"author_id": 415989,
"author_profile": "https://Stackoverflow.com/users/415989",
"pm_score": 0,
"selected": false,
"text": "<p>If you use sharepoint you should configure max size with Administrative Tools too:\n<a href=\"http://support.microsoft.com/kb/925083\" rel=\"nofollow\">kb925083</a></p>\n"
},
{
"answer_id": 15679792,
"author": "Massimo Zerbini",
"author_id": 940939,
"author_profile": "https://Stackoverflow.com/users/940939",
"pm_score": 3,
"selected": false,
"text": "<p>I've the same problem in a win 2008 IIS server, I've solved the problem adding this configuration in the web.config:</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code><system.web>\n <httpRuntime executionTimeout=\"3600\" maxRequestLength=\"102400\" \n appRequestQueueLimit=\"100\" requestValidationMode=\"2.0\"\n requestLengthDiskThreshold=\"10024000\"/>\n</system.web>\n</code></pre>\n\n<p>The <strong>requestLengthDiskThreshold</strong> by default is 80000 bytes so it's too small for my application. requestLengthDiskThreshold is measured in bytes and maxRequestLength is expressed in Kbytes.</p>\n\n<p>The problem is present if the application is using a <code>System.Web.UI.HtmlControls.HtmlInputFile</code> server component. Increasing the requestLengthDiskThreshold is necessary to solve it.</p>\n"
},
{
"answer_id": 18531025,
"author": "4imble",
"author_id": 180420,
"author_profile": "https://Stackoverflow.com/users/180420",
"pm_score": 8,
"selected": false,
"text": "<p>For IIS 7+, as well as adding the httpRuntime maxRequestLength setting you also need to add:</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code> <system.webServer>\n <security>\n <requestFiltering>\n <requestLimits maxAllowedContentLength=\"52428800\" /> <!--50MB-->\n </requestFiltering>\n </security>\n </system.webServer>\n</code></pre>\n\n<p>Or in IIS (7): </p>\n\n<blockquote>\n <ul>\n <li>Select the website you want enable to accept large file uploads.</li>\n <li>In the main window double click 'Request filtering'</li>\n <li>Select \"Edit Feature Settings\"</li>\n <li>Modify the \"Maximum allowed content length (bytes)\"</li>\n </ul>\n</blockquote>\n"
},
{
"answer_id": 22826216,
"author": "sk1900",
"author_id": 2341601,
"author_profile": "https://Stackoverflow.com/users/2341601",
"pm_score": 0,
"selected": false,
"text": "<p>I have a blog post on how to <a href=\"http://www.aspnetify.com/2010/11/aspnet-fileupload-control-use-and.html\" rel=\"nofollow\">increase the file size for asp upload control</a>. </p>\n\n<p>From the post:</p>\n\n<blockquote>\n <p>By default, the FileUpload control allows a maximum of 4MB file to be uploaded and the execution \n timeout is 110 seconds. These properties can be changed from within the web.config fileβs httpRuntime section. The maxRequestLength property determines the maximum file size that can be uploaded. The \n executionTimeout property determines the maximum time for execution.</p>\n</blockquote>\n"
},
{
"answer_id": 23910210,
"author": "user3683243",
"author_id": 3683243,
"author_profile": "https://Stackoverflow.com/users/3683243",
"pm_score": 2,
"selected": false,
"text": "<p>You can write that block of code in your application web.config file.</p>\n\n<pre><code><httpRuntime maxRequestLength=\"2048576000\" />\n<sessionState timeout=\"3600\" />\n</code></pre>\n\n<p>By writing that code you can upload a larger file than now</p>\n"
},
{
"answer_id": 29141957,
"author": "Rahat Ali",
"author_id": 4689207,
"author_profile": "https://Stackoverflow.com/users/4689207",
"pm_score": 0,
"selected": false,
"text": "<p>If it works in your local machine and does not work after deployment in IIS (i used Windows Server 2008 R2) i have a solution. </p>\n\n<p>Open IIS (inetmgr)\nGo to your website\nAt right hand side go to Content (Request Filtering)\nGo to Edit Feature Settings\nChange maximum content size as (Bytes you required)\nThis will work.\nYou can also take help from following thread\n<a href=\"http://www.iis.net/configreference/system.webserver/security/requestfiltering/requestlimits\" rel=\"nofollow\">http://www.iis.net/configreference/system.webserver/security/requestfiltering/requestlimits</a></p>\n"
},
{
"answer_id": 31516339,
"author": "damir",
"author_id": 1030264,
"author_profile": "https://Stackoverflow.com/users/1030264",
"pm_score": 3,
"selected": false,
"text": "<p>I know it is an old question.</p>\n\n<p>So this is what you have to do:</p>\n\n<p>In you web.config file, add this in <code><system.web></code>:</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code><!-- 3GB Files / in kilobyte (3072*1024) -->\n<httpRuntime targetFramework=\"4.5\" maxRequestLength=\"3145728\"/>\n</code></pre>\n\n<p>and this under <code><system.webServer></code>:</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code><security>\n <requestFiltering>\n\n <!-- 3GB Files / in byte (3072*1024*1024) -->\n <requestLimits maxAllowedContentLength=\"3221225472\" />\n\n </requestFiltering>\n</security>\n</code></pre>\n\n<p>You see in the comment how this works. In one you need to have the sie in bytes and in the other one in kilobytes. Hope that helps. </p>\n"
},
{
"answer_id": 32519833,
"author": "cangosta",
"author_id": 797252,
"author_profile": "https://Stackoverflow.com/users/797252",
"pm_score": 4,
"selected": false,
"text": "<p>for a 2 GB max limit, on your application web.config:</p>\n\n<pre><code><system.web>\n <compilation debug=\"true\" targetFramework=\"4.5\" />\n <httpRuntime targetFramework=\"4.5\" maxRequestLength=\"2147483647\" executionTimeout=\"1600\" requestLengthDiskThreshold=\"2147483647\" />\n</system.web>\n\n<system.webServer>\n <security>\n <requestFiltering>\n <requestLimits maxAllowedContentLength=\"2147483647\" />\n </requestFiltering>\n </security>\n</system.webServer>\n</code></pre>\n"
},
{
"answer_id": 37475722,
"author": "Malik Khalil",
"author_id": 4859919,
"author_profile": "https://Stackoverflow.com/users/4859919",
"pm_score": 6,
"selected": false,
"text": "<p>To increase uploading file's size limit we have two ways</p>\n\n<p><strong>1.\nIIS6 or lower</strong></p>\n\n<blockquote>\n <p>By default, in ASP.Net the maximum size of a file to be uploaded to the server is\n around <strong>4MB</strong>. This value can be increased by modifying the\n <strong>maxRequestLength</strong> attribute in <em>web.config</em>.</p>\n \n <p><strong>Remember : maxRequestLenght is in KB</strong></p>\n</blockquote>\n\n<p><strong>Example</strong>: if you want to restrict uploads to 15MB, set maxRequestLength to β15360β (15 x 1024).</p>\n\n<pre><code><system.web>\n <!-- maxRequestLength for asp.net, in KB --> \n <httpRuntime maxRequestLength=\"15360\" ></httpRuntime> \n</system.web>\n</code></pre>\n\n<p><strong>2.\nIIS7 or higher</strong></p>\n\n<blockquote>\n <p>A slight different way used here to upload files.IIS7 has\n introduced <strong>request filtering module</strong>.Which executed before\n ASP.Net.Means the way pipeline works is that the IIS\n value(<strong>maxAllowedContentLength</strong>) checked first then ASP.NET\n value(<strong>maxRequestLength</strong>) is checked.The maxAllowedContentLength\n attribute defaults to <strong>28.61 MB</strong>.This value can be increased by\n modifying both attribute in same <em>web.config</em>.</p>\n \n <p><strong>Remember : maxAllowedContentLength is in bytes</strong></p>\n</blockquote>\n\n<p><strong>Example</strong> : if you want to restrict uploads to 15MB, set maxRequestLength to β15360β and maxAllowedContentLength to \"15728640\" (15 x 1024 x 1024).</p>\n\n<pre><code><system.web>\n <!-- maxRequestLength for asp.net, in KB --> \n <httpRuntime maxRequestLength=\"15360\" ></httpRuntime> \n</system.web>\n\n<system.webServer> \n <security> \n <requestFiltering> \n <!-- maxAllowedContentLength, for IIS, in bytes --> \n <requestLimits maxAllowedContentLength=\"15728640\" ></requestLimits>\n </requestFiltering> \n </security>\n</system.webServer>\n</code></pre>\n\n<p><strong>MSDN Reference link</strong> : <a href=\"https://msdn.microsoft.com/en-us/library/e1f13641(VS.80).aspx\">https://msdn.microsoft.com/en-us/library/e1f13641(VS.80).aspx</a></p>\n"
},
{
"answer_id": 46450705,
"author": "mbadeveloper",
"author_id": 3752193,
"author_profile": "https://Stackoverflow.com/users/3752193",
"pm_score": 2,
"selected": false,
"text": "<p>If you are using Framework 4.6</p>\n\n<pre><code><httpRuntime targetFramework=\"4.6.1\" requestValidationMode=\"2.0\" maxRequestLength=\"10485760\" />\n</code></pre>\n"
},
{
"answer_id": 52671089,
"author": "Martin",
"author_id": 355272,
"author_profile": "https://Stackoverflow.com/users/355272",
"pm_score": 3,
"selected": false,
"text": "<p>Max file size can be restricted to a single MVC Controller or even to an Action.<br/>\nweb.config <location> tag can be used for this:</p>\n\n<pre><code><location path=\"YourAreaName/YourControllerName>/YourActionName>\">\n <system.web>\n <!-- 15MB maxRequestLength for asp.net, in KB 15360 -->\n <httpRuntime maxRequestLength=\"15360\" />\n </system.web>\n <system.webServer>\n <security>\n <requestFiltering>\n <!-- 15MB maxAllowedContentLength, for IIS, in bytes 15728640 -->\n <requestLimits maxAllowedContentLength=\"15728640\" />\n </requestFiltering>\n </security>\n </system.webServer>\n</location>\n</code></pre>\n\n<p>Or you can add these entries in area's own web.config.</p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/576/"
] |
I have a form that excepts a file upload in ASP.NET. I need to increase the max upload size to above the 4 MB default.
I have found in certain places referencing the below code at [msdn](http://msdn.microsoft.com/en-us/library/system.web.configuration.httpruntimesection.maxrequestlength.aspx).
```
[ConfigurationPropertyAttribute("maxRequestLength", DefaultValue = )]
```
None of the references actually describe how to use it, and I have tried several things with no success. I only want to modify this attribute for certain pages that are asking for file upload.
Is this the correct route to take? And how do I use this?
|
This setting goes in your web.config file. It affects the entire application, though... I don't think you can set it per page.
```xml
<configuration>
<system.web>
<httpRuntime maxRequestLength="xxx" />
</system.web>
</configuration>
```
"xxx" is in KB. The default is 4096 (= 4 MB).
|
288,614 |
<p>How would I go about creating a real world form creation class that I can use to display a new form with fields of different types, as how many fields I want, I can use drop downs and I can do all of this by using OOP?</p>
|
[
{
"answer_id": 288706,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 4,
"selected": true,
"text": "<p>You definitely can. Consider a Form class which stores information about the form itself: the <code>method</code>, <code>action</code>, <code>enctype</code> attributes. Also throw in stuff like an optional heading and/or description text at the top. Of course you will also need an array of input elements. These could probably be put into their own class (though subclassing them for InputText, InputCheckbox, InputRadio maybe be a bit over the top). Here's a vague skeleton design:</p>\n\n<pre><code>class Form {\n var $attributes, // array, with keys ['method' => 'post', 'action' => 'mypage.php'...]\n $heading,\n $description,\n $inputs // array of FormInput elements\n ;\n\n function render() {\n $output = \"<form \" . /* insert attributes here */ \">\"\n . \"<h1>\" . $this->heading . \"</h1>\"\n . \"<p>\" . $this->description . \"</p>\"\n ;\n // wrap your inputs in whatever output style you prefer:\n // ordered list, table, etc.\n foreach ($this->inputs as $input) {\n $output .= $input->render();\n }\n $output .= \"</form>\";\n return $output;\n }\n}\n</code></pre>\n\n<p>The FormInput class would just need to store the basics, such as type, name, value, label. If you wanted to get tricky then you could apply validation rules which would then be converted to Javascript when rendering.</p>\n"
},
{
"answer_id": 288798,
"author": "starmonkey",
"author_id": 29854,
"author_profile": "https://Stackoverflow.com/users/29854",
"pm_score": 3,
"selected": false,
"text": "<p>To be honest I wouldn't roll my own, considering there are a few mature form packages out there for PHP.</p>\n\n<p>I use PEAR's HTML_QuickForm package (<a href=\"http://pear.php.net/manual/en/package.html.html-quickform.php\" rel=\"noreferrer\">http://pear.php.net/manual/en/package.html.html-quickform.php</a>) for PHP4 sites.</p>\n\n<p>For PHP5, I'd have a look into Zend_Form (<a href=\"http://framework.zend.com/manual/en/zend.form.html\" rel=\"noreferrer\">http://framework.zend.com/manual/en/zend.form.html</a>).</p>\n\n<p>For my quickform code, I use a helper class that lets me define forms using a config array. For example:</p>\n\n<pre><code>echo QuickFormHelper::renderFromConfig(array(\n 'name' => 'area_edit',\n 'elements' => array(\n 'area_id' => array('type' => 'hidden'),\n 'active' => array('type' => 'toggle'),\n 'site_name' => array('type' => 'text'),\n 'base_url' => array('type' => 'text'),\n 'email' => array('type' => 'text'),\n 'email_admin' => array('type' => 'text'),\n 'email_financial' => array('type' => 'text'),\n 'cron_enabled' => array('type' => 'toggle'),\n 'address' => array('type' => 'address'),\n ),\n 'groups' => array(\n 'Basic Details' => array('site_name', 'base_url'),\n 'Address Details' => array('address'),\n 'Misc Details' => array(), // SM: Display the rest with this heading.\n ),\n 'defaults' => $site,\n 'callback_on_success' => array(\n 'object' => $module,\n 'function' => 'saveSite',\n ),\n));\n</code></pre>\n\n<p>Note that the above element types 'address' and 'toggle' are in fact multiple form fields (basically, meta-types). This is what I love about this helper class - I can define a standard group of fields with their rules (such as address, credit_card, etc) and they can be used on lots of pages in a consistent fashion.</p>\n"
},
{
"answer_id": 10885443,
"author": "Andrew Odri",
"author_id": 574904,
"author_profile": "https://Stackoverflow.com/users/574904",
"pm_score": 0,
"selected": false,
"text": "<p>Just for reference, <a href=\"http://php.xivix.net/php_7_24_Object_Oriented_Forms_Introduction\" rel=\"nofollow\">Object Oriented Forms</a> by Khurram Khan is an excellent OO forms implementation for PHP.</p>\n\n<p>Here is a sample of what the code looks like:</p>\n\n<pre><code>$form = new Form(\"Register\", \"form.php\"); \n\n$personal = new Block(\"Personal Information\"); \n\n$name = new Text(\"name\", \"Your name\"); \n$name->setDescription(\"this is my description\"); \n$name->addValidator(new MaxLengthValidator(\"The name you have entered is too long\", 30)); \n\n...\n</code></pre>\n\n<p>Another more popular implementation is <a href=\"http://www.sanisoft.com/phplib/manual/oohforms.php\" rel=\"nofollow\">PHPlib</a>. However, I find this to be a bit clunky; it seems like it's just some standard functional programming wrapped in a class.</p>\n\n<p>Another option would be writing an abstraction for the built in <a href=\"http://www.php.net/manual/en/book.dom.php\" rel=\"nofollow\">DOM</a> library. This will allow you to manually create any kind of form and form element using OO notation, with the added benefit that you will be returned an OO DOM instance that can be used elsewhere in your program.</p>\n"
},
{
"answer_id": 40190467,
"author": "JG Estiot",
"author_id": 964292,
"author_profile": "https://Stackoverflow.com/users/964292",
"pm_score": 2,
"selected": false,
"text": "<p>I will go against other advice here and suggest that you build your own library to generate forms. If you fail, you will still learn a lot in the process. </p>\n\n<p>The design process is most important here. You start from the top and ask yourself what goes on a form. At an abstract level, a form is full of elements. Some are visible, some are not, some can be entered by the user but others cannot, some elements can trigger other elements... and the list goes on...</p>\n\n<p>Eventually you end up with elements that are \"decorative\" (Text, Headings, Separators, Fieldsets, Links, Images), elements that are interactive (Inputs, Dropdowns, Checkboxes, Radio buttons, Submit Buttons) and finally elements that are neither decorative nor interactive (Hidden Inputs, Anchors and elements that act as containers to group other elements.) </p>\n\n<p>Once you have the different categories organised you start looking into features that all elements have and you can put that into the base element class. Then you go up the chain making your classes doing more and more, inheriting from other simpler element classes. In my library, the base element class is called form_element and each form_element has a unique name that no other element within the same form can have. A form_element also has a set of attributes. It has a function that all elements have called render(). In the base class render() does nothing (so a base element is always invisible) but in derived classes it starts producing HTML. By the way, I never make any of my classes create HTML. Instead I have a static class called html which writes HTML for all the classes that needs its services. </p>\n\n<p>Very early in the chain of form elements, you should have one, a container that groups others. It should have an add() function and its render() function should consist of calling the render() function of all its sub-elements. the form class will be derived from this container class. </p>\n\n<p>Spend plenty of time on the design. Pay attention to compatibility with the rest of your library. </p>\n\n<p>If you want the data from the form to come from a database and be saved to one, you will need to add this functionality and have a form element class linked to a table and column. Here too, I have a separate DB class that can retrieve/save the data. I have a query class that creates queries. Form elements should have nothing to do with creating HTML, creating queries or accessing a database. My static class DB and my query class take care of the dirty work. The form class should only be involved with form stuff. The form class collects into an array all the tables and columns for the fields that need to be saved and pas it to the query class which creates the query which is then passed to the DB class which executes it. </p>\n\n<p>Once you are properly setup, what appears to be horrendously complicated suddenly becomes very easy with properly designed classes. </p>\n\n<p>Because you have a class that can write HTML, your form class needs to just html::init() and follow it with render() and the entire HTML code for the form is available within the html buffer. html::output() flushes everything out. </p>\n\n<p>Validation is also handled externally with a static validation class. Form elements that can be validated hold validation instructions within an array in a format that can be passed directly to the validation class. Each element that needs to be validated is bound to an error element which displays the error if the element does not validate or remains invisible if all goes well. </p>\n\n<p>This is to show you that when you design a form environment (or anything else) you really need to consider absolutely everything before you get started. The work that you put into it may not immediately translate into code that can power your application but it will sure make you a much better developer, thus making your future projects much easier to handle. </p>\n\n<p>The form class creates a form, the html class creates the HTML, the query class makes queries and the DB class handles the database. If your classes start doing work that should be done by separate classes, you have a design problem. </p>\n\n<p>Here is a code sample to show how my form library works:</p>\n\n<pre><code>$fm = new form('myform');\n$fm->binding(FORM_DATABASE);\n$fm->state(FORM_RETRIEVE); \n$fm->set_recno(1);\n$fm->add(new form_heading(\"My form\"));\n$fm->add($el=new form_input(\"name\",40));\n$el->bind_data('mytable','mycolumn');\n$el->set_attribute('size', 25);\n$el->set_default('Name');\n$fm->add($el=new form_submit(\"submit_btn\",\"Submit\"));\nif($fm->manage())\n {\n redirect or do something else here. The interaction with the form is done. The initial state for the form was FORM_RETRIEVE. If it had been FORM_NEW it would have displayed default values instead of the retrieved record and saved the form as a new record in the table. \n }\n</code></pre>\n\n<p>Note that the manage() function of the form takes care of absolutely everything, retrieving data from the database, rendering the form into the view, validating data and saving it back to the database. </p>\n\n<p>One of the advantages of creating forms programmatically (as above) is the option to write your own form-based code generator to create the code to make your forms. </p>\n\n<p>I hope this can help you or someone else.</p>\n"
},
{
"answer_id": 60345097,
"author": "Bruce Wells",
"author_id": 4081533,
"author_profile": "https://Stackoverflow.com/users/4081533",
"pm_score": 0,
"selected": false,
"text": "<p>You definitely should use OO PHP to do forms, and all the rest of your HTML output. I could not find any PHP library (many of the links in these answers are dead) to do what I wanted, so I wrote <a href=\"https://packagist.org/packages/phpfui/phpfui\" rel=\"nofollow noreferrer\">PHPFUI</a>. It is not a generic HMTL output library, but outputs pages for the <a href=\"https://get.foundation/sites/docs/\" rel=\"nofollow noreferrer\">Foundation CSS Framework</a>. You could easily use the same technique to output a more vanilla page, or Bootstrap or what ever. I did not want to write a generic HTML OO PHP library, as I wanted something lean and mean for performance reasons. Also I don't like to over engineer stuff, so it is hard coded to Foundation. But the same principles would apply to any PHP library that would want to output clean HTML with no validation issues, which you often find in hand written HTML.</p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37418/"
] |
How would I go about creating a real world form creation class that I can use to display a new form with fields of different types, as how many fields I want, I can use drop downs and I can do all of this by using OOP?
|
You definitely can. Consider a Form class which stores information about the form itself: the `method`, `action`, `enctype` attributes. Also throw in stuff like an optional heading and/or description text at the top. Of course you will also need an array of input elements. These could probably be put into their own class (though subclassing them for InputText, InputCheckbox, InputRadio maybe be a bit over the top). Here's a vague skeleton design:
```
class Form {
var $attributes, // array, with keys ['method' => 'post', 'action' => 'mypage.php'...]
$heading,
$description,
$inputs // array of FormInput elements
;
function render() {
$output = "<form " . /* insert attributes here */ ">"
. "<h1>" . $this->heading . "</h1>"
. "<p>" . $this->description . "</p>"
;
// wrap your inputs in whatever output style you prefer:
// ordered list, table, etc.
foreach ($this->inputs as $input) {
$output .= $input->render();
}
$output .= "</form>";
return $output;
}
}
```
The FormInput class would just need to store the basics, such as type, name, value, label. If you wanted to get tricky then you could apply validation rules which would then be converted to Javascript when rendering.
|
288,619 |
<p>Say I have a sql query </p>
<pre><code>SELECT fname, lname, dob, ssn, address1, address2, zip, phone,state from users
</code></pre>
<p>Now say the records are now either in dictionary base or a strongly typed collection.</p>
<p>I have a grid view control and i want to bind it to my collection but I only want to display fname, lname, dob and ssn and not the other columns.</p>
<p>Is there an easy way to extract the columns and then bind to the extracted item? Not sure if LINQ would be helpful here.</p>
<p>This is a test project as I am getting familiar with the web world wqith VS-2008</p>
|
[
{
"answer_id": 288627,
"author": "Cristian Libardo",
"author_id": 16526,
"author_profile": "https://Stackoverflow.com/users/16526",
"pm_score": 2,
"selected": false,
"text": "<p>Perhaps LINQ and an anonymous class could do the trick for you.</p>\n\n<pre><code>from user in UserCollection\nselect new { FirstName=user.fname, LastName=user.lname, Dob=user.dob, SSN=user.ssn }\n</code></pre>\n"
},
{
"answer_id": 288630,
"author": "Tim Merrifield",
"author_id": 36706,
"author_profile": "https://Stackoverflow.com/users/36706",
"pm_score": 0,
"selected": false,
"text": "<p>You can use linq to return an anonymous type (AKA tuple). That tuple would contain only the properties you are looking for. Then you can bind your grid to that collection. Google anonymous types or tuples in C# to see what I mean.</p>\n"
},
{
"answer_id": 288632,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 0,
"selected": false,
"text": "<p>Assuming your data is in some form of IENumerable<T>:</p>\n\n<pre><code>var filteredUser = from U in Users\n select new { U.fname, U.lname, U.dob, U.SSN };\n</code></pre>\n\n<p>FilteredUser is now a collection with just those properties.</p>\n\n<p>This is part of the cool thing about LINQ To Objects. You don't need to use LINQ-To-SQL to get your data, you can use anything you want to populate your initial question, and then use Linq-To-Objects to prune it down in memory.</p>\n"
},
{
"answer_id": 288635,
"author": "lomaxx",
"author_id": 493,
"author_profile": "https://Stackoverflow.com/users/493",
"pm_score": 1,
"selected": false,
"text": "<p>You can specify what columns you want to display in the gridview. Just specify the columns you want in the aspx page:</p>\n\n<pre><code><asp:GridView ID=\"gvwExample\" runat=\"server\" AutoGenerateColumns=\"False\" >\n<columns>\n<asp:BoundField DataField=\"firstname\" HeaderText=\"First Name\" />\n<asp:BoundField DataField=\"lastname\" HeaderText=\"Last Name\" />\n<asp:BoundField DataField=\"hiredate\" HeaderText=\"Date Hired\" />\n</columns>\n</asp:GridView> \n</code></pre>\n"
},
{
"answer_id": 288648,
"author": "Nathan W",
"author_id": 6335,
"author_profile": "https://Stackoverflow.com/users/6335",
"pm_score": 0,
"selected": false,
"text": "<p>You could use linq for what you need. If you have created a dbml for your data then you could just use LINQ to pull the records straight from the db(or if your collection is IEnumerable), like so:</p>\n\n<pre><code>Dim _records = From user in users _\n Select New With {.FirstName = user.fname,_\n .Lastname = user.lname,.dob = user.dob,.ssn = user.ssn}\n\n{gridcontrol}.datasource = _records\n</code></pre>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Say I have a sql query
```
SELECT fname, lname, dob, ssn, address1, address2, zip, phone,state from users
```
Now say the records are now either in dictionary base or a strongly typed collection.
I have a grid view control and i want to bind it to my collection but I only want to display fname, lname, dob and ssn and not the other columns.
Is there an easy way to extract the columns and then bind to the extracted item? Not sure if LINQ would be helpful here.
This is a test project as I am getting familiar with the web world wqith VS-2008
|
Perhaps LINQ and an anonymous class could do the trick for you.
```
from user in UserCollection
select new { FirstName=user.fname, LastName=user.lname, Dob=user.dob, SSN=user.ssn }
```
|
288,637 |
<p>I need to construct some rather simple SQL, I suppose, but as it's a rare event that I work with DBs these days I can't figure out the details.</p>
<p>I have a table 'posts' with the following columns:</p>
<blockquote>
<p>id, caption, text</p>
</blockquote>
<p>and a table 'comments' with the following columns:</p>
<blockquote>
<p>id, name, text, post_id</p>
</blockquote>
<p>What would the (single) SQL statement look like which retrieves the captions of all posts which have one or more comments associated with it through the 'post_id' key? The DBMS is MySQL if it has any relevance for the SQL query.</p>
|
[
{
"answer_id": 288655,
"author": "hark",
"author_id": 34826,
"author_profile": "https://Stackoverflow.com/users/34826",
"pm_score": -1,
"selected": false,
"text": "<p>You're basically looking at performing a subquery --</p>\n\n<p><code>SELECT p.caption FROM posts p WHERE (SELECT COUNT(*) FROM comments c WHERE c.post_id=p.id) > 1;</code></p>\n\n<p>This has the effect of running the <code>SELECT COUNT(*)</code> subquery for each row in the posts table. Depending on the size of your tables, you might consider adding an additional column, <code>comment_count</code>, into your <code>posts</code> table to store the number of corresponding <code>comments</code>, such that you can simply do</p>\n\n<p><code>SELECT p.caption FROM posts p WHERE comment_count > 1</code></p>\n"
},
{
"answer_id": 288660,
"author": "lomaxx",
"author_id": 493,
"author_profile": "https://Stackoverflow.com/users/493",
"pm_score": -1,
"selected": false,
"text": "<p>Just going off the top of my head here but maybe something like:</p>\n\n<pre><code>SELECT caption FROM posts WHERE id IN (SELECT post_id FROM comments HAVING count(*) > 0)\n</code></pre>\n"
},
{
"answer_id": 288668,
"author": "Nick DeVore",
"author_id": 1380,
"author_profile": "https://Stackoverflow.com/users/1380",
"pm_score": 4,
"selected": true,
"text": "<pre>select p.caption, count(c.id)\nfrom posts p join comments c on p.id = c.post_id\ngroup by p.caption\nhaving count (c.id) > 0</pre>\n"
},
{
"answer_id": 288676,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 2,
"selected": false,
"text": "<pre><code>SELECT DISTINCT p.caption, p.id\n FROM posts p, \n comments c \n WHERE c.post_ID = p.ID \n</code></pre>\n\n<p>I think using a join would be a lot faster than using the IN clause or a subquery.</p>\n"
},
{
"answer_id": 288701,
"author": "Tjofras",
"author_id": 37486,
"author_profile": "https://Stackoverflow.com/users/37486",
"pm_score": 0,
"selected": false,
"text": "<pre><code>SELECT caption FROM posts \nINNER JOIN comments ON comments.post_id = posts.id \nGROUP BY posts.id;\n</code></pre>\n<p>No need for a <code>having</code> clause or <code>count()</code>.</p>\n<p>edit: Should be a <code>inner join</code> of course (to avoid nulls if a comment is orphaned), thanks to jishi.</p>\n"
},
{
"answer_id": 288784,
"author": "James",
"author_id": 16282,
"author_profile": "https://Stackoverflow.com/users/16282",
"pm_score": 0,
"selected": false,
"text": "<pre><code>SELECT DISTINCT caption\nFROM posts\n INNER JOIN comments ON posts.id = comments.post_id\n</code></pre>\n\n<p>Forget about counts and subqueries. </p>\n\n<p>The inner join will pick up all the comments that have valid posts and exclude all the posts that have 0 comments. The DISTINCT will coalesce the duplicate caption entries for posts that have more then 1 comment.</p>\n"
},
{
"answer_id": 289038,
"author": "Ian Varley",
"author_id": 37539,
"author_profile": "https://Stackoverflow.com/users/37539",
"pm_score": 0,
"selected": false,
"text": "<p>I find this syntax to be the most readable in this situation:</p>\n\n<pre><code>SELECT * FROM posts P \n WHERE EXISTS (SELECT * FROM Comments WHERE post_id = P.id)\n</code></pre>\n\n<p>It expresses your intent better than most of the others in this thread - \"give me all the posts ...\" (select * from posts) \"... that have any comments\" (where exist (select * from comments ... )). It's essentially the same as the joins above, but because you're not actually doing a join, you don't have to worry about getting duplicates of the records in Posts, so you'll just get one record per post.</p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4055/"
] |
I need to construct some rather simple SQL, I suppose, but as it's a rare event that I work with DBs these days I can't figure out the details.
I have a table 'posts' with the following columns:
>
> id, caption, text
>
>
>
and a table 'comments' with the following columns:
>
> id, name, text, post\_id
>
>
>
What would the (single) SQL statement look like which retrieves the captions of all posts which have one or more comments associated with it through the 'post\_id' key? The DBMS is MySQL if it has any relevance for the SQL query.
|
```
select p.caption, count(c.id)
from posts p join comments c on p.id = c.post_id
group by p.caption
having count (c.id) > 0
```
|
288,687 |
<p>I've written a cheap & cheerful sound board in for my Mac, and I play the various sounds with NSSound like this:</p>
<pre><code>-(void)play:(NSSound *)soundEffect:(BOOL)stopIfPlaying {
BOOL wasPlaying = FALSE;
if([nowPlaying isPlaying]) {
[nowPlaying stop];
wasPlaying = TRUE;
}
if(soundEffect != nowPlaying)
{
[soundEffect play];
nowPlaying = soundEffect;
} else if(soundEffect == nowPlaying && ![nowPlaying isPlaying] && !wasPlaying) {
[nowPlaying play];
}
}
</code></pre>
<p>Rather than just stop it dead, I'd like it to fade out over a couple of seconds or so.</p>
|
[
{
"answer_id": 289386,
"author": "Chris Blackwell",
"author_id": 1329401,
"author_profile": "https://Stackoverflow.com/users/1329401",
"pm_score": 0,
"selected": false,
"text": "<p>Something like this perhaps? You probably want a more linear dropoff, but the basic idea is make a loop and sleep the period of time till the next update.</p>\n\n<pre><code>if([nowPlaying isPlaying]) {\n for(int i = 1; i < 100; ++i)\n {\n [nowPlaying setVolume: (1.0 / i)];\n Sleep(20);\n }\n [nowPlaying stop];\n wasPlaying = TRUE;\n}\n</code></pre>\n"
},
{
"answer_id": 294399,
"author": "Stuart Grimshaw",
"author_id": 11470,
"author_profile": "https://Stackoverflow.com/users/11470",
"pm_score": 2,
"selected": true,
"text": "<p>This is the final version of the method:</p>\n\n<pre><code>-(void)play:(NSSound *)soundEffect:(BOOL)stopIfPlaying {\n BOOL wasPlaying = FALSE;\n\n if([nowPlaying isPlaying]) {\n struct timespec ts;\n ts.tv_sec = 0;\n ts.tv_nsec = 25000000;\n\n // If the sound effect is the same, fade it out.\n if(soundEffect == nowPlaying)\n {\n for(int i = 1; i < 30; ++i)\n {\n [nowPlaying setVolume: (1.0 / i )];\n nanosleep(&ts, &ts);\n } \n }\n\n [nowPlaying stop];\n [nowPlaying setVolume:1];\n wasPlaying = TRUE;\n } \n\n if(soundEffect != nowPlaying)\n {\n [soundEffect play];\n nowPlaying = soundEffect;\n } else if(soundEffect == nowPlaying && ![nowPlaying isPlaying] && !wasPlaying) {\n [nowPlaying play];\n }\n}\n</code></pre>\n\n<p>So it only fades out if I pass the same sound in (ie, click the same button), also, I went for nanosleep rather than sleep, as that on has a granularity of 1 second.</p>\n\n<p>I struggled for a while trying to work out why my 200 millisecond delay didn't seem to have any effect, but then 200 NANOseconds isn't really that long is it :-)</p>\n"
},
{
"answer_id": 302630,
"author": "Marc Charbonneau",
"author_id": 35136,
"author_profile": "https://Stackoverflow.com/users/35136",
"pm_score": 1,
"selected": false,
"text": "<p>I would use NSTimer to avoid blocking the main thread.</p>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11470/"
] |
I've written a cheap & cheerful sound board in for my Mac, and I play the various sounds with NSSound like this:
```
-(void)play:(NSSound *)soundEffect:(BOOL)stopIfPlaying {
BOOL wasPlaying = FALSE;
if([nowPlaying isPlaying]) {
[nowPlaying stop];
wasPlaying = TRUE;
}
if(soundEffect != nowPlaying)
{
[soundEffect play];
nowPlaying = soundEffect;
} else if(soundEffect == nowPlaying && ![nowPlaying isPlaying] && !wasPlaying) {
[nowPlaying play];
}
}
```
Rather than just stop it dead, I'd like it to fade out over a couple of seconds or so.
|
This is the final version of the method:
```
-(void)play:(NSSound *)soundEffect:(BOOL)stopIfPlaying {
BOOL wasPlaying = FALSE;
if([nowPlaying isPlaying]) {
struct timespec ts;
ts.tv_sec = 0;
ts.tv_nsec = 25000000;
// If the sound effect is the same, fade it out.
if(soundEffect == nowPlaying)
{
for(int i = 1; i < 30; ++i)
{
[nowPlaying setVolume: (1.0 / i )];
nanosleep(&ts, &ts);
}
}
[nowPlaying stop];
[nowPlaying setVolume:1];
wasPlaying = TRUE;
}
if(soundEffect != nowPlaying)
{
[soundEffect play];
nowPlaying = soundEffect;
} else if(soundEffect == nowPlaying && ![nowPlaying isPlaying] && !wasPlaying) {
[nowPlaying play];
}
}
```
So it only fades out if I pass the same sound in (ie, click the same button), also, I went for nanosleep rather than sleep, as that on has a granularity of 1 second.
I struggled for a while trying to work out why my 200 millisecond delay didn't seem to have any effect, but then 200 NANOseconds isn't really that long is it :-)
|
288,699 |
<p>Can someone show me how to get the <code>top</code> & <code>left</code> position of a <code>div</code> or <code>span</code> element when one is not specified?</p>
<p>ie:</p>
<pre><code><span id='11a' style='top:55px;' onmouseover="GetPos(this);">stuff</span>
<span id='12a' onmouseover="GetPos(this);">stuff</span>
</code></pre>
<p>In the above, if I do:</p>
<pre><code>document.getElementById('11a').style.top
</code></pre>
<p>The value of <code>55px</code> is returned. However, if I try that for <code>span</code> '12a', then nothing gets returned.</p>
<p>I have a bunch of <code>div</code>/<code>span</code>s on a page that I cannot specify the <code>top</code>/<code>left</code> properties for, but I need to display a <code>div</code> directly under that element.</p>
|
[
{
"answer_id": 288708,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 8,
"selected": true,
"text": "<p>This function will tell you the x,y position of the element relative to the page. Basically you have to loop up through all the element's parents and add their offsets together.</p>\n\n<pre><code>function getPos(el) {\n // yay readability\n for (var lx=0, ly=0;\n el != null;\n lx += el.offsetLeft, ly += el.offsetTop, el = el.offsetParent);\n return {x: lx,y: ly};\n}\n</code></pre>\n\n<p>However, if you just wanted the x,y position of the element relative to its container, then all you need is:</p>\n\n<pre><code>var x = el.offsetLeft, y = el.offsetTop;\n</code></pre>\n\n<p>To put an element directly below this one, you'll also need to know its height. This is stored in the offsetHeight/offsetWidth property.</p>\n\n<pre><code>var yPositionOfNewElement = el.offsetTop + el.offsetHeight + someMargin;\n</code></pre>\n"
},
{
"answer_id": 288731,
"author": "alex",
"author_id": 31671,
"author_profile": "https://Stackoverflow.com/users/31671",
"pm_score": 8,
"selected": false,
"text": "<p>You can call the method <code>getBoundingClientRect()</code> on a reference to the element. Then you can examine the <code>top</code>, <code>left</code>, <code>right</code> and/or <code>bottom</code> properties...</p>\n\n<pre><code>var offsets = document.getElementById('11a').getBoundingClientRect();\nvar top = offsets.top;\nvar left = offsets.left;\n</code></pre>\n\n<p>If using jQuery, you can use the more succinct code...</p>\n\n<pre><code>var offsets = $('#11a').offset();\nvar top = offsets.top;\nvar left = offsets.left;\n</code></pre>\n"
},
{
"answer_id": 7207965,
"author": "Dylan Valade",
"author_id": 638452,
"author_profile": "https://Stackoverflow.com/users/638452",
"pm_score": 4,
"selected": false,
"text": "<p>As Alex noted you can use jQuery offset() to get the position relative to the document flow. Use position() for its x,y coordinates relative to the parent.</p>\n\n<p>EDIT: Switched <code>document.ready</code> for <code>window.load</code> because <code>load</code> waits for all of the elements so you get their size instead of simply preparing the DOM. In my experience, <code>load</code> results in fewer incorrectly Javascript positioned elements.</p>\n\n<pre><code>$(window).load(function(){ \n // Log the position with jQuery\n var position = $('#myDivInQuestion').position();\n console.log('X: ' + position.left + \", Y: \" + position.top );\n});\n</code></pre>\n"
},
{
"answer_id": 13019016,
"author": "Jens Frandsen",
"author_id": 1451951,
"author_profile": "https://Stackoverflow.com/users/1451951",
"pm_score": 3,
"selected": false,
"text": "<p>For anyone needing just top or left position, slight modifications to @Nickf's readable code does the trick.</p>\n\n<pre><code>function getTopPos(el) {\n for (var topPos = 0;\n el != null;\n topPos += el.offsetTop, el = el.offsetParent);\n return topPos;\n}\n</code></pre>\n\n<p>and</p>\n\n<pre><code>function getLeftPos(el) {\n for (var leftPos = 0;\n el != null;\n leftPos += el.offsetLeft, el = el.offsetParent);\n return leftPos;\n}\n</code></pre>\n"
},
{
"answer_id": 27809127,
"author": "lukeed",
"author_id": 3577474,
"author_profile": "https://Stackoverflow.com/users/3577474",
"pm_score": 2,
"selected": false,
"text": "<p>I realize this is an old thread, but @alex 's answer needs to be marked as the correct answer</p>\n\n<p><code>element.getBoundingClientRect()</code> is an exact match to jQuery's <code>$(element).offset()</code></p>\n\n<p>And it's compatible with IE4+ ...\n<a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element.getBoundingClientRect\" rel=\"nofollow\">https://developer.mozilla.org/en-US/docs/Web/API/Element.getBoundingClientRect</a></p>\n"
},
{
"answer_id": 30949389,
"author": "Benjamin Intal",
"author_id": 174172,
"author_profile": "https://Stackoverflow.com/users/174172",
"pm_score": 4,
"selected": false,
"text": "<p>While @nickf's answer works. If you don't care for older browsers, you can use this pure Javascript version. Works in IE9+, and others</p>\n\n<pre><code>var rect = el.getBoundingClientRect();\n\nvar position = {\n top: rect.top + window.pageYOffset,\n left: rect.left + window.pageXOffset\n};\n</code></pre>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26685/"
] |
Can someone show me how to get the `top` & `left` position of a `div` or `span` element when one is not specified?
ie:
```
<span id='11a' style='top:55px;' onmouseover="GetPos(this);">stuff</span>
<span id='12a' onmouseover="GetPos(this);">stuff</span>
```
In the above, if I do:
```
document.getElementById('11a').style.top
```
The value of `55px` is returned. However, if I try that for `span` '12a', then nothing gets returned.
I have a bunch of `div`/`span`s on a page that I cannot specify the `top`/`left` properties for, but I need to display a `div` directly under that element.
|
This function will tell you the x,y position of the element relative to the page. Basically you have to loop up through all the element's parents and add their offsets together.
```
function getPos(el) {
// yay readability
for (var lx=0, ly=0;
el != null;
lx += el.offsetLeft, ly += el.offsetTop, el = el.offsetParent);
return {x: lx,y: ly};
}
```
However, if you just wanted the x,y position of the element relative to its container, then all you need is:
```
var x = el.offsetLeft, y = el.offsetTop;
```
To put an element directly below this one, you'll also need to know its height. This is stored in the offsetHeight/offsetWidth property.
```
var yPositionOfNewElement = el.offsetTop + el.offsetHeight + someMargin;
```
|
288,715 |
<p>How can I check whether a variable is defined in Ruby? Is there an <code>isset</code>-type method available?</p>
|
[
{
"answer_id": 288724,
"author": "digitalsanctum",
"author_id": 22436,
"author_profile": "https://Stackoverflow.com/users/22436",
"pm_score": 4,
"selected": false,
"text": "<p><code>defined?(your_var)</code> will work. Depending on what you're doing you can also do something like <code>your_var.nil?</code></p>\n"
},
{
"answer_id": 288726,
"author": "Ricardo Acras",
"author_id": 19224,
"author_profile": "https://Stackoverflow.com/users/19224",
"pm_score": 11,
"selected": true,
"text": "<p>Use the <code>defined?</code> keyword (<a href=\"http://ruby-doc.org/docs/keywords/1.9/Object.html#method-i-defined-3F\" rel=\"noreferrer\">documentation</a>). It will return a String with the kind of the item, or <code>nil</code> if it doesnβt exist.</p>\n\n<pre><code>>> a = 1\n => 1\n>> defined? a\n => \"local-variable\"\n>> defined? b\n => nil\n>> defined? nil\n => \"nil\"\n>> defined? String\n => \"constant\"\n>> defined? 1\n => \"expression\"\n</code></pre>\n\n<p>As skalee commented: \"It is worth noting that variable which is set to nil is initialized.\"</p>\n\n<pre><code>>> n = nil \n>> defined? n\n => \"local-variable\"\n</code></pre>\n"
},
{
"answer_id": 288729,
"author": "danmayer",
"author_id": 27738,
"author_profile": "https://Stackoverflow.com/users/27738",
"pm_score": 7,
"selected": false,
"text": "<p>This is useful if you want to do nothing if it does exist but create it if it doesn't exist.</p>\n\n<pre><code>def get_var\n @var ||= SomeClass.new()\nend\n</code></pre>\n\n<p>This only creates the new instance once. After that it just keeps returning the var.</p>\n"
},
{
"answer_id": 3724712,
"author": "Sardathrion - against SE abuse",
"author_id": 232794,
"author_profile": "https://Stackoverflow.com/users/232794",
"pm_score": 3,
"selected": false,
"text": "<p>Here is some code, nothing rocket science but it works well enough</p>\n\n<pre><code>require 'rubygems'\nrequire 'rainbow'\nif defined?(var).nil? # .nil? is optional but might make for clearer intent.\n print \"var is not defined\\n\".color(:red)\nelse\n print \"car is defined\\n\".color(:green)\nend\n</code></pre>\n\n<p>Clearly, the colouring code is not necessary, just a nice visualation in this toy example.</p>\n"
},
{
"answer_id": 6152507,
"author": "foomip",
"author_id": 773112,
"author_profile": "https://Stackoverflow.com/users/773112",
"pm_score": 6,
"selected": false,
"text": "<p>The correct syntax for the above statement is:</p>\n\n<pre><code>if (defined?(var)).nil? # will now return true or false\n print \"var is not defined\\n\".color(:red)\nelse\n print \"var is defined\\n\".color(:green)\nend\n</code></pre>\n\n<p>substituting (<code>var</code>) with your variable. This syntax will return a true/false value for evaluation in the if statement.</p>\n"
},
{
"answer_id": 9728836,
"author": "Bruno Barros",
"author_id": 1272706,
"author_profile": "https://Stackoverflow.com/users/1272706",
"pm_score": 3,
"selected": false,
"text": "<p>You can try:</p>\n\n<pre><code>unless defined?(var)\n #ruby code goes here\nend\n=> true\n</code></pre>\n\n<p>Because it returns a boolean.</p>\n"
},
{
"answer_id": 10049018,
"author": "user761856",
"author_id": 761856,
"author_profile": "https://Stackoverflow.com/users/761856",
"pm_score": 4,
"selected": false,
"text": "<p>Try \"unless\" instead of \"if\"</p>\n\n<pre><code>a = \"apple\"\n# Note that b is not declared\nc = nil\n\nunless defined? a\n puts \"a is not defined\"\nend\n\nunless defined? b\n puts \"b is not defined\"\nend\n\nunless defined? c\n puts \"c is not defined\"\nend\n</code></pre>\n"
},
{
"answer_id": 16238957,
"author": "Saqib R.",
"author_id": 932733,
"author_profile": "https://Stackoverflow.com/users/932733",
"pm_score": 3,
"selected": false,
"text": "<p>Use <code>defined? YourVariable</code><br>\n<strong><em>Keep it simple silly</em></strong> .. ;)</p>\n"
},
{
"answer_id": 27445810,
"author": "Robert Klemme",
"author_id": 131583,
"author_profile": "https://Stackoverflow.com/users/131583",
"pm_score": 2,
"selected": false,
"text": "<p>Please note the distinction between \"defined\" and \"assigned\".</p>\n\n<pre><code>$ ruby -e 'def f; if 1>2; x=99; end;p x, defined? x; end;f'\nnil\n\"local-variable\"\n</code></pre>\n\n<p>x is defined even though it is never assigned!</p>\n"
},
{
"answer_id": 33307520,
"author": "Elliott",
"author_id": 4561506,
"author_profile": "https://Stackoverflow.com/users/4561506",
"pm_score": 0,
"selected": false,
"text": "<p>Also, you can check if it's defined while in a string via interpolation, if you code: </p>\n\n<pre><code>puts \"Is array1 defined and what type is it? #{defined?(@array1)}\"\n</code></pre>\n\n<p>The system will tell you the type if it is defined.\nIf it is not defined it will just return a warning saying the variable is not initialized.</p>\n\n<p>Hope this helps! :)</p>\n"
},
{
"answer_id": 41532508,
"author": "donnoman",
"author_id": 5220436,
"author_profile": "https://Stackoverflow.com/users/5220436",
"pm_score": 3,
"selected": false,
"text": "<p>As many other examples show you don't actually need a boolean from a method to make logical choices in ruby. It would be a poor form to coerce everything to a boolean unless you actually need a boolean. </p>\n\n<p>But if you absolutely need a boolean. Use !! (bang bang) or \"falsy falsy reveals the truth\".</p>\n\n<pre><code>βΊ irb\n>> a = nil\n=> nil\n>> defined?(a)\n=> \"local-variable\"\n>> defined?(b)\n=> nil\n>> !!defined?(a)\n=> true\n>> !!defined?(b)\n=> false\n</code></pre>\n\n<p>Why it doesn't usually pay to coerce:</p>\n\n<pre><code>>> (!!defined?(a) ? \"var is defined\".colorize(:green) : \"var is not defined\".colorize(:red)) == (defined?(a) ? \"var is defined\".colorize(:green) : \"var is not defined\".colorize(:red))\n=> true\n</code></pre>\n\n<p>Here's an example where it matters because it relies on the implicit coercion of the boolean value to its string representation.</p>\n\n<pre><code>>> puts \"var is defined? #{!!defined?(a)} vs #{defined?(a)}\"\nvar is defined? true vs local-variable\n=> nil\n</code></pre>\n"
},
{
"answer_id": 44982213,
"author": "BenKoshy",
"author_id": 4880924,
"author_profile": "https://Stackoverflow.com/users/4880924",
"pm_score": 4,
"selected": false,
"text": "<h3>WARNING Re: A Common Ruby Pattern</h3>\n<p>This is the key answer: the <code>defined?</code> method. The <a href=\"https://stackoverflow.com/a/288726/4880924\">accepted answer above</a> illustrates this perfectly.</p>\n<p><em><strong>But there is a shark, lurking beneath the waves...</strong></em></p>\n<p>Consider this common ruby pattern:</p>\n<pre><code> def method1\n @x ||= method2\n end\n\n def method2\n nil\n end\n</code></pre>\n<ol>\n<li><code>method2</code> always returns <code>nil</code>.</li>\n<li>The first time you call <code>method1</code>, the <code>@x</code> variable is not set - therefore <code>method2</code> will be run. and</li>\n<li><code>method2</code> will set <code>@x</code> to <code>nil</code>.</li>\n</ol>\n<p>But what happens the second time you call <code>method1</code>?</p>\n<p>Remember @x has already been set to nil. But <code>method2</code> will still be run again!! If method2 is a costly undertaking this might not be something that you want.</p>\n<p>Let the <code>defined?</code> method come to the rescue:</p>\n<pre><code> def method1\n return @x if defined? @x\n @x = method2\n end\n</code></pre>\n<p>As with most things, the devil is in the implementation details.</p>\n"
},
{
"answer_id": 45691059,
"author": "leberknecht",
"author_id": 1466713,
"author_profile": "https://Stackoverflow.com/users/1466713",
"pm_score": 2,
"selected": false,
"text": "<p>It should be mentioned that using <code>defined</code> to check if a specific field is set in a hash might behave unexpected:</p>\n\n<pre><code>var = {}\nif defined? var['unknown']\n puts 'this is unexpected'\nend\n# will output \"this is unexpected\"\n</code></pre>\n\n<p>The syntax is correct here, but <code>defined? var['unknown']</code> will be evaluated to the string <code>\"method\"</code>, so the <code>if</code> block will be executed</p>\n\n<p>edit: The correct notation for checking if a key exists in a hash would be:</p>\n\n<pre><code>if var.key?('unknown')\n</code></pre>\n"
},
{
"answer_id": 50395751,
"author": "John Donner",
"author_id": 4411487,
"author_profile": "https://Stackoverflow.com/users/4411487",
"pm_score": 2,
"selected": false,
"text": "<p><code>defined?</code> is great, but if you are in a Rails environment you can also use <code>try</code>, especially in cases where you want to check a dynamic variable name:</p>\n\n<pre><code>foo = 1\nmy_foo = \"foo\"\nmy_bar = \"bar\"\ntry(:foo) # => 1\ntry(:bar) # => nil\ntry(my_foo) # => 1\ntry(my_bar) # => nil\n</code></pre>\n"
},
{
"answer_id": 66048871,
"author": "stevec",
"author_id": 5783745,
"author_profile": "https://Stackoverflow.com/users/5783745",
"pm_score": 0,
"selected": false,
"text": "<p>Leaving an incredibly simple example in case it helps.</p>\n<p>When variable <strong>doesn't exist</strong>:</p>\n<pre><code>if defined? a then "hi" end\n# => nil\n</code></pre>\n<p>When variable <strong>does exist</strong>:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>a = 2\nif defined? a then "hi" end\n# => "hi"\n</code></pre>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
] |
How can I check whether a variable is defined in Ruby? Is there an `isset`-type method available?
|
Use the `defined?` keyword ([documentation](http://ruby-doc.org/docs/keywords/1.9/Object.html#method-i-defined-3F)). It will return a String with the kind of the item, or `nil` if it doesnβt exist.
```
>> a = 1
=> 1
>> defined? a
=> "local-variable"
>> defined? b
=> nil
>> defined? nil
=> "nil"
>> defined? String
=> "constant"
>> defined? 1
=> "expression"
```
As skalee commented: "It is worth noting that variable which is set to nil is initialized."
```
>> n = nil
>> defined? n
=> "local-variable"
```
|
288,732 |
<p>I'm working on a program that searches entire drives for a given file. At the moment, I calculate an MD5 hash for the known file and then scan all files recursively, looking for a match.</p>
<p>The only problem is that MD5 is painfully slow on large files. Is there a faster alternative that I can use while retaining a very small probablity of false positives?</p>
<p>All code is in C#.</p>
<p>Thank you.</p>
<p><strong>Update</strong></p>
<p>I've read that even MD5 can be pretty quick and that disk I/O should be the limiting factor. That leads me to believe that my code might not be optimal. Are there any problems with this approach?</p>
<pre><code> MD5 md5 = MD5.Create();
StringBuilder sb = new StringBuilder();
try
{
using (FileStream fs = File.Open(fileName, FileMode.Open, FileAccess.Read))
{
foreach (byte b in md5.ComputeHash(fs))
sb.Append(b.ToString("X2"));
}
return sb.ToString();
}
catch (Exception)
{
return "";
}
</code></pre>
|
[
{
"answer_id": 288749,
"author": "jalf",
"author_id": 33213,
"author_profile": "https://Stackoverflow.com/users/33213",
"pm_score": 3,
"selected": false,
"text": "<p>just read the file linearly? It seems pretty pointless to read the entire file, compute a md5 hash, and then compare the hash.</p>\n\n<p>Reading the file sequentially, a few bytes at a time, would allow you to discard the vast majority of files after reading, say, 4 bytes. And you'd save all the processing overhead of computing a hashing function which doesn't give you anything in your case.</p>\n\n<p>If you already had the hashes for all the files in the drive, it'd make sense to compare them, but if you have to compute them on the fly, there just doesn't seem to be any advantage to the hashing.</p>\n\n<p>Am I missing something here? What does hashing buy you in this case?</p>\n"
},
{
"answer_id": 288754,
"author": "Adam Byrtek",
"author_id": 36656,
"author_profile": "https://Stackoverflow.com/users/36656",
"pm_score": 3,
"selected": false,
"text": "<p>First consider what is really your bottleneck: the hash function itself or rather a disk access speed? If you are bounded by disk, changing hashing algorithm won't give you much. From your description I imply that you are always scanning the whole disk to find a match - consider building the index first and then only match a given hash against the index, this will be much faster.</p>\n"
},
{
"answer_id": 288756,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 7,
"selected": true,
"text": "<p>I hope you're checking for an MD5 match only if the file size already matches.</p>\n\n<p>Another optimization is to do a quick checksum of the first 1K (or some other arbitrary, but reasonably small number) and make sure those match before working the whole file.</p>\n\n<p>Of course, all this assumes that you're just looking for a match/nomatch decision for a particular file.</p>\n"
},
{
"answer_id": 288789,
"author": "CesarB",
"author_id": 28258,
"author_profile": "https://Stackoverflow.com/users/28258",
"pm_score": 3,
"selected": false,
"text": "<p>There is one small problem with using MD5 to compare files: there are known pairs of files which are <em>different</em> but have the <em>same</em> MD5.</p>\n\n<p>This means you can use MD5 to tell if the files are <em>different</em> (if the MD5 is different, the files must be different), but you cannot use MD5 to tell if the files are <em>equal</em> (if the files are equal, the MD5 must be the same, but if the MD5 is equal, the files might or might not be equal).</p>\n\n<p>You should either use a hash function which has not been broken yet (like SHA-1), or (as @SoapBox mentioned) use MD5 only as a fast way to find candidates for a deeper comparison.</p>\n\n<p>References:</p>\n\n<ul>\n<li><a href=\"http://www.win.tue.nl/hashclash/SoftIntCodeSign/\" rel=\"noreferrer\">http://www.win.tue.nl/hashclash/SoftIntCodeSign/</a></li>\n</ul>\n"
},
{
"answer_id": 3314181,
"author": "Rich.",
"author_id": 399721,
"author_profile": "https://Stackoverflow.com/users/399721",
"pm_score": 3,
"selected": false,
"text": "<p>Regardless of cryptographic requirements, the possibility of a hash collision exists, so no hashing function can be used to <em>guarantee</em> that two files are identical.</p>\n\n<p>I wrote similar code a while back which I got to run pretty fast by indexing all the files first, and discarding any with a different size. A fast hash comparison (on part of each file) was then performed on the remaining entries (comparing bytes for this step was proved to be less useful - many file types have common headers which have identical bytes at the start of the file). Any files that were left after this stage were then checked using MD5, and finally a byte comparison of the whole file if the MD5 matched, just to ensure that the contents were the same. </p>\n"
},
{
"answer_id": 17743934,
"author": "Sergey Grischenko",
"author_id": 2599083,
"author_profile": "https://Stackoverflow.com/users/2599083",
"pm_score": 0,
"selected": false,
"text": "<p>Use MD5CryptoServiceProvider and BufferedStream</p>\n\n<pre><code> using (FileStream stream = File.OpenRead(filePath))\n {\n using (var bufferedStream = new BufferedStream(stream, 1024 * 32))\n {\n var sha = new MD5CryptoServiceProvider();\n byte[] checksum = sha.ComputeHash(bufferedStream);\n return BitConverter.ToString(checksum).Replace(\"-\", String.Empty);\n }\n }\n</code></pre>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14333/"
] |
I'm working on a program that searches entire drives for a given file. At the moment, I calculate an MD5 hash for the known file and then scan all files recursively, looking for a match.
The only problem is that MD5 is painfully slow on large files. Is there a faster alternative that I can use while retaining a very small probablity of false positives?
All code is in C#.
Thank you.
**Update**
I've read that even MD5 can be pretty quick and that disk I/O should be the limiting factor. That leads me to believe that my code might not be optimal. Are there any problems with this approach?
```
MD5 md5 = MD5.Create();
StringBuilder sb = new StringBuilder();
try
{
using (FileStream fs = File.Open(fileName, FileMode.Open, FileAccess.Read))
{
foreach (byte b in md5.ComputeHash(fs))
sb.Append(b.ToString("X2"));
}
return sb.ToString();
}
catch (Exception)
{
return "";
}
```
|
I hope you're checking for an MD5 match only if the file size already matches.
Another optimization is to do a quick checksum of the first 1K (or some other arbitrary, but reasonably small number) and make sure those match before working the whole file.
Of course, all this assumes that you're just looking for a match/nomatch decision for a particular file.
|
288,739 |
<p>I need to generate random numbers within a specified interval, [max;min].</p>
<p>Also, the random numbers should be uniformly distributed over the interval, not located to a particular point.</p>
<p>Currenly I am generating as:</p>
<pre><code>for(int i=0; i<6; i++)
{
DWORD random = rand()%(max-min+1) + min;
}
</code></pre>
<p>From my tests, random numbers are generated around one point only.</p>
<pre><code>Example
min = 3604607;
max = 7654607;
</code></pre>
<p>Random numbers generated:</p>
<pre><code>3631594
3609293
3630000
3628441
3636376
3621404
</code></pre>
<p>From answers below: OK, RAND_MAX is 32767. I am on C++ Windows platform. Is there any other method to generate random numbers with a uniform distribution?</p>
|
[
{
"answer_id": 288753,
"author": "Jason Coco",
"author_id": 34218,
"author_profile": "https://Stackoverflow.com/users/34218",
"pm_score": 2,
"selected": false,
"text": "<p>If you want numbers to be uniformly distributed over the range, you should break your range up into a number of equal sections that represent the number of points you need. Then get a random number with a min/max for each section.</p>\n\n<p>As another note, you should probably not use <code>rand()</code> as it's not very good at actually generating random numbers. I don't know what platform you're running on, but there is probably a better function you can call like <code>random()</code>.</p>\n"
},
{
"answer_id": 288760,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 2,
"selected": false,
"text": "<p>Check what <code>RAND_MAX</code> is on your system -- I'm guessing it is only 16 bits, and your range is too big for it.</p>\n\n<p>Beyond that see this discussion on: <a href=\"http://members.cox.net/srice1/random/genrange.html\" rel=\"nofollow noreferrer\">Generating Random Integers within a Desired Range</a> and the notes on using (or not) the <a href=\"http://members.cox.net/srice1/random/crandom.html\" rel=\"nofollow noreferrer\">C rand() function</a>.</p>\n"
},
{
"answer_id": 288762,
"author": "SoapBox",
"author_id": 36384,
"author_profile": "https://Stackoverflow.com/users/36384",
"pm_score": 3,
"selected": false,
"text": "<p>If you are concerned about randomness and not about speed, you should use a secure random number generation method. There are several ways to do this... The easiest one being to use <a href=\"http://www.openssl.org/\" rel=\"nofollow noreferrer\">OpenSSL's</a> <a href=\"http://www.openssl.org/docs/crypto/rand.html#\" rel=\"nofollow noreferrer\">Random Number Generator</a>.</p>\n\n<p>You can also write your own using an encryption algorithm (like <a href=\"http://en.wikipedia.org/wiki/Advanced_Encryption_Standard\" rel=\"nofollow noreferrer\">AES</a>). By picking a seed and an <a href=\"http://en.wikipedia.org/wiki/Initialization_vector\" rel=\"nofollow noreferrer\">IV</a> and then continuously re-encrypting the output of the encryption function. Using OpenSSL is easier, but less manly.</p>\n"
},
{
"answer_id": 288769,
"author": "abelenky",
"author_id": 34824,
"author_profile": "https://Stackoverflow.com/users/34824",
"pm_score": 3,
"selected": false,
"text": "<p>You should look at <code>RAND_MAX</code> for your particular compiler/environment.\nI think you would see these results if <code>rand()</code> is producing a random 16-bit number. (you seem to be assuming it will be a 32-bit number).</p>\n\n<p>I can't promise this is the answer, but please post your value of <code>RAND_MAX</code>, and a little more detail on your environment.</p>\n"
},
{
"answer_id": 288777,
"author": "Kluge",
"author_id": 8752,
"author_profile": "https://Stackoverflow.com/users/8752",
"pm_score": 0,
"selected": false,
"text": "<p>By their nature, a small sample of random numbers doesn't have to be uniformly distributed. They're random, after all. I agree that if a random number generator is generating numbers that consistently appear to be grouped, then there is probably something wrong with it.</p>\n<p>But keep in mind that randomness isn't necessarily uniform.</p>\n"
},
{
"answer_id": 288786,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 3,
"selected": false,
"text": "<p>If <code>RAND_MAX</code> is 32767, you can double the number of bits easily.</p>\n\n<pre><code>int BigRand()\n{\n assert(INT_MAX/(RAND_MAX+1) > RAND_MAX);\n return rand() * (RAND_MAX+1) + rand();\n}\n</code></pre>\n"
},
{
"answer_id": 288816,
"author": "anand",
"author_id": 33411,
"author_profile": "https://Stackoverflow.com/users/33411",
"pm_score": -1,
"selected": false,
"text": "<p>I just found this on the Internet. This should work:</p>\n\n<pre><code>DWORD random = ((min) + rand()/(RAND_MAX + 1.0) * ((max) - (min) + 1));\n</code></pre>\n"
},
{
"answer_id": 288844,
"author": "calandoa",
"author_id": 26074,
"author_profile": "https://Stackoverflow.com/users/26074",
"pm_score": 0,
"selected": false,
"text": "<p>The solution given by <a href=\"http://linux.die.net/man/3/rand\" rel=\"nofollow noreferrer\">man 3 rand</a> for a number between 1 and 10 inclusive is:</p>\n\n<pre><code>j = 1 + (int) (10.0 * (rand() / (RAND_MAX + 1.0)));\n</code></pre>\n\n<p>In your case, it would be:</p>\n\n<pre><code>j = min + (int) ((max-min+1) * (rand() / (RAND_MAX + 1.0)));\n</code></pre>\n\n<p>Of course, this is not perfect randomness or uniformity as some other messages are pointing out, but this is enough for most cases.</p>\n"
},
{
"answer_id": 288869,
"author": "peterchen",
"author_id": 31317,
"author_profile": "https://Stackoverflow.com/users/31317",
"pm_score": 6,
"selected": false,
"text": "<p><strong>Warning: Do not use <code>rand()</code> for statistics, simulation, cryptography or anything serious.</strong></p>\n<p>It's good enough to make numbers <em>look</em> random for a typical human in a hurry, no more.</p>\n<p>See <a href=\"https://stackoverflow.com/a/20136256/4513656\">Jefffrey's reply</a> for better options, or <a href=\"https://stackoverflow.com/a/2572373/59087\">this answer</a> for crypto-secure random numbers.</p>\n<hr />\n<p>Generally, the high bits show a better distribution than the low bits, so the recommended way to generate random numbers of a range for simple purposes is:</p>\n<pre><code>((double) rand() / (RAND_MAX+1)) * (max-min+1) + min\n</code></pre>\n<p><strong>Note</strong>: make sure RAND_MAX+1 does not overflow (thanks Demi)!</p>\n<p>The division generates a random number in the interval [0, 1); "stretch" this to the required range. Only when max-min+1 gets close to RAND_MAX you need a "BigRand()" function like posted by Mark Ransom.</p>\n<p>This also avoids some slicing problems due to the modulo, which can worsen your numbers even more.</p>\n<hr />\n<p>The built-in random number generator isn't guaranteed to have a the quality required for statistical simulations. It is OK for numbers to "look random" to a human, but for a serious application, you should take something better - or at least check its properties (uniform distribution is usually good, but values tend to correlate, and the sequence is deterministic). Knuth has an excellent (if hard-to-read) treatise on random number generators, and I recently found <a href=\"http://en.wikipedia.org/wiki/Linear_feedback_shift_register\" rel=\"nofollow noreferrer\">LFSR</a> to be excellent and darn simple to implement, given its properties are OK for you.</p>\n"
},
{
"answer_id": 288929,
"author": "Jeff Thomas",
"author_id": 1561,
"author_profile": "https://Stackoverflow.com/users/1561",
"pm_score": 3,
"selected": false,
"text": "<p>If you are able to, use <a href=\"http://en.wikipedia.org/wiki/Boost_C++_Libraries\" rel=\"nofollow noreferrer\">Boost</a>. I have had good luck with their <a href=\"http://www.boost.org/doc/libs/1_37_0/libs/random/index.html\" rel=\"nofollow noreferrer\">random library</a>.</p>\n\n<p><code>uniform_int</code> should do what you want.</p>\n"
},
{
"answer_id": 20136256,
"author": "Shoe",
"author_id": 493122,
"author_profile": "https://Stackoverflow.com/users/493122",
"pm_score": 9,
"selected": true,
"text": "<h2>Why <code>rand</code> is a bad idea</h2>\n<p>Most of the answers you got here make use of the <code>rand</code> function and the modulus operator. That method <a href=\"http://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful\" rel=\"noreferrer\">may not generate numbers uniformly</a> (it depends on the range and the value of <code>RAND_MAX</code>), and is therefore discouraged.</p>\n<h2>C++11 and generation over a range</h2>\n<p>With C++11 multiple other options have risen. One of which fits your requirements, for generating a random number in a range, pretty nicely: <a href=\"http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution\" rel=\"noreferrer\"><code>std::uniform_int_distribution</code></a>. Here's an example:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include <iostream>\n#include <random>\nint main()\n{ \n const int range_from = 0;\n const int range_to = 1000;\n std::random_device rand_dev;\n std::mt19937 generator(rand_dev());\n std::uniform_int_distribution<int> distr(range_from, range_to);\n\n std::cout << distr(generator) << '\\n';\n}\n</code></pre>\n<p><sub><a href=\"https://godbolt.org/z/xq77YGjqc\" rel=\"noreferrer\">Try it online on Godbolt</a></sub></p>\n<p>And <a href=\"http://coliru.stacked-crooked.com/a/c5b94870fdcd13f2\" rel=\"noreferrer\">here</a>'s the running example.</p>\n<p>Template function may help some:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>template<typename T>\nT random(T range_from, T range_to) {\n std::random_device rand_dev;\n std::mt19937 generator(rand_dev());\n std::uniform_int_distribution<T> distr(range_from, range_to);\n return distr(generator);\n}\n</code></pre>\n<h3>Other random generators</h3>\n<p>The <a href=\"http://en.cppreference.com/w/cpp/numeric/random\" rel=\"noreferrer\"><code><random></code> header</a> offers innumerable other random number generators with different kind of distributions including Bernoulli, Poisson and normal.</p>\n<h3>How can I shuffle a container?</h3>\n<p>The standard provides <a href=\"http://en.cppreference.com/w/cpp/algorithm/random_shuffle\" rel=\"noreferrer\"><code>std::shuffle</code></a>, which can be used as follows:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include <iostream>\n#include <random>\n#include <vector>\nint main()\n{ \n std::vector<int> vec = {4, 8, 15, 16, 23, 42};\n \n std::random_device random_dev;\n std::mt19937 generator(random_dev());\n \n std::shuffle(vec.begin(), vec.end(), generator);\n std::for_each(vec.begin(), vec.end(), [](auto i){std::cout << i << '\\n';});\n}\n</code></pre>\n<p><sub><a href=\"https://godbolt.org/z/rxrrrche5\" rel=\"noreferrer\">Try it online on Godbolt</a></sub></p>\n<p>The algorithm will reorder the elements randomly, with a linear complexity.</p>\n<h2>Boost.Random</h2>\n<p>Another alternative, in case you don't have access to a C++11+ compiler, is to use <a href=\"http://www.boost.org/doc/libs/1_55_0/doc/html/boost_random.html\" rel=\"noreferrer\">Boost.Random</a>. Its interface is very similar to the C++11 one.</p>\n"
},
{
"answer_id": 21478635,
"author": "Ritualmaster",
"author_id": 3256548,
"author_profile": "https://Stackoverflow.com/users/3256548",
"pm_score": 0,
"selected": false,
"text": "<h3>A solution</h3>\n<p><code>((double) rand() / (RAND_MAX+1)) * (max-min+1) + min</code></p>\n<p><strong>Warning</strong>: Don't forget due to stretching and possible precision errors (even if RAND_MAX were large enough), you'll only be able to generate evenly distributed "bins" and not all numbers in [min,max].</p>\n<hr />\n<h3>A solution using Bigrand</h3>\n<p><strong>Warning</strong>: Note that this doubles the bits, but still won't be able to generate all numbers in your range in general, i.e., it is not necessarily true that BigRand() will generate all numbers between in its range.</p>\n<hr />\n<p><strong>Information</strong>: Your approach (modulo) is "fine" as long as the range of rand() exceeds your interval range and rand() is "uniform". The error for at most the first max - min numbers is 1/(RAND_MAX +1).</p>\n<p>Also, I suggest to switch to the new <a href=\"http://www.cplusplus.com/reference/random/\" rel=\"nofollow noreferrer\">random package</a> in C++11 too, which offers better and more varieties of implementations than rand().</p>\n"
},
{
"answer_id": 24628873,
"author": "user3503711",
"author_id": 3503711,
"author_profile": "https://Stackoverflow.com/users/3503711",
"pm_score": 2,
"selected": false,
"text": "<p>This is not the code, but this logic may help you.</p>\n<pre><code>static double rnd(void)\n{\n return (1.0 / (RAND_MAX + 1.0) * ((double)(rand())));\n}\n\nstatic void InitBetterRnd(unsigned int seed)\n{\n register int i;\n srand(seed);\n for(i = 0; i < POOLSIZE; i++)\n {\n pool[i] = rnd();\n }\n}\n\n // This function returns a number between 0 and 1\n static double rnd0_1(void)\n {\n static int i = POOLSIZE - 1;\n double r;\n\n i = (int)(POOLSIZE*pool[i]);\n r = pool[i];\n pool[i] = rnd();\n return (r);\n}\n</code></pre>\n"
},
{
"answer_id": 30738381,
"author": "benf",
"author_id": 1669250,
"author_profile": "https://Stackoverflow.com/users/1669250",
"pm_score": 2,
"selected": false,
"text": "<p>This should provide a uniform distribution over the range <code>[low, high)</code> without using floats, as long as the overall range is less than RAND_MAX.</p>\n\n<pre><code>uint32_t rand_range_low(uint32_t low, uint32_t high)\n{\n uint32_t val;\n // only for 0 < range <= RAND_MAX\n assert(low < high);\n assert(high - low <= RAND_MAX);\n\n uint32_t range = high-low;\n uint32_t scale = RAND_MAX/range;\n do {\n val = rand();\n } while (val >= scale * range); // since scale is truncated, pick a new val until it's lower than scale*range\n return val/scale + low;\n}\n</code></pre>\n\n<p>and for values greater than RAND_MAX you want something like</p>\n\n<pre><code>uint32_t rand_range(uint32_t low, uint32_t high)\n{\n assert(high>low);\n uint32_t val;\n uint32_t range = high-low;\n if (range < RAND_MAX)\n return rand_range_low(low, high);\n uint32_t scale = range/RAND_MAX;\n do {\n val = rand() + rand_range(0, scale) * RAND_MAX; // scale the initial range in RAND_MAX steps, then add an offset to get a uniform interval\n } while (val >= range);\n return val + low;\n}\n</code></pre>\n\n<p>This is roughly how std::uniform_int_distribution does things.</p>\n"
},
{
"answer_id": 34316875,
"author": "Alberto M",
"author_id": 2453661,
"author_profile": "https://Stackoverflow.com/users/2453661",
"pm_score": 4,
"selected": false,
"text": "<p>I'd like to complement <a href=\"https://stackoverflow.com/questions/288739/generate-random-numbers-uniformly-over-an-entire-range/20136256#20136256\">Shoe's</a> and <a href=\"https://stackoverflow.com/questions/288739/generate-random-numbers-uniformly-over-an-entire-range/288869#288869\">peterchen's excellent answers</a> with a short overview of the state of the art in 2015:</p>\n<h1>Some good choices</h1>\n<h2><code>randutils</code></h2>\n<p>The <code>randutils</code> library <a href=\"http://www.pcg-random.org/posts/ease-of-use-without-loss-of-power.html\" rel=\"nofollow noreferrer\">(presentation)</a> is an interesting novelty, offering a simple interface and (declared) robust random capabilities. It has the disadvantages that it adds a dependence on your project and, being new, it has not been extensively tested. Anyway, being free (<a href=\"https://en.wikipedia.org/wiki/MIT_License\" rel=\"nofollow noreferrer\">MIT License</a>) and header-only, I think it's worth a try.</p>\n<p>Minimal sample: a die roll</p>\n<pre><code>#include <iostream>\n#include "randutils.hpp"\nint main() {\n randutils::mt19937_rng rng;\n std::cout << rng.uniform(1,6) << "\\n";\n}\n</code></pre>\n<p>Even if one is not interested in the library, <a href=\"http://www.pcg-random.org/\" rel=\"nofollow noreferrer\">the website</a> provides many interesting articles about the theme of random number generation in general and the C++ library in particular.</p>\n<h2>Boost.Random</h2>\n<p><code>Boost.Random</code> <a href=\"http://www.boost.org/doc/libs/1_59_0/doc/html/boost_random.html\" rel=\"nofollow noreferrer\">(documentation)</a> is the library which inspired <a href=\"https://en.wikipedia.org/wiki/C%2B%2B11\" rel=\"nofollow noreferrer\">C++11</a>'s <code><random></code>, with whom it shares much of the interface. While theoretically also being an external dependency, <a href=\"https://en.wikipedia.org/wiki/Boost_%28C%2B%2B_libraries%29\" rel=\"nofollow noreferrer\">Boost</a> has by now a status of "quasi-standard" library, and its <code>Random</code> module could be regarded as the classical choice for good-quality random number generation. It features two advantages with respect to the C++11 solution:</p>\n<ul>\n<li>it is more portable, just needing compiler support for <a href=\"https://en.wikipedia.org/wiki/C%2B%2B03\" rel=\"nofollow noreferrer\">C++03</a></li>\n<li>its <code>random_device</code> uses system-specific methods to offer seeding of good quality</li>\n</ul>\n<p>The only small flaw is that the module offering <code>random_device</code> is not header-only, one has to compile and link <code>boost_random</code>.</p>\n<p>Minimal sample: a die roll</p>\n<pre><code>#include <iostream>\n#include <boost/random.hpp>\n#include <boost/nondet_random.hpp>\n\nint main() {\n boost::random::random_device rand_dev;\n boost::random::mt19937 generator(rand_dev());\n boost::random::uniform_int_distribution<> distr(1, 6);\n\n std::cout << distr(generator) << '\\n';\n}\n</code></pre>\n<p>While the minimal sample does its work well, real programs should use a pair of improvements:</p>\n<ul>\n<li>make <code>mt19937</code> a <code>thread_local</code>: the generator is quite plump (more than 2 KB) and is better not allocated on the stack</li>\n<li>seed <code>mt19937</code> with more than one integer: the <a href=\"https://en.wikipedia.org/wiki/Mersenne_Twister\" rel=\"nofollow noreferrer\">Mersenne Twister</a> has a big state and can take benefit of more entropy during initialization</li>\n</ul>\n<h1>Some not-so-good choices</h1>\n<h2>The C++11 library</h2>\n<p>While being the most idiomatic solution, the <code><random></code> library does not offer much in exchange for the complexity of its interface even for the basic needs. The flaw is in <code>std::random_device</code>: the Standard does not mandate any minimal quality for its output (as long as <code>entropy()</code> returns <code>0</code>) and, as of 2015, <a href=\"https://en.wikipedia.org/wiki/MinGW\" rel=\"nofollow noreferrer\">MinGW</a> (not the most used compiler, but hardly an esoteric choice) will always print <code>4</code> on the minimal sample.</p>\n<p>Minimal sample: a die roll</p>\n<pre><code>#include <iostream>\n#include <random>\n\nint main() {\n std::random_device rand_dev;\n std::mt19937 generator(rand_dev());\n std::uniform_int_distribution<int> distr(1, 6);\n\n std::cout << distr(generator) << '\\n';\n}\n</code></pre>\n<p>If the implementation is not rotten, this solution should be equivalent to the Boost one, and the same suggestions apply.</p>\n<h2><a href=\"https://en.wikipedia.org/wiki/Godot_(game_engine)\" rel=\"nofollow noreferrer\">Godot</a>'s solution</h2>\n<p>Minimal sample: a die roll</p>\n<pre><code>#include <iostream>\n#include <random>\n\nint main() {\n std::cout << std::randint(1,6);\n}\n</code></pre>\n<p>This is a simple, effective and neat solution. The only defect is it will take a while to compile β about two years, providing <a href=\"https://en.wikipedia.org/wiki/C%2B%2B17\" rel=\"nofollow noreferrer\">C++17</a> is released on time and the experimental <code>randint</code> function is approved into the new Standard. Maybe by that time also the guarantees on the seeding quality will improve.</p>\n<h2>The <a href=\"https://en.wikipedia.org/wiki/Worse_is_better\" rel=\"nofollow noreferrer\">worse-is-better</a> solution</h2>\n<p>Minimal sample: a die roll</p>\n<pre><code>#include <cstdlib>\n#include <ctime>\n#include <iostream>\n\nint main() {\n std::srand(std::time(nullptr));\n std::cout << (std::rand() % 6 + 1);\n}\n</code></pre>\n<p>The old C solution is considered harmful, and for good reasons (see the other answers here or <a href=\"http://cpp.indi.frih.net/blog/2014/12/the-bell-has-tolled-for-rand/\" rel=\"nofollow noreferrer\">this detailed analysis</a>). Still, it has its advantages: is is simple, portable, fast and honest, in the sense it is known that the random numbers one gets are hardly decent, and therefore one is not tempted to use them for serious purposes.</p>\n<h2>The accounting troll solution</h2>\n<p>Minimal sample: a die roll</p>\n<pre><code>#include <iostream>\n\nint main() {\n std::cout << 9; // http://dilbert.com/strip/2001-10-25\n}\n</code></pre>\n<p>While 9 is a somewhat unusual outcome for a regular die roll, one has to admire the excellent combination of good qualities in this solution, which manages to be the fastest, simplest, most cache-friendly and most portable one. By substituting 9 with 4, one gets a perfect generator for any kind of <a href=\"https://en.wikipedia.org/wiki/Dice_notation#History\" rel=\"nofollow noreferrer\"><em>Dungeons & Dragons</em> die</a>, while still avoiding the symbol-laden values 1, 2 and 3. The only small flaw is that, because of the bad temper of <em><a href=\"https://en.wikipedia.org/wiki/Dilbert\" rel=\"nofollow noreferrer\">Dilbert</a></em>'s accounting trolls, this program actually engenders undefined behavior.</p>\n"
},
{
"answer_id": 56586409,
"author": "Michael Haephrati",
"author_id": 1592639,
"author_profile": "https://Stackoverflow.com/users/1592639",
"pm_score": -1,
"selected": false,
"text": "<p>Of course, the following code won't give you random numbers, but pseudo random numbers.</p>\n<p>Use the following code</p>\n<pre><code>#define QUICK_RAND(m,n) m + ( std::rand() % ( (n) - (m) + 1 ) )\n</code></pre>\n<p>For example:</p>\n<pre><code>int myRand = QUICK_RAND(10, 20);\n</code></pre>\n<p>You must call</p>\n<pre><code>srand(time(0)); // Initialize random number generator.\n</code></pre>\n<p>Otherwise the numbers won't be near random.</p>\n"
},
{
"answer_id": 61350542,
"author": "Ryan",
"author_id": 2266345,
"author_profile": "https://Stackoverflow.com/users/2266345",
"pm_score": 0,
"selected": false,
"text": "<p>This is the solution I came up with:</p>\n\n<pre><code>#include \"<stdlib.h>\"\n\nint32_t RandomRange(int32_t min, int32_t max) {\n return (rand() * (max - min + 1) / (RAND_MAX + 1)) + min;\n}\n</code></pre>\n\n<p>This is a bucket solution, conceptually similar to the solutions that use <code>rand() / RAND_MAX</code> to get a floating point range between 0-1 and then round that into a bucket. However, it uses purely integer math, and takes advantage of integer division flooring to round down the value to the nearest bucket.</p>\n\n<p>It makes a few assumptions. First, it assumes that <code>RAND_MAX * (max - min + 1)</code> will always fit within an <code>int32_t</code>. If <code>RAND_MAX</code> is 32767 and 32 bit int calculations are used, the the maximum range you can have is 32767. If your implementation has a much larger RAND_MAX, you can overcome this by using a larger integer (like <code>int64_t</code>) for the calculation. Secondly, if <code>int64_t</code> is used but <code>RAND_MAX</code> is still 32767, at ranges greater than <code>RAND_MAX</code> you will start to get \"holes\" in the possible output numbers. This is probably the biggest issue with any solution derived from scaling <code>rand()</code>.</p>\n\n<p>Testing over a huge number of iterations nevertheless shows this method to be very uniform for small ranges. However, it is possible (and likely) that mathematically this has some small bias and possibly develops issues when the range approaches <code>RAND_MAX</code>. Test it for yourself and decide if it meets your needs.</p>\n"
},
{
"answer_id": 70630169,
"author": "heothesennoc",
"author_id": 12087117,
"author_profile": "https://Stackoverflow.com/users/12087117",
"pm_score": 2,
"selected": false,
"text": "<p>Using a <a href=\"https://en.wikipedia.org/wiki/Mersenne_Twister\" rel=\"nofollow noreferrer\">Mersenne Twister</a> engine (C++11):</p>\n<pre><code>#include <random>\n\n// Returns a random integer within the range [min, max]\nint generateRandomInt(const int min, const int max) {\n static bool is_seeded = false;\n static std::mt19937 generator;\n\n // Seed once\n if (!is_seeded) {\n std::random_device rd;\n generator.seed(rd());\n is_seeded = true;\n }\n\n // Use a Mersenne Twister engine to pick a random number\n // within the given range\n std::uniform_int_distribution<int> distribution(min, max);\n return distribution(generator);\n}\n</code></pre>\n"
},
{
"answer_id": 74125371,
"author": "gatopeich",
"author_id": 501336,
"author_profile": "https://Stackoverflow.com/users/501336",
"pm_score": 0,
"selected": false,
"text": "<p>Minimal implementation with C++11:</p>\n<pre><code>#include <random>\n\nint randrange (int min, int max) {\n static std::random_device rd; // Static in case init is costly\n return std::uniform_int_distribution {min, max} (rd);\n}\n</code></pre>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33411/"
] |
I need to generate random numbers within a specified interval, [max;min].
Also, the random numbers should be uniformly distributed over the interval, not located to a particular point.
Currenly I am generating as:
```
for(int i=0; i<6; i++)
{
DWORD random = rand()%(max-min+1) + min;
}
```
From my tests, random numbers are generated around one point only.
```
Example
min = 3604607;
max = 7654607;
```
Random numbers generated:
```
3631594
3609293
3630000
3628441
3636376
3621404
```
From answers below: OK, RAND\_MAX is 32767. I am on C++ Windows platform. Is there any other method to generate random numbers with a uniform distribution?
|
Why `rand` is a bad idea
------------------------
Most of the answers you got here make use of the `rand` function and the modulus operator. That method [may not generate numbers uniformly](http://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful) (it depends on the range and the value of `RAND_MAX`), and is therefore discouraged.
C++11 and generation over a range
---------------------------------
With C++11 multiple other options have risen. One of which fits your requirements, for generating a random number in a range, pretty nicely: [`std::uniform_int_distribution`](http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution). Here's an example:
```cpp
#include <iostream>
#include <random>
int main()
{
const int range_from = 0;
const int range_to = 1000;
std::random_device rand_dev;
std::mt19937 generator(rand_dev());
std::uniform_int_distribution<int> distr(range_from, range_to);
std::cout << distr(generator) << '\n';
}
```
[Try it online on Godbolt](https://godbolt.org/z/xq77YGjqc)
And [here](http://coliru.stacked-crooked.com/a/c5b94870fdcd13f2)'s the running example.
Template function may help some:
```cpp
template<typename T>
T random(T range_from, T range_to) {
std::random_device rand_dev;
std::mt19937 generator(rand_dev());
std::uniform_int_distribution<T> distr(range_from, range_to);
return distr(generator);
}
```
### Other random generators
The [`<random>` header](http://en.cppreference.com/w/cpp/numeric/random) offers innumerable other random number generators with different kind of distributions including Bernoulli, Poisson and normal.
### How can I shuffle a container?
The standard provides [`std::shuffle`](http://en.cppreference.com/w/cpp/algorithm/random_shuffle), which can be used as follows:
```cpp
#include <iostream>
#include <random>
#include <vector>
int main()
{
std::vector<int> vec = {4, 8, 15, 16, 23, 42};
std::random_device random_dev;
std::mt19937 generator(random_dev());
std::shuffle(vec.begin(), vec.end(), generator);
std::for_each(vec.begin(), vec.end(), [](auto i){std::cout << i << '\n';});
}
```
[Try it online on Godbolt](https://godbolt.org/z/rxrrrche5)
The algorithm will reorder the elements randomly, with a linear complexity.
Boost.Random
------------
Another alternative, in case you don't have access to a C++11+ compiler, is to use [Boost.Random](http://www.boost.org/doc/libs/1_55_0/doc/html/boost_random.html). Its interface is very similar to the C++11 one.
|
288,752 |
<p>I have this strange issue with my web app. You see, I'm using jQuery with the Forms API and doing $('#MyForm').ajaxSubmit(api parms and callback function goes here).</p>
<p>Randomly when I do this, however, and only on Firefox, the page load icon starts spinning, the page load progress bar runs in the status bar, and the stop button goes red -- but it has already posted the form and brought back a result. If I refresh the page and keep trying to do this, it randomly exhibits the problem, but not consistently.</p>
<p>This problem occurred on FF2 on Windows 2008 Server and FF3 on Ubuntu 8.04. The problem is not seen with IE6, IE7, Opera (latest stable, Nov 2008), or Safari (latest stable, Nov 2008).</p>
<p>Is this just a known bug in FF with AJAX, or is there something I can do with jQuery to stop the page load issue?</p>
<p>EDIT: This <em>might</em> have something to do with TinyMCE. I cannot confirm this 100%, but when I use jQuery to bring back a form with a TinyMCE control on it, the problem seems to exhibit itself more often. I tried doing it with a form that does not have a TinyMCE control on it, several times, and couldn't get the problem to occur. Again, that's nothing conclusive, but might be a factor.</p>
<p>EDIT: Okay, I just commented out the TinyMCE stuff and I can confirm that the problem goes away then. If I bring the TinyMCE control back, the problem randomly occurs.</p>
|
[
{
"answer_id": 288753,
"author": "Jason Coco",
"author_id": 34218,
"author_profile": "https://Stackoverflow.com/users/34218",
"pm_score": 2,
"selected": false,
"text": "<p>If you want numbers to be uniformly distributed over the range, you should break your range up into a number of equal sections that represent the number of points you need. Then get a random number with a min/max for each section.</p>\n\n<p>As another note, you should probably not use <code>rand()</code> as it's not very good at actually generating random numbers. I don't know what platform you're running on, but there is probably a better function you can call like <code>random()</code>.</p>\n"
},
{
"answer_id": 288760,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 2,
"selected": false,
"text": "<p>Check what <code>RAND_MAX</code> is on your system -- I'm guessing it is only 16 bits, and your range is too big for it.</p>\n\n<p>Beyond that see this discussion on: <a href=\"http://members.cox.net/srice1/random/genrange.html\" rel=\"nofollow noreferrer\">Generating Random Integers within a Desired Range</a> and the notes on using (or not) the <a href=\"http://members.cox.net/srice1/random/crandom.html\" rel=\"nofollow noreferrer\">C rand() function</a>.</p>\n"
},
{
"answer_id": 288762,
"author": "SoapBox",
"author_id": 36384,
"author_profile": "https://Stackoverflow.com/users/36384",
"pm_score": 3,
"selected": false,
"text": "<p>If you are concerned about randomness and not about speed, you should use a secure random number generation method. There are several ways to do this... The easiest one being to use <a href=\"http://www.openssl.org/\" rel=\"nofollow noreferrer\">OpenSSL's</a> <a href=\"http://www.openssl.org/docs/crypto/rand.html#\" rel=\"nofollow noreferrer\">Random Number Generator</a>.</p>\n\n<p>You can also write your own using an encryption algorithm (like <a href=\"http://en.wikipedia.org/wiki/Advanced_Encryption_Standard\" rel=\"nofollow noreferrer\">AES</a>). By picking a seed and an <a href=\"http://en.wikipedia.org/wiki/Initialization_vector\" rel=\"nofollow noreferrer\">IV</a> and then continuously re-encrypting the output of the encryption function. Using OpenSSL is easier, but less manly.</p>\n"
},
{
"answer_id": 288769,
"author": "abelenky",
"author_id": 34824,
"author_profile": "https://Stackoverflow.com/users/34824",
"pm_score": 3,
"selected": false,
"text": "<p>You should look at <code>RAND_MAX</code> for your particular compiler/environment.\nI think you would see these results if <code>rand()</code> is producing a random 16-bit number. (you seem to be assuming it will be a 32-bit number).</p>\n\n<p>I can't promise this is the answer, but please post your value of <code>RAND_MAX</code>, and a little more detail on your environment.</p>\n"
},
{
"answer_id": 288777,
"author": "Kluge",
"author_id": 8752,
"author_profile": "https://Stackoverflow.com/users/8752",
"pm_score": 0,
"selected": false,
"text": "<p>By their nature, a small sample of random numbers doesn't have to be uniformly distributed. They're random, after all. I agree that if a random number generator is generating numbers that consistently appear to be grouped, then there is probably something wrong with it.</p>\n<p>But keep in mind that randomness isn't necessarily uniform.</p>\n"
},
{
"answer_id": 288786,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 3,
"selected": false,
"text": "<p>If <code>RAND_MAX</code> is 32767, you can double the number of bits easily.</p>\n\n<pre><code>int BigRand()\n{\n assert(INT_MAX/(RAND_MAX+1) > RAND_MAX);\n return rand() * (RAND_MAX+1) + rand();\n}\n</code></pre>\n"
},
{
"answer_id": 288816,
"author": "anand",
"author_id": 33411,
"author_profile": "https://Stackoverflow.com/users/33411",
"pm_score": -1,
"selected": false,
"text": "<p>I just found this on the Internet. This should work:</p>\n\n<pre><code>DWORD random = ((min) + rand()/(RAND_MAX + 1.0) * ((max) - (min) + 1));\n</code></pre>\n"
},
{
"answer_id": 288844,
"author": "calandoa",
"author_id": 26074,
"author_profile": "https://Stackoverflow.com/users/26074",
"pm_score": 0,
"selected": false,
"text": "<p>The solution given by <a href=\"http://linux.die.net/man/3/rand\" rel=\"nofollow noreferrer\">man 3 rand</a> for a number between 1 and 10 inclusive is:</p>\n\n<pre><code>j = 1 + (int) (10.0 * (rand() / (RAND_MAX + 1.0)));\n</code></pre>\n\n<p>In your case, it would be:</p>\n\n<pre><code>j = min + (int) ((max-min+1) * (rand() / (RAND_MAX + 1.0)));\n</code></pre>\n\n<p>Of course, this is not perfect randomness or uniformity as some other messages are pointing out, but this is enough for most cases.</p>\n"
},
{
"answer_id": 288869,
"author": "peterchen",
"author_id": 31317,
"author_profile": "https://Stackoverflow.com/users/31317",
"pm_score": 6,
"selected": false,
"text": "<p><strong>Warning: Do not use <code>rand()</code> for statistics, simulation, cryptography or anything serious.</strong></p>\n<p>It's good enough to make numbers <em>look</em> random for a typical human in a hurry, no more.</p>\n<p>See <a href=\"https://stackoverflow.com/a/20136256/4513656\">Jefffrey's reply</a> for better options, or <a href=\"https://stackoverflow.com/a/2572373/59087\">this answer</a> for crypto-secure random numbers.</p>\n<hr />\n<p>Generally, the high bits show a better distribution than the low bits, so the recommended way to generate random numbers of a range for simple purposes is:</p>\n<pre><code>((double) rand() / (RAND_MAX+1)) * (max-min+1) + min\n</code></pre>\n<p><strong>Note</strong>: make sure RAND_MAX+1 does not overflow (thanks Demi)!</p>\n<p>The division generates a random number in the interval [0, 1); "stretch" this to the required range. Only when max-min+1 gets close to RAND_MAX you need a "BigRand()" function like posted by Mark Ransom.</p>\n<p>This also avoids some slicing problems due to the modulo, which can worsen your numbers even more.</p>\n<hr />\n<p>The built-in random number generator isn't guaranteed to have a the quality required for statistical simulations. It is OK for numbers to "look random" to a human, but for a serious application, you should take something better - or at least check its properties (uniform distribution is usually good, but values tend to correlate, and the sequence is deterministic). Knuth has an excellent (if hard-to-read) treatise on random number generators, and I recently found <a href=\"http://en.wikipedia.org/wiki/Linear_feedback_shift_register\" rel=\"nofollow noreferrer\">LFSR</a> to be excellent and darn simple to implement, given its properties are OK for you.</p>\n"
},
{
"answer_id": 288929,
"author": "Jeff Thomas",
"author_id": 1561,
"author_profile": "https://Stackoverflow.com/users/1561",
"pm_score": 3,
"selected": false,
"text": "<p>If you are able to, use <a href=\"http://en.wikipedia.org/wiki/Boost_C++_Libraries\" rel=\"nofollow noreferrer\">Boost</a>. I have had good luck with their <a href=\"http://www.boost.org/doc/libs/1_37_0/libs/random/index.html\" rel=\"nofollow noreferrer\">random library</a>.</p>\n\n<p><code>uniform_int</code> should do what you want.</p>\n"
},
{
"answer_id": 20136256,
"author": "Shoe",
"author_id": 493122,
"author_profile": "https://Stackoverflow.com/users/493122",
"pm_score": 9,
"selected": true,
"text": "<h2>Why <code>rand</code> is a bad idea</h2>\n<p>Most of the answers you got here make use of the <code>rand</code> function and the modulus operator. That method <a href=\"http://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful\" rel=\"noreferrer\">may not generate numbers uniformly</a> (it depends on the range and the value of <code>RAND_MAX</code>), and is therefore discouraged.</p>\n<h2>C++11 and generation over a range</h2>\n<p>With C++11 multiple other options have risen. One of which fits your requirements, for generating a random number in a range, pretty nicely: <a href=\"http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution\" rel=\"noreferrer\"><code>std::uniform_int_distribution</code></a>. Here's an example:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include <iostream>\n#include <random>\nint main()\n{ \n const int range_from = 0;\n const int range_to = 1000;\n std::random_device rand_dev;\n std::mt19937 generator(rand_dev());\n std::uniform_int_distribution<int> distr(range_from, range_to);\n\n std::cout << distr(generator) << '\\n';\n}\n</code></pre>\n<p><sub><a href=\"https://godbolt.org/z/xq77YGjqc\" rel=\"noreferrer\">Try it online on Godbolt</a></sub></p>\n<p>And <a href=\"http://coliru.stacked-crooked.com/a/c5b94870fdcd13f2\" rel=\"noreferrer\">here</a>'s the running example.</p>\n<p>Template function may help some:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>template<typename T>\nT random(T range_from, T range_to) {\n std::random_device rand_dev;\n std::mt19937 generator(rand_dev());\n std::uniform_int_distribution<T> distr(range_from, range_to);\n return distr(generator);\n}\n</code></pre>\n<h3>Other random generators</h3>\n<p>The <a href=\"http://en.cppreference.com/w/cpp/numeric/random\" rel=\"noreferrer\"><code><random></code> header</a> offers innumerable other random number generators with different kind of distributions including Bernoulli, Poisson and normal.</p>\n<h3>How can I shuffle a container?</h3>\n<p>The standard provides <a href=\"http://en.cppreference.com/w/cpp/algorithm/random_shuffle\" rel=\"noreferrer\"><code>std::shuffle</code></a>, which can be used as follows:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include <iostream>\n#include <random>\n#include <vector>\nint main()\n{ \n std::vector<int> vec = {4, 8, 15, 16, 23, 42};\n \n std::random_device random_dev;\n std::mt19937 generator(random_dev());\n \n std::shuffle(vec.begin(), vec.end(), generator);\n std::for_each(vec.begin(), vec.end(), [](auto i){std::cout << i << '\\n';});\n}\n</code></pre>\n<p><sub><a href=\"https://godbolt.org/z/rxrrrche5\" rel=\"noreferrer\">Try it online on Godbolt</a></sub></p>\n<p>The algorithm will reorder the elements randomly, with a linear complexity.</p>\n<h2>Boost.Random</h2>\n<p>Another alternative, in case you don't have access to a C++11+ compiler, is to use <a href=\"http://www.boost.org/doc/libs/1_55_0/doc/html/boost_random.html\" rel=\"noreferrer\">Boost.Random</a>. Its interface is very similar to the C++11 one.</p>\n"
},
{
"answer_id": 21478635,
"author": "Ritualmaster",
"author_id": 3256548,
"author_profile": "https://Stackoverflow.com/users/3256548",
"pm_score": 0,
"selected": false,
"text": "<h3>A solution</h3>\n<p><code>((double) rand() / (RAND_MAX+1)) * (max-min+1) + min</code></p>\n<p><strong>Warning</strong>: Don't forget due to stretching and possible precision errors (even if RAND_MAX were large enough), you'll only be able to generate evenly distributed "bins" and not all numbers in [min,max].</p>\n<hr />\n<h3>A solution using Bigrand</h3>\n<p><strong>Warning</strong>: Note that this doubles the bits, but still won't be able to generate all numbers in your range in general, i.e., it is not necessarily true that BigRand() will generate all numbers between in its range.</p>\n<hr />\n<p><strong>Information</strong>: Your approach (modulo) is "fine" as long as the range of rand() exceeds your interval range and rand() is "uniform". The error for at most the first max - min numbers is 1/(RAND_MAX +1).</p>\n<p>Also, I suggest to switch to the new <a href=\"http://www.cplusplus.com/reference/random/\" rel=\"nofollow noreferrer\">random package</a> in C++11 too, which offers better and more varieties of implementations than rand().</p>\n"
},
{
"answer_id": 24628873,
"author": "user3503711",
"author_id": 3503711,
"author_profile": "https://Stackoverflow.com/users/3503711",
"pm_score": 2,
"selected": false,
"text": "<p>This is not the code, but this logic may help you.</p>\n<pre><code>static double rnd(void)\n{\n return (1.0 / (RAND_MAX + 1.0) * ((double)(rand())));\n}\n\nstatic void InitBetterRnd(unsigned int seed)\n{\n register int i;\n srand(seed);\n for(i = 0; i < POOLSIZE; i++)\n {\n pool[i] = rnd();\n }\n}\n\n // This function returns a number between 0 and 1\n static double rnd0_1(void)\n {\n static int i = POOLSIZE - 1;\n double r;\n\n i = (int)(POOLSIZE*pool[i]);\n r = pool[i];\n pool[i] = rnd();\n return (r);\n}\n</code></pre>\n"
},
{
"answer_id": 30738381,
"author": "benf",
"author_id": 1669250,
"author_profile": "https://Stackoverflow.com/users/1669250",
"pm_score": 2,
"selected": false,
"text": "<p>This should provide a uniform distribution over the range <code>[low, high)</code> without using floats, as long as the overall range is less than RAND_MAX.</p>\n\n<pre><code>uint32_t rand_range_low(uint32_t low, uint32_t high)\n{\n uint32_t val;\n // only for 0 < range <= RAND_MAX\n assert(low < high);\n assert(high - low <= RAND_MAX);\n\n uint32_t range = high-low;\n uint32_t scale = RAND_MAX/range;\n do {\n val = rand();\n } while (val >= scale * range); // since scale is truncated, pick a new val until it's lower than scale*range\n return val/scale + low;\n}\n</code></pre>\n\n<p>and for values greater than RAND_MAX you want something like</p>\n\n<pre><code>uint32_t rand_range(uint32_t low, uint32_t high)\n{\n assert(high>low);\n uint32_t val;\n uint32_t range = high-low;\n if (range < RAND_MAX)\n return rand_range_low(low, high);\n uint32_t scale = range/RAND_MAX;\n do {\n val = rand() + rand_range(0, scale) * RAND_MAX; // scale the initial range in RAND_MAX steps, then add an offset to get a uniform interval\n } while (val >= range);\n return val + low;\n}\n</code></pre>\n\n<p>This is roughly how std::uniform_int_distribution does things.</p>\n"
},
{
"answer_id": 34316875,
"author": "Alberto M",
"author_id": 2453661,
"author_profile": "https://Stackoverflow.com/users/2453661",
"pm_score": 4,
"selected": false,
"text": "<p>I'd like to complement <a href=\"https://stackoverflow.com/questions/288739/generate-random-numbers-uniformly-over-an-entire-range/20136256#20136256\">Shoe's</a> and <a href=\"https://stackoverflow.com/questions/288739/generate-random-numbers-uniformly-over-an-entire-range/288869#288869\">peterchen's excellent answers</a> with a short overview of the state of the art in 2015:</p>\n<h1>Some good choices</h1>\n<h2><code>randutils</code></h2>\n<p>The <code>randutils</code> library <a href=\"http://www.pcg-random.org/posts/ease-of-use-without-loss-of-power.html\" rel=\"nofollow noreferrer\">(presentation)</a> is an interesting novelty, offering a simple interface and (declared) robust random capabilities. It has the disadvantages that it adds a dependence on your project and, being new, it has not been extensively tested. Anyway, being free (<a href=\"https://en.wikipedia.org/wiki/MIT_License\" rel=\"nofollow noreferrer\">MIT License</a>) and header-only, I think it's worth a try.</p>\n<p>Minimal sample: a die roll</p>\n<pre><code>#include <iostream>\n#include "randutils.hpp"\nint main() {\n randutils::mt19937_rng rng;\n std::cout << rng.uniform(1,6) << "\\n";\n}\n</code></pre>\n<p>Even if one is not interested in the library, <a href=\"http://www.pcg-random.org/\" rel=\"nofollow noreferrer\">the website</a> provides many interesting articles about the theme of random number generation in general and the C++ library in particular.</p>\n<h2>Boost.Random</h2>\n<p><code>Boost.Random</code> <a href=\"http://www.boost.org/doc/libs/1_59_0/doc/html/boost_random.html\" rel=\"nofollow noreferrer\">(documentation)</a> is the library which inspired <a href=\"https://en.wikipedia.org/wiki/C%2B%2B11\" rel=\"nofollow noreferrer\">C++11</a>'s <code><random></code>, with whom it shares much of the interface. While theoretically also being an external dependency, <a href=\"https://en.wikipedia.org/wiki/Boost_%28C%2B%2B_libraries%29\" rel=\"nofollow noreferrer\">Boost</a> has by now a status of "quasi-standard" library, and its <code>Random</code> module could be regarded as the classical choice for good-quality random number generation. It features two advantages with respect to the C++11 solution:</p>\n<ul>\n<li>it is more portable, just needing compiler support for <a href=\"https://en.wikipedia.org/wiki/C%2B%2B03\" rel=\"nofollow noreferrer\">C++03</a></li>\n<li>its <code>random_device</code> uses system-specific methods to offer seeding of good quality</li>\n</ul>\n<p>The only small flaw is that the module offering <code>random_device</code> is not header-only, one has to compile and link <code>boost_random</code>.</p>\n<p>Minimal sample: a die roll</p>\n<pre><code>#include <iostream>\n#include <boost/random.hpp>\n#include <boost/nondet_random.hpp>\n\nint main() {\n boost::random::random_device rand_dev;\n boost::random::mt19937 generator(rand_dev());\n boost::random::uniform_int_distribution<> distr(1, 6);\n\n std::cout << distr(generator) << '\\n';\n}\n</code></pre>\n<p>While the minimal sample does its work well, real programs should use a pair of improvements:</p>\n<ul>\n<li>make <code>mt19937</code> a <code>thread_local</code>: the generator is quite plump (more than 2 KB) and is better not allocated on the stack</li>\n<li>seed <code>mt19937</code> with more than one integer: the <a href=\"https://en.wikipedia.org/wiki/Mersenne_Twister\" rel=\"nofollow noreferrer\">Mersenne Twister</a> has a big state and can take benefit of more entropy during initialization</li>\n</ul>\n<h1>Some not-so-good choices</h1>\n<h2>The C++11 library</h2>\n<p>While being the most idiomatic solution, the <code><random></code> library does not offer much in exchange for the complexity of its interface even for the basic needs. The flaw is in <code>std::random_device</code>: the Standard does not mandate any minimal quality for its output (as long as <code>entropy()</code> returns <code>0</code>) and, as of 2015, <a href=\"https://en.wikipedia.org/wiki/MinGW\" rel=\"nofollow noreferrer\">MinGW</a> (not the most used compiler, but hardly an esoteric choice) will always print <code>4</code> on the minimal sample.</p>\n<p>Minimal sample: a die roll</p>\n<pre><code>#include <iostream>\n#include <random>\n\nint main() {\n std::random_device rand_dev;\n std::mt19937 generator(rand_dev());\n std::uniform_int_distribution<int> distr(1, 6);\n\n std::cout << distr(generator) << '\\n';\n}\n</code></pre>\n<p>If the implementation is not rotten, this solution should be equivalent to the Boost one, and the same suggestions apply.</p>\n<h2><a href=\"https://en.wikipedia.org/wiki/Godot_(game_engine)\" rel=\"nofollow noreferrer\">Godot</a>'s solution</h2>\n<p>Minimal sample: a die roll</p>\n<pre><code>#include <iostream>\n#include <random>\n\nint main() {\n std::cout << std::randint(1,6);\n}\n</code></pre>\n<p>This is a simple, effective and neat solution. The only defect is it will take a while to compile β about two years, providing <a href=\"https://en.wikipedia.org/wiki/C%2B%2B17\" rel=\"nofollow noreferrer\">C++17</a> is released on time and the experimental <code>randint</code> function is approved into the new Standard. Maybe by that time also the guarantees on the seeding quality will improve.</p>\n<h2>The <a href=\"https://en.wikipedia.org/wiki/Worse_is_better\" rel=\"nofollow noreferrer\">worse-is-better</a> solution</h2>\n<p>Minimal sample: a die roll</p>\n<pre><code>#include <cstdlib>\n#include <ctime>\n#include <iostream>\n\nint main() {\n std::srand(std::time(nullptr));\n std::cout << (std::rand() % 6 + 1);\n}\n</code></pre>\n<p>The old C solution is considered harmful, and for good reasons (see the other answers here or <a href=\"http://cpp.indi.frih.net/blog/2014/12/the-bell-has-tolled-for-rand/\" rel=\"nofollow noreferrer\">this detailed analysis</a>). Still, it has its advantages: is is simple, portable, fast and honest, in the sense it is known that the random numbers one gets are hardly decent, and therefore one is not tempted to use them for serious purposes.</p>\n<h2>The accounting troll solution</h2>\n<p>Minimal sample: a die roll</p>\n<pre><code>#include <iostream>\n\nint main() {\n std::cout << 9; // http://dilbert.com/strip/2001-10-25\n}\n</code></pre>\n<p>While 9 is a somewhat unusual outcome for a regular die roll, one has to admire the excellent combination of good qualities in this solution, which manages to be the fastest, simplest, most cache-friendly and most portable one. By substituting 9 with 4, one gets a perfect generator for any kind of <a href=\"https://en.wikipedia.org/wiki/Dice_notation#History\" rel=\"nofollow noreferrer\"><em>Dungeons & Dragons</em> die</a>, while still avoiding the symbol-laden values 1, 2 and 3. The only small flaw is that, because of the bad temper of <em><a href=\"https://en.wikipedia.org/wiki/Dilbert\" rel=\"nofollow noreferrer\">Dilbert</a></em>'s accounting trolls, this program actually engenders undefined behavior.</p>\n"
},
{
"answer_id": 56586409,
"author": "Michael Haephrati",
"author_id": 1592639,
"author_profile": "https://Stackoverflow.com/users/1592639",
"pm_score": -1,
"selected": false,
"text": "<p>Of course, the following code won't give you random numbers, but pseudo random numbers.</p>\n<p>Use the following code</p>\n<pre><code>#define QUICK_RAND(m,n) m + ( std::rand() % ( (n) - (m) + 1 ) )\n</code></pre>\n<p>For example:</p>\n<pre><code>int myRand = QUICK_RAND(10, 20);\n</code></pre>\n<p>You must call</p>\n<pre><code>srand(time(0)); // Initialize random number generator.\n</code></pre>\n<p>Otherwise the numbers won't be near random.</p>\n"
},
{
"answer_id": 61350542,
"author": "Ryan",
"author_id": 2266345,
"author_profile": "https://Stackoverflow.com/users/2266345",
"pm_score": 0,
"selected": false,
"text": "<p>This is the solution I came up with:</p>\n\n<pre><code>#include \"<stdlib.h>\"\n\nint32_t RandomRange(int32_t min, int32_t max) {\n return (rand() * (max - min + 1) / (RAND_MAX + 1)) + min;\n}\n</code></pre>\n\n<p>This is a bucket solution, conceptually similar to the solutions that use <code>rand() / RAND_MAX</code> to get a floating point range between 0-1 and then round that into a bucket. However, it uses purely integer math, and takes advantage of integer division flooring to round down the value to the nearest bucket.</p>\n\n<p>It makes a few assumptions. First, it assumes that <code>RAND_MAX * (max - min + 1)</code> will always fit within an <code>int32_t</code>. If <code>RAND_MAX</code> is 32767 and 32 bit int calculations are used, the the maximum range you can have is 32767. If your implementation has a much larger RAND_MAX, you can overcome this by using a larger integer (like <code>int64_t</code>) for the calculation. Secondly, if <code>int64_t</code> is used but <code>RAND_MAX</code> is still 32767, at ranges greater than <code>RAND_MAX</code> you will start to get \"holes\" in the possible output numbers. This is probably the biggest issue with any solution derived from scaling <code>rand()</code>.</p>\n\n<p>Testing over a huge number of iterations nevertheless shows this method to be very uniform for small ranges. However, it is possible (and likely) that mathematically this has some small bias and possibly develops issues when the range approaches <code>RAND_MAX</code>. Test it for yourself and decide if it meets your needs.</p>\n"
},
{
"answer_id": 70630169,
"author": "heothesennoc",
"author_id": 12087117,
"author_profile": "https://Stackoverflow.com/users/12087117",
"pm_score": 2,
"selected": false,
"text": "<p>Using a <a href=\"https://en.wikipedia.org/wiki/Mersenne_Twister\" rel=\"nofollow noreferrer\">Mersenne Twister</a> engine (C++11):</p>\n<pre><code>#include <random>\n\n// Returns a random integer within the range [min, max]\nint generateRandomInt(const int min, const int max) {\n static bool is_seeded = false;\n static std::mt19937 generator;\n\n // Seed once\n if (!is_seeded) {\n std::random_device rd;\n generator.seed(rd());\n is_seeded = true;\n }\n\n // Use a Mersenne Twister engine to pick a random number\n // within the given range\n std::uniform_int_distribution<int> distribution(min, max);\n return distribution(generator);\n}\n</code></pre>\n"
},
{
"answer_id": 74125371,
"author": "gatopeich",
"author_id": 501336,
"author_profile": "https://Stackoverflow.com/users/501336",
"pm_score": 0,
"selected": false,
"text": "<p>Minimal implementation with C++11:</p>\n<pre><code>#include <random>\n\nint randrange (int min, int max) {\n static std::random_device rd; // Static in case init is costly\n return std::uniform_int_distribution {min, max} (rd);\n}\n</code></pre>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/288752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have this strange issue with my web app. You see, I'm using jQuery with the Forms API and doing $('#MyForm').ajaxSubmit(api parms and callback function goes here).
Randomly when I do this, however, and only on Firefox, the page load icon starts spinning, the page load progress bar runs in the status bar, and the stop button goes red -- but it has already posted the form and brought back a result. If I refresh the page and keep trying to do this, it randomly exhibits the problem, but not consistently.
This problem occurred on FF2 on Windows 2008 Server and FF3 on Ubuntu 8.04. The problem is not seen with IE6, IE7, Opera (latest stable, Nov 2008), or Safari (latest stable, Nov 2008).
Is this just a known bug in FF with AJAX, or is there something I can do with jQuery to stop the page load issue?
EDIT: This *might* have something to do with TinyMCE. I cannot confirm this 100%, but when I use jQuery to bring back a form with a TinyMCE control on it, the problem seems to exhibit itself more often. I tried doing it with a form that does not have a TinyMCE control on it, several times, and couldn't get the problem to occur. Again, that's nothing conclusive, but might be a factor.
EDIT: Okay, I just commented out the TinyMCE stuff and I can confirm that the problem goes away then. If I bring the TinyMCE control back, the problem randomly occurs.
|
Why `rand` is a bad idea
------------------------
Most of the answers you got here make use of the `rand` function and the modulus operator. That method [may not generate numbers uniformly](http://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful) (it depends on the range and the value of `RAND_MAX`), and is therefore discouraged.
C++11 and generation over a range
---------------------------------
With C++11 multiple other options have risen. One of which fits your requirements, for generating a random number in a range, pretty nicely: [`std::uniform_int_distribution`](http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution). Here's an example:
```cpp
#include <iostream>
#include <random>
int main()
{
const int range_from = 0;
const int range_to = 1000;
std::random_device rand_dev;
std::mt19937 generator(rand_dev());
std::uniform_int_distribution<int> distr(range_from, range_to);
std::cout << distr(generator) << '\n';
}
```
[Try it online on Godbolt](https://godbolt.org/z/xq77YGjqc)
And [here](http://coliru.stacked-crooked.com/a/c5b94870fdcd13f2)'s the running example.
Template function may help some:
```cpp
template<typename T>
T random(T range_from, T range_to) {
std::random_device rand_dev;
std::mt19937 generator(rand_dev());
std::uniform_int_distribution<T> distr(range_from, range_to);
return distr(generator);
}
```
### Other random generators
The [`<random>` header](http://en.cppreference.com/w/cpp/numeric/random) offers innumerable other random number generators with different kind of distributions including Bernoulli, Poisson and normal.
### How can I shuffle a container?
The standard provides [`std::shuffle`](http://en.cppreference.com/w/cpp/algorithm/random_shuffle), which can be used as follows:
```cpp
#include <iostream>
#include <random>
#include <vector>
int main()
{
std::vector<int> vec = {4, 8, 15, 16, 23, 42};
std::random_device random_dev;
std::mt19937 generator(random_dev());
std::shuffle(vec.begin(), vec.end(), generator);
std::for_each(vec.begin(), vec.end(), [](auto i){std::cout << i << '\n';});
}
```
[Try it online on Godbolt](https://godbolt.org/z/rxrrrche5)
The algorithm will reorder the elements randomly, with a linear complexity.
Boost.Random
------------
Another alternative, in case you don't have access to a C++11+ compiler, is to use [Boost.Random](http://www.boost.org/doc/libs/1_55_0/doc/html/boost_random.html). Its interface is very similar to the C++11 one.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.