qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
214,441
|
<p>I would like to show a set of consecutive numbers in a UIPickerView component but have it wrap around like the seconds component of the Clock->Timer application. The only behavior I can enable looks like the hours component of the Timer application, where you can scroll in only one direction.</p>
|
[
{
"answer_id": 221955,
"author": "David",
"author_id": 28275,
"author_profile": "https://Stackoverflow.com/users/28275",
"pm_score": 5,
"selected": false,
"text": "return [rows objectAtIndex:(row % [rows count])];\n //we want the selection to always be in the SECOND set (so that it looks like it has stuff before and after)\nif (row < [rows count] || row >= (2 * [rows count]) ) {\n row = row % [rows count];\n row += [rows count];\n [pickerView selectRow:row inComponent:component animated:NO];\n}\n"
},
{
"answer_id": 367436,
"author": "squelart",
"author_id": 42690,
"author_profile": "https://Stackoverflow.com/users/42690",
"pm_score": 7,
"selected": true,
"text": "- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {\n // Near-infinite number of rows.\n return NSIntegerMax;\n}\n\n- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {\n // Row n is same as row (n modulo numberItems).\n return [NSString stringWithFormat:@\"%d\", row % numberItems];\n}\n\n- (void)viewDidLoad {\n [super viewDidLoad];\n\n self.pickerView = [[[UIPickerView alloc] initWithFrame:CGRectZero] autorelease];\n // ...set pickerView properties... Look at Apple's UICatalog sample code for a good example.\n // Set current row to a large value (adjusted to current value if needed).\n [pickerView selectRow:currentValue+100000 inComponent:0 animated:NO];\n [self.view addSubview:pickerView];\n}\n\n- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {\n NSInteger actualRow = row % numberItems;\n // ...\n}\n"
},
{
"answer_id": 30428669,
"author": "user2912794",
"author_id": 2912794,
"author_profile": "https://Stackoverflow.com/users/2912794",
"pm_score": 0,
"selected": false,
"text": "NSString *stdStepper;\n\n for (int j = 0; j<10; j++) {\n for(int i=0; i<24; i++)\n {\n stdStepper = [NSString stringWithFormat:@\"%d\", i];\n\n [_hoursArray addObject:stdStepper];\n\n }\n }\n [_hoursPickerView selectRow:120 inComponent:0 animated:NO];\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28275/"
] |
214,491
|
<p>I'm working with a JavaScript API where most of the functions are asynchronous. The API is the <a href="http://webkit.org/blog/126/webkit-does-html5-client-side-database-storage/" rel="noreferrer">WebKit JavaScript Database API</a> which is a binding to a subset of functionality to manipulate SQLite3 databases. I understand the design decision to make things async as to not block and provide a responsive user interface. In my situation I know that my usage of the async API calls will execute fast. Since this is the case I'd like to provide my developers a cleaner and easier to use wrapper API that forces synchronous calls.</p>
<p>Here's the async call</p>
<pre><code>db.executeSql(sqlStatement, function(result) {
// do something with result
});
</code></pre>
<p>And here's what I'd like to be able to do</p>
<pre><code>var result = dbWrapper.executeSql(sqlStatement);
// do something with result
</code></pre>
<p>Is there a design pattern/way to do this? A written or linked to code example is preferred. The target platform/broswer is Mobile Safari on the iPhone.</p>
<p>Thank you</p>
|
[
{
"answer_id": 214973,
"author": "johnstok",
"author_id": 27929,
"author_profile": "https://Stackoverflow.com/users/27929",
"pm_score": 1,
"selected": false,
"text": "callA(function(resultA) {\n callB(resultA, function(resultB) {\n callC(); //etc.\n });\n});\n callStack = [\n callA(),\n callB(),\n callC()\n];\n\ncallStack.execute();\n"
},
{
"answer_id": 2004054,
"author": "Mike Gleason jr Couturier",
"author_id": 193982,
"author_profile": "https://Stackoverflow.com/users/193982",
"pm_score": 2,
"selected": false,
"text": "function synch()\n{\n var done = false;\n var returnVal = undefined;\n\n // asynch takes a callback method\n // that is called when done\n asynch(function(data) {\n returnVal = data;\n done = true;\n });\n\n while (done == false) {};\n return returnVal;\n}\n"
},
{
"answer_id": 4642806,
"author": "Andrew Shooner",
"author_id": 186501,
"author_profile": "https://Stackoverflow.com/users/186501",
"pm_score": 0,
"selected": false,
"text": " render: function(queryResults){\n if (typeof queryResults != 'undefined'){\n console.log('Query completed!');\n //do what you will with the results (check for query errors here)\n\n } else {\n console.log('Beginning query...');\n this.db.read(this.render); //db.read is my wrapper method for the sql db, and I'm sending this render method as the callback.\n }\n }\n"
},
{
"answer_id": 4681514,
"author": "tomg",
"author_id": 455118,
"author_profile": "https://Stackoverflow.com/users/455118",
"pm_score": 3,
"selected": false,
"text": "var db = require(\"webdatabase\").openDatabase(\"CandyDB\", ...);\ntry {\n var kids = db.executeSql(\"SELECT * FROM kids\").rows;\n db.executeSql(\"INSERT INTO kids (name) VALUES (:name);\", [kids[0]]);\n alert(\"done\");\n} catch(e) {\n alert(\"something went wrong\");\n}\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29148/"
] |
214,500
|
<p>LINQ is one of the greatest improvements to .NET since generics and it saves me tons of time, and lines of code. However, the fluent syntax seems to come much more natural to me than the query expression syntax.</p>
<pre><code>var title = entries.Where(e => e.Approved)
.OrderBy(e => e.Rating).Select(e => e.Title)
.FirstOrDefault();
var query = (from e in entries
where e.Approved
orderby e.Rating
select e.Title).FirstOrDefault();
</code></pre>
<p>Is there any difference between the two or is there any particular benefit of one over other?</p>
|
[
{
"answer_id": 214610,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 6,
"selected": false,
"text": "var titlesQuery = from e in entries\n where e.Approved\n orderby e.Rating\n select e.Titles;\n\nvar title = titlesQuery.FirstOrDefault();\n .MethodCalls() var title = entries\n .Where (e => e.Approved)\n .OrderBy (e => e.Rating)\n .Select (e => e.Title)\n .FirstOrDefault();\n"
},
{
"answer_id": 823155,
"author": "Joe Albahari",
"author_id": 46223,
"author_profile": "https://Stackoverflow.com/users/46223",
"pm_score": 9,
"selected": true,
"text": "string[] fullNames = { \"Anne Williams\", \"John Fred Smith\", \"Sue Green\" };\n\nvar query =\n from fullName in fullNames\n from name in fullName.Split()\n orderby fullName, name\n select name + \" came from \" + fullName;\n var query = fullNames\n .SelectMany (fName => fName.Split().Select (name => new { name, fName } ))\n .OrderBy (x => x.fName)\n .ThenBy (x => x.name)\n .Select (x => x.name + \" came from \" + x.fName);\n var query =\n from c in db.Customers\n let totalSpend = c.Purchases.Sum (p => p.Price) // Method syntax here\n where totalSpend > 1000\n from p in c.Purchases\n select new { p.Description, totalSpend, c.Address.State };\n"
},
{
"answer_id": 9039282,
"author": "Tim Schmelter",
"author_id": 284240,
"author_profile": "https://Stackoverflow.com/users/284240",
"pm_score": 5,
"selected": false,
"text": "Function Dim fullNames = { \"Anne Williams\", \"John Fred Smith\", \"Sue Green\" };\nDim query =\n fullNames.SelectMany(Function(fName) fName.Split().\n Select(Function(Name) New With {Name, fName})).\n OrderBy(Function(x) x.fName).\n ThenBy(Function(x) x.Name).\n Select(Function(x) x.Name & \" came from \" & x.fName)\n query = From fullName In fullNames\n From name In fullName.Split()\n Order By fullName, name\n Select name & \" came from \" & fullName\n Dim first10Rows = From r In dataTable1 Take 10\n var first10Rows = (from r in dataTable1.AsEnumerable() \n select r)\n .Take(10);\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214500",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16340/"
] |
214,517
|
<p>The following Perl statements behave identically on Unixish machines. Do they behave differently on Windows? If yes, is it because of the magic \n?</p>
<pre><code> split m/\015\012/ms, $http_msg;
split m/\015\012/s, $http_msg;
</code></pre>
<p>I got a <a href="http://www.nntp.perl.org/group/perl.cpan.testers/2008/10/msg2450019.html" rel="nofollow noreferrer">failure</a> on one of my CPAN modules from a Win32 smoke tester. It looks like it's an \r\n vs \n issue. One change I made recently was to add //m to my regexes.</p>
|
[
{
"answer_id": 214800,
"author": "bart",
"author_id": 19966,
"author_profile": "https://Stackoverflow.com/users/19966",
"pm_score": 5,
"selected": true,
"text": "m/\\015\\012/ms\nm/\\015\\012/s\n . \\n . ^ $ \\n ^ $ \\r \\015 \\015 /\\015?\\012/\n m//"
},
{
"answer_id": 215256,
"author": "brian d foy",
"author_id": 2766176,
"author_profile": "https://Stackoverflow.com/users/2766176",
"pm_score": 1,
"selected": false,
"text": "/m /m ^ $ my @lines = split /^/m, $big_string;\n open my $string_fh, '<', \\ $big_string;\nwhile( <$string_fh> ) {\n ... process a line\n }\n"
},
{
"answer_id": 215351,
"author": "Aristotle Pagaltzis",
"author_id": 9410,
"author_profile": "https://Stackoverflow.com/users/9410",
"pm_score": 2,
"selected": false,
"text": "\\n \\n \\r \\cJ \\cM \\n \\r \\cM \\r\\n \\n \\cZ binmode /s /m . ^ $"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14783/"
] |
214,536
|
<p>What are some good templating engines for web designers? I definitely have my preferences as to what I'd prefer to work with as a programmer. But web designers seem to have a different way of thinking about things and thus may prefer a different system.</p>
<p>So:</p>
<ul>
<li>Web designers: what templating engine do you prefer to work with?</li>
<li>programmers: what templating engines have you worked with that made working with web designers easy?</li>
</ul>
|
[
{
"answer_id": 214932,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 4,
"selected": true,
"text": "${...}"
},
{
"answer_id": 214956,
"author": "nosklo",
"author_id": 17160,
"author_profile": "https://Stackoverflow.com/users/17160",
"pm_score": 3,
"selected": false,
"text": ">>> import jinja2\n>>> print jinja2.Environment().compile('{% for row in data %}{{ row.name | upper }}{% endfor %}', raw=True) \nfrom __future__ import division\nfrom jinja2.runtime import LoopContext, Context, TemplateReference, Macro, Markup, TemplateRuntimeError, missing, concat, escape, markup_join, unicode_join\nname = None\n\ndef root(context, environment=environment):\n l_data = context.resolve('data')\n t_1 = environment.filters['upper']\n if 0: yield None\n for l_row in l_data:\n if 0: yield None\n yield unicode(t_1(environment.getattr(l_row, 'name')))\n\nblocks = {}\ndebug_info = '1=9'\n if 0: yield None"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
] |
214,537
|
<p>I just moved a project to the the beta release of <code>ASP.net MVC</code> framework and the only problem I am having is with <code>jQuery</code> and <code>jQueryUI</code>. </p>
<p>Here's the deal:</p>
<p>In <code>Site.Master</code> are the following script references:</p>
<pre><code><script src="../../Scripts/jquery-1.2.6.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-ui.js" type="text/javascript"></script>
</code></pre>
<p>And using those, the <code>accordian UI</code> that I have on one of the views works perfectly, except for one problem: the images from <code>ThemeRoller</code> aren't included on the page. If I comment out the jQuery references, the ThemeRoller images are there. All of the css is in the <code>Content folder</code> and all of the scripts are in the <code>Scripts folder</code>.</p>
<p>I know this is a silly path problem, but it's making me twitch.</p>
<p>What am I missing?</p>
<p><strong>Update</strong></p>
<p>I tried the first answer to no avail, read the comment for details. Thanks again for those who are viewing. </p>
<p>The second approach is not working either. I'm baffled.</p>
<p><strong>Another Update</strong></p>
<p>Using the <code>Url.Content</code> tags for the scripts does indeed allow the scripts to run properly. Using a regular tag for the stylesheet gets all of the styles onto the page EXCEPT for all of those related to ThemeRoller. </p>
<p>The <code>jquery-ui-themeroller.css</code> file is in the Content folder and when I inspect an element, the css is present. I suspect the problem is in the mapping from this css file to the images folder for the themeroller, which is in the Content folder as well. Image links in this file as specified as: <code>background: url(images/foo.gif)</code></p>
<p>Do the links in this file need to change? </p>
|
[
{
"answer_id": 215395,
"author": "Adhip Gupta",
"author_id": 384,
"author_profile": "https://Stackoverflow.com/users/384",
"pm_score": 0,
"selected": false,
"text": "background: url(images/foo.gif)\n background: url(foo.gif)\n"
},
{
"answer_id": 656066,
"author": "chris",
"author_id": 79203,
"author_profile": "https://Stackoverflow.com/users/79203",
"pm_score": 0,
"selected": false,
"text": " protected void Page_Load(object sender, EventArgs e)\n {\n Page.ClientScript.RegisterClientScriptInclude(this.GetType(),\"JQuery\", ResolveUrl(\"~/js/jquery.min.js\"));\n Page.ClientScript.RegisterClientScriptInclude(this.GetType(), \"JQueryUI\", ResolveUrl(\"~/js/jquery-ui.custom.min.js\"));\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13139/"
] |
214,549
|
<p>On the Python side, I can create new numpy record arrays as follows:</p>
<pre><code>numpy.zeros((3,), dtype=[('a', 'i4'), ('b', 'U5')])
</code></pre>
<p>How do I do the same from a C program? I suppose I have to call <code>PyArray_SimpleNewFromDescr(nd, dims, descr)</code>, but how do I construct a <code>PyArray_Descr</code> that is appropriate for passing as the third argument to <code>PyArray_SimpleNewFromDescr</code>?</p>
|
[
{
"answer_id": 214574,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 3,
"selected": false,
"text": "[('a', 'i4'), ('b', 'U5')]"
},
{
"answer_id": 215090,
"author": "Vebjorn Ljosa",
"author_id": 17498,
"author_profile": "https://Stackoverflow.com/users/17498",
"pm_score": 5,
"selected": true,
"text": "PyArray_DescrConverter #include <Python.h>\n#include <stdio.h>\n#include <numpy/arrayobject.h>\n\nint main(int argc, char *argv[])\n{\n int dims[] = { 2, 3 };\n PyObject *op, *array;\n PyArray_Descr *descr;\n\n Py_Initialize();\n import_array();\n op = Py_BuildValue(\"[(s, s), (s, s)]\", \"a\", \"i4\", \"b\", \"U5\");\n PyArray_DescrConverter(op, &descr);\n Py_DECREF(op);\n array = PyArray_SimpleNewFromDescr(2, dims, descr);\n PyObject_Print(array, stdout, 0);\n printf(\"\\n\");\n Py_DECREF(array);\n return 0;\n}\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214549",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17498/"
] |
214,553
|
<p>When I enable common control visual style support (InitCommonControls()) and I am using any theme other then Windows Classic Theme, buttons inside a group box appear with a black border with square corners. </p>
<p>Windows Classic Theme appears normal, as well as when I turn off visual styling.</p>
<p>I am using the following code:</p>
<pre><code>group_box = CreateWindow(TEXT("BUTTON"), TEXT("BS_GROUPBOX"),
WS_CHILD | WS_VISIBLE | BS_GROUPBOX | WS_GROUP,
10, 10, 200, 300,
hwnd, NULL, hInstance, 0);
push_button = CreateWindow(TEXT("BUTTON"), TEXT("BS_PUSHBUTTON"),
WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,
40, 40, 100, 22,
group_box, NULL, hInstance, 0);
</code></pre>
<p>EDIT: The issue occurs with radio buttons as well</p>
<p>EDIT: I am not using any dialogs/resources, only CreateWindow/Ex. </p>
<p>I am compiling under Visual C++ 2008 Express SP1, with a generic <a href="http://msdn.microsoft.com/en-us/library/ms997646.aspx" rel="nofollow noreferrer">manifest</a> file</p>
<p><a href="http://img.ispankcode.com/black_border_issue.png" rel="nofollow noreferrer">Screenshot http://img.ispankcode.com/black_border_issue.png</a></p>
|
[
{
"answer_id": 214685,
"author": "SmacL",
"author_id": 22564,
"author_profile": "https://Stackoverflow.com/users/22564",
"pm_score": 1,
"selected": false,
"text": "WS_EX_STATICEDGE, WS_EX_WINDOWEDGE and WS_EX_CLIENTEDGE"
},
{
"answer_id": 296594,
"author": "efotinis",
"author_id": 12320,
"author_profile": "https://Stackoverflow.com/users/12320",
"pm_score": 3,
"selected": true,
"text": "// Calculate the client area of a dialog that corresponds to the perceived\n// client area of a groupbox control. An extra padding in dialog units can\n// be specified (preferably in multiples of 4).\n//\nRECT getClientAreaInGroupBox(HWND dlg, int id, int padding = 0) {\n HWND group = GetDlgItem(dlg, id);\n RECT rc;\n GetWindowRect(group, &rc);\n MapWindowPoints(0, dlg, (POINT*)&rc, 2);\n\n // Note that the top DUs should be 9 to completely avoid overlapping the\n // groupbox label, but 8 is used instead for better alignment on a 4x4\n // design grid.\n RECT border = { 4, 8, 4, 4 };\n OffsetRect(&border, padding, padding);\n MapDialogRect(dlg, &border);\n\n rc.left += border.left;\n rc.right -= border.right;\n rc.top += border.top;\n rc.bottom -= border.bottom;\n return rc;\n}\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2067/"
] |
214,568
|
<p>Is there a good way to add a .swf programatically to a panel on an asp.net page - ie: I know i could just insert the html tags:</p>
<p>ie: </p>
<pre><code><object type="application/x-shockwave-flash" data="yourflash.swf" width="" height="">
<param name="movie" value="yourflash.swf">
</object>
</code></pre>
<p>But is there an existing .net or free FLASH component already that you just set the properties on, or do i need to create a custom web control myself (not preferred) so i dont have to continously do this?</p>
<p>Thank you. </p>
|
[
{
"answer_id": 214685,
"author": "SmacL",
"author_id": 22564,
"author_profile": "https://Stackoverflow.com/users/22564",
"pm_score": 1,
"selected": false,
"text": "WS_EX_STATICEDGE, WS_EX_WINDOWEDGE and WS_EX_CLIENTEDGE"
},
{
"answer_id": 296594,
"author": "efotinis",
"author_id": 12320,
"author_profile": "https://Stackoverflow.com/users/12320",
"pm_score": 3,
"selected": true,
"text": "// Calculate the client area of a dialog that corresponds to the perceived\n// client area of a groupbox control. An extra padding in dialog units can\n// be specified (preferably in multiples of 4).\n//\nRECT getClientAreaInGroupBox(HWND dlg, int id, int padding = 0) {\n HWND group = GetDlgItem(dlg, id);\n RECT rc;\n GetWindowRect(group, &rc);\n MapWindowPoints(0, dlg, (POINT*)&rc, 2);\n\n // Note that the top DUs should be 9 to completely avoid overlapping the\n // groupbox label, but 8 is used instead for better alignment on a 4x4\n // design grid.\n RECT border = { 4, 8, 4, 4 };\n OffsetRect(&border, padding, padding);\n MapDialogRect(dlg, &border);\n\n rc.left += border.left;\n rc.right -= border.right;\n rc.top += border.top;\n rc.bottom -= border.bottom;\n return rc;\n}\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26685/"
] |
214,583
|
<p>In the default asp.net mvc project, in the Site.Master file, there is a menu navigation list:</p>
<pre><code><div id="menucontainer">
<ul id="menu">
<li><%= Html.ActionLink("Home", "Index", "Home")%></li>
<li><%= Html.ActionLink("About Us", "About", "Home")%></li>
</ul>
</div>
</code></pre>
<p>This renders in the browser to:</p>
<pre><code><div id="menucontainer">
<ul id="menu">
<li><a href="/">Home</a></li>
<li><a href="/Home/About">About Us</a></li>
</ul>
</div>
</code></pre>
<p>I want to be able to dynamically set the active list item, based on the view that is being called. That is, when the user is looking at the home page, I would want the following HTML to be created:</p>
<pre><code><div id="menucontainer">
<ul id="menu">
<li class="active"><a href="/">Home</a></li>
<li><a href="/Home/About">About Us</a></li>
</ul>
</div>
</code></pre>
<p>I would expect that the way to do this would be something like:</p>
<pre><code><div id="menucontainer">
<ul id="menu">
<li <% if(actionName == "Index"){%> class="active"<%}%>><%= Html.ActionLink("Home", "Index", "Home")%></li>
<li <% if(actionName == "About"){%> class="active"<%}%>><%= Html.ActionLink("About Us", "About", "Home")%></li>
</ul>
</div>
</code></pre>
<p>The key bit here is the <code><% if(actionName == "Index"){%> class="active"<%}%></code> line. I do not know how to determine what the current actionName is.</p>
<p>Any suggestions on how to do this? Or, if I'm on completely the wrong track, is there a better way to do this?</p>
|
[
{
"answer_id": 215385,
"author": "Jason Whitehorn",
"author_id": 27860,
"author_profile": "https://Stackoverflow.com/users/27860",
"pm_score": 0,
"selected": false,
"text": "public ActionResult Index(){\n ViewData[\"currentAction\"] = \"Index\";\n //... other code\n return View();\n}\n <% if( ((string)ViewData[\"currentAction\"]) == \"Index\" {%> <!- some links --><% } %>\n<% if( ((string)ViewData[\"currentAction\"]) == \"SomethingElse\" {%> <!- some links --><% } %>\n"
},
{
"answer_id": 226120,
"author": "Craig Stuntz",
"author_id": 7714,
"author_profile": "https://Stackoverflow.com/users/7714",
"pm_score": 3,
"selected": false,
"text": "ViewContext.RouteData.Values[\"action\"].ToString()\n"
},
{
"answer_id": 230334,
"author": "Jonathan S.",
"author_id": 2034,
"author_profile": "https://Stackoverflow.com/users/2034",
"pm_score": 0,
"selected": false,
"text": "<ul id=\"menu\">\n <li id=\"menuHomeIndex\" runat=\"server\"><%= Html.ActionLink(\"Home\", \"Index\", \"Home\") %></li>\n <li id=\"menuHomeAbout\" runat=\"server\"><%= Html.ActionLink(\"About Us\", \"About\", \"Home\") %></li>\n</ul>\n // This is called in Page_Load\nprivate void SetActiveLink()\n{\n string action = \"\" + ViewContext.RouteData.Values[\"controller\"] + ViewContext.RouteData.Values[\"action\"];\n var activeMenu = (HtmlGenericControl)Page.Master.FindControl(\"menu\" + action);\n\n if (activeMenu != null)\n {\n activeMenu.Attributes.Add(\"class\", \"selected\");\n }\n}\n"
},
{
"answer_id": 326234,
"author": "labilbe",
"author_id": 1195872,
"author_profile": "https://Stackoverflow.com/users/1195872",
"pm_score": 3,
"selected": false,
"text": "public static string MenuActionLink(this HtmlHelper helper, string linkText, string actionName, string controllerName)\n{\n var htmlAttributes = new RouteValueDictionary();\n\n if (helper.ViewContext.Controller.GetType().Name.Equals(controllerName + \"Controller\", StringComparison.OrdinalIgnoreCase))\n {\n htmlAttributes.Add(\"class\", \"current\");\n }\n\n return helper.ActionLink(linkText, actionName, controllerName, new RouteValueDictionary(), htmlAttributes);\n}\n"
},
{
"answer_id": 326313,
"author": "Slee",
"author_id": 34548,
"author_profile": "https://Stackoverflow.com/users/34548",
"pm_score": 1,
"selected": false,
"text": "<script src=\"http://www.google.com/jsapi\" type=\"text/javascript\" language=\"javascript\"></script>\n<script type=\"text/javascript\" language=\"javascript\">google.load(\"jquery\", \"1\");</script> \n\n<script language=\"javascript\" type=\"text/javascript\">\n $(document).ready(function(){\n var str=location.href.toLowerCase(); \n $('#menucontainer ul#menu li a').each(function() {\n if (str.indexOf(this.href.toLowerCase()) > -1) {\n $(this).attr(\"class\",\"current\"); //hightlight parent tab\n } \n });\n }); \n </script>\n"
},
{
"answer_id": 366070,
"author": "Adam Carr",
"author_id": 1405,
"author_profile": "https://Stackoverflow.com/users/1405",
"pm_score": 5,
"selected": false,
"text": "protected string ActiveActionLinkHelper(string linkText, string actionName, string controlName, string activeClassName)\n{\n if (ViewContext.RouteData.Values[\"action\"].ToString() == actionName && \n ViewContext.RouteData.Values[\"controller\"].ToString() == controlName)\n return Html.ActionLink(linkText, actionName, controlName, new { Class = activeClassName });\n\n return Html.ActionLink(linkText, actionName, controlName);\n}\n <%= ActiveActionLinkHelper(\"Home\", \"Index\", \"Home\", \"selected\")%>\n"
},
{
"answer_id": 6894018,
"author": "Ricardo Vera",
"author_id": 870299,
"author_profile": "https://Stackoverflow.com/users/870299",
"pm_score": 0,
"selected": false,
"text": "<ul id=\"menu\">\n @if (ViewContext.RouteData.Values[\"action\"].ToString() == \"Index\")\n {\n <li class=\"active\">@Html.ActionLink(\"Home\", \"Index\", \"Home\")</li>\n }\n else\n {\n <li>@Html.ActionLink(\"Home\", \"Index\", \"Home\")</li>\n }\n @if (ViewContext.RouteData.Values[\"action\"].ToString() == \"About\")\n {\n <li class=\"active\">@Html.ActionLink(\"About\", \"About\", \"Home\")</li>\n }\n else\n {\n <li>@Html.ActionLink(\"About\", \"About\", \"Home\")</li>\n }\n</ul>\n ul#menu li.active \n{\n text-decoration:underline;\n}\n"
},
{
"answer_id": 8312320,
"author": "Telvin Nguyen",
"author_id": 1041471,
"author_profile": "https://Stackoverflow.com/users/1041471",
"pm_score": 3,
"selected": false,
"text": "@{string ctrName = ViewContext.RouteData.Values[\"controller\"].ToString();}\n\n<div id=\"menucontainer\">\n <ul id=\"menu\"> \n <li @if(ctrName == \"Home\"){<text> class=\"active\"</text>}>@ Html.ActionLink(\"Home\", \"Index\", \"Home\")</li>\n <li @if(ctrName == \"About\"){<text> class=\"active\"</text>}>@ Html.ActionLink(\"About Us\", \"About\", \"Home\")</li>\n </ul>\n</div>\n @{string ctrName = ViewContext.RouteData.Values[\"action\"].ToString();}\n"
},
{
"answer_id": 10683129,
"author": "Yvo",
"author_id": 136819,
"author_profile": "https://Stackoverflow.com/users/136819",
"pm_score": 0,
"selected": false,
"text": "using System;\nusing System.Web.Mvc;\nusing System.Web.Mvc.Html;\nusing System.Web.Routing;\n\nnamespace MyApp.Web {\n public static class HtmlHelpers {\n /// <summary>\n /// Returns an anchor element (a element) that contains the virtual path of the\n /// specified action. If the controller name matches the active controller, the\n /// css class 'current' will be applied.\n /// </summary>\n public static MvcHtmlString MenuActionLink(this HtmlHelper helper, string linkText, string actionName, string controllerName) {\n var htmlAttributes = new RouteValueDictionary();\n string name = helper.ViewContext.Controller.GetType().Name;\n\n if (name.Equals(controllerName + \"Controller\", StringComparison.OrdinalIgnoreCase))\n htmlAttributes.Add(\"class\", \"current\");\n\n return helper.ActionLink(linkText, actionName, controllerName, new RouteValueDictionary(), htmlAttributes);\n }\n }\n}\n"
},
{
"answer_id": 10850198,
"author": "Tim Iles",
"author_id": 487544,
"author_profile": "https://Stackoverflow.com/users/487544",
"pm_score": 3,
"selected": false,
"text": "/// \n/// adds the active class if the link's action & controller matches current request\n/// \npublic static MvcHtmlString MenuActionLink(this HtmlHelper htmlHelper,\n string linkText, string actionName, string controllerName,\n object routeValues = null, object htmlAttributes = null,\n string activeClassName = \"active\")\n{\n IDictionary htmlAttributesDictionary =\n HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);\n\n if (((string)htmlHelper.ViewContext.RouteData.Values[\"controller\"])\n .Equals(controllerName, StringComparison.OrdinalIgnoreCase) &&\n ((string)htmlHelper.ViewContext.RouteData.Values[\"action\"])\n .Equals(actionName, StringComparison.OrdinalIgnoreCase))\n {\n // careful in case class already exists\n htmlAttributesDictionary[\"class\"] += \" \" + activeClassName;\n }\n\n return htmlHelper.ActionLink(linkText, actionName, controllerName,\n new RouteValueDictionary(routeValues),\n htmlAttributesDictionary);\n}\n\n/// \n/// adds the active class if the link's path matches current request\n/// \npublic static MvcHtmlString MenuActionLink(this HtmlHelper htmlHelper,\n string linkText, string path, object htmlAttributes = null,\n string activeClassName = \"active\")\n{\n IDictionary htmlAttributesDictionary =\n HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);\n if (HttpContext.Current.Request.Path\n .Equals(path, StringComparison.OrdinalIgnoreCase))\n {\n // careful in case class already exists\n htmlAttributesDictionary[\"class\"] += \" \" + activeClassName;\n }\n var tagBuilder = new TagBuilder(\"a\")\n {\n InnerHtml = !string.IsNullOrEmpty(linkText)\n ? HttpUtility.HtmlEncode(linkText)\n : string.Empty\n };\n tagBuilder.MergeAttributes(htmlAttributesDictionary);\n tagBuilder.MergeAttribute(\"href\", path);\n return MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.Normal));\n}"
},
{
"answer_id": 15315818,
"author": "Bermy Dev",
"author_id": 2152420,
"author_profile": "https://Stackoverflow.com/users/2152420",
"pm_score": 1,
"selected": false,
"text": "public abstract class LayoutModel\n{\n public CurrentPage CurrentPage { get; set; }\n}\n public class LayoutAttribute : ActionFilterAttribute\n{\n private CurrentPage _currentPage { get; set; }\n\n public LayoutAttribute(\n CurrentPage CurrentPage\n ){\n _currentPage = CurrentPage;\n }\n\n public override void OnActionExecuted(ActionExecutedContext filterContext)\n {\n var result = filterContext.Result as ViewResultBase;\n if (result == null || result.Model == null || !(result.Model is LayoutModel)) return;\n\n ((LayoutModel)result.Model).CurrentPage = _currentPage;\n }\n}\n [Layout(CurrentPage.Account)]\npublic class MyController : Controller\n{\n\n}\n"
},
{
"answer_id": 22595795,
"author": "Anytoe",
"author_id": 1367811,
"author_profile": "https://Stackoverflow.com/users/1367811",
"pm_score": 2,
"selected": false,
"text": "<li class=\"@ViewBag.NavClassHome\">@Html.ActionLink(\"Home\", \"Index\", \"Home\")</li>\n<li class=\"@ViewBag.NavClassAbout\">@Html.ActionLink(\"Disclaimer\", \"About\", \"Home\")</li>\n public ActionResult Index() {\n ViewBag.NavClassHome = \"active\";\n return View();\n} \n\npublic ActionResult About() {\n ViewBag.NavClassAbout = \"active\";\n return View();\n}\n [HttpPost]\npublic ActionResult Index() {\n ViewBag.NavClassHome = \"active\";\n return View();\n}\n\n[HttpPost]\npublic ActionResult About() {\n ViewBag.NavClassAbout = \"active\";\n return View();\n}\n"
},
{
"answer_id": 31123936,
"author": "Nanan",
"author_id": 5062725,
"author_profile": "https://Stackoverflow.com/users/5062725",
"pm_score": 3,
"selected": false,
"text": "@{\n ViewBag.PageName = \"Index\";\n}\n <li class=\"@((ViewBag.PageName == \"Index\") ? \"active\" : \"\")\"><a href=\"@Url.Action(\"Index\",\"Home\")\">Home</a></li>\n<li class=\"@((ViewBag.PageName == \"About\") ? \"active\" : \"\")\"><a href=\"@Url.Action(\"About\",\"Home\")\">About</a></li>\n<li class=\"@((ViewBag.PageName == \"Contact\") ? \"active\" : \"\")\"><a href=\"@Url.Action(\"Contact\",\"Home\")\">Contact</a></li>"
},
{
"answer_id": 62834436,
"author": "Farhana",
"author_id": 11040220,
"author_profile": "https://Stackoverflow.com/users/11040220",
"pm_score": 0,
"selected": false,
"text": "<ul>\n <li class=\"@(ViewContext.RouteData.Values[\"Controller\"].ToString() == \"Home\" ? \"active\" : \"\")\">\n <a asp-area=\"\" asp-controller=\"Home\" asp-action=\"Index\"><i class=\"icon fa fa-home\"></i><span>Home</span>\n </a>\n </li>\n</ul>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29092/"
] |
214,590
|
<p>I'm looking for something that will let me parse Atom and RSS in Ruby and Rails. I've looked at the standard RSS library, but is there one library that will auto-detect whatever type of feed it is and parse it for me?</p>
|
[
{
"answer_id": 214611,
"author": "Pistos",
"author_id": 28558,
"author_profile": "https://Stackoverflow.com/users/28558",
"pm_score": 4,
"selected": false,
"text": "require 'simple-rss'\nrequire 'open-uri'\nrss = SimpleRSS.parse open('http://slashdot.org/index.rdf')\nrss.channel.title # => \"Slashdot\"\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4322/"
] |
214,622
|
<p>I have a webservice, which takes java.lang.object objects as parameters (because at runtime only know hte type of object)...after doing process, reply response setting java.lang.Object to it.</p>
<p>I am able to send the reuest objects to webservice from calling program, but getting NotSerializable exception while building the response from webservice.</p>
<p>I came to know that 'if we implement, java.io.serializable, the mebmers also should be serializable objects'... here Object isnot a serializable object..it doesn't impllement Serializable....</p>
<p>If anyone could guide mw with right solution..I wouold be thankful.</p>
<p>Thanks
Bhaskar</p>
|
[
{
"answer_id": 214813,
"author": "myplacedk",
"author_id": 28683,
"author_profile": "https://Stackoverflow.com/users/28683",
"pm_score": 1,
"selected": false,
"text": "private void writeObject(java.io.ObjectOutputStream out) throws IOException;\nprivate void readObject(java.io.ObjectInputStream in) throws IOException, classNotFoundException;\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
214,640
|
<p>It's just so much <code>HRESULT E_FAIL</code>, if you know what I'm talking about. </p>
<p>And if you use Visual Studio, you know what I'm talking about.</p>
<p>Similar thread, but not a duplicate: <a href="https://stackoverflow.com/questions/196001/is-the-design-view-for-aspx-pages-in-visual-studio-useful">Is the design view for aspx pages in Visual Studio useful?</a></p>
<p>Any insight, including input from Microsoft MVPs (oh, I know you're out there) would be super cool.</p>
|
[
{
"answer_id": 3284130,
"author": "ItsPronounced",
"author_id": 355754,
"author_profile": "https://Stackoverflow.com/users/355754",
"pm_score": -1,
"selected": false,
"text": "masterpages web.config <location path=\"MasterPage\">\n<system.web>\n <authorization>\n <allow users=\"?\" />\n </authorization>\n</system.web>\n"
},
{
"answer_id": 21383444,
"author": "Suhaib Janjua",
"author_id": 3240038,
"author_profile": "https://Stackoverflow.com/users/3240038",
"pm_score": 2,
"selected": false,
"text": "<%@ Register Src=\"Ctrl_AdminReports.ascx\" TagName=\"Ctrl_AdminReports\" TagPrefix=\"uc1\" %>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13578/"
] |
214,642
|
<p>I know it's by design that you can't control what happens when an object is destroyed. I am also aware of defining some class method as a finalizer.</p>
<p>However is the ruby idiom for C++'s RAII (Resources are initialized in constructor, closed in destructor)? How do people manage resources used inside objects even when errors or exceptions happen?</p>
<p>Using <em>ensure</em> works:</p>
<pre><code>f = File.open("testfile")
begin
# .. process
rescue
# .. handle error
ensure
f.close unless f.nil?
end
</code></pre>
<p>but users of the class <strong>have to remember to do the whole begin-rescue-ensure chacha</strong> everytime the open method needs to be called. </p>
<p>So for example, I'll have the following class:</p>
<pre><code>class SomeResource
def initialize(connection_string)
@resource_handle = ...some mojo here...
end
def do_something()
begin
@resource_handle.do_that()
...
rescue
...
ensure
end
def close
@resource_handle.close
end
end
</code></pre>
<p>The resource_handle won't be closed if the exception is cause by some other class and the script exits.</p>
<p>Or is the problem more of I'm still doing this too C++-like?</p>
|
[
{
"answer_id": 214648,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": -1,
"selected": false,
"text": "ensure f = File.open(\"testfile\")\nbegin\n # .. process\nrescue\n # .. handle error\nensure\n f.close unless f.nil?\nend\n"
},
{
"answer_id": 214663,
"author": "bk1e",
"author_id": 8090,
"author_profile": "https://Stackoverflow.com/users/8090",
"pm_score": 3,
"selected": false,
"text": "yield File.open(\"testfile\") do |f|\n begin\n # .. process\n rescue\n # .. handle error\n end\nend\n"
},
{
"answer_id": 1077774,
"author": "Greg",
"author_id": 384507,
"author_profile": "https://Stackoverflow.com/users/384507",
"pm_score": 5,
"selected": true,
"text": "rescue ensure yield class SomeResource\n ...\n def SomeResource.use(*resource_args)\n # create resource\n resource = SomeResource.new(*resource_args) # pass args direct to constructor\n # export it\n yield resource\n rescue\n # known error processing\n ...\n ensure\n # close up when done even if unhandled exception thrown from block\n resource.close\n end\n ...\nend\n SomeResource.use(connection_string) do | resource |\n resource.do_something\n ... # whatever else\nend\n# after this point resource has been .close()d\n File.open File.open(\"testfile\") do |f|\n # .. process - may include throwing exceptions\nend\n# f is guaranteed closed after this point even if exceptions are \n# thrown during processing\n"
},
{
"answer_id": 4309164,
"author": "Julik",
"author_id": 153886,
"author_profile": "https://Stackoverflow.com/users/153886",
"pm_score": 2,
"selected": false,
"text": "def with_shmoo\n handle = allocate_shmoo\n yield(handle)\nensure\n handle.close\nend\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26374/"
] |
214,644
|
<p>I have two windows services running on the same machine. Both the services uses</p>
<p>private HttpListener listener;</p>
<p>I specify the baseURL as "<a href="http://IPAddress:8080/" rel="noreferrer">http://IPAddress:8080/</a>" & "<a href="http://IPAddress:8081/" rel="noreferrer">http://IPAddress:8081/</a>" respectively for each of the services. Then I do the needful and call</p>
<p>listener.Start();</p>
<p>The first service starts successfully at 8080 port. But when I now start the 2nd service,
I get HTTPListenerException "The process cannot access the file because it is being used by another process" for listener object.</p>
<p>Could anybody please tell me:
1) If it is possible to start two HTTP listeners on the same IIS at two different ports.
2) If yes, how can we achecive this?
3) Is there any other way of doing this?</p>
<p>For your information:
I am using C#.NET 2.0 and IIS 6.0 server.</p>
<p>Thanks & Regards,</p>
<p>Hari</p>
|
[
{
"answer_id": 214754,
"author": "s3v1",
"author_id": 17554,
"author_profile": "https://Stackoverflow.com/users/17554",
"pm_score": 2,
"selected": false,
"text": "String[] prefixes = { \"http://localhost:8280/\", \"http://localhost:8281/\"};\n\nHttpListener listener = new HttpListener();\nlistener.Prefixes.Add(\"http://localhost:8280/\");\nlistener.Start();\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
214,645
|
<p>Is there a clever way of adding XML serialization instructions without modifying the serialized class?</p>
<p>I don’t like the default serialization and I can’t modify the class. I was considering inheriting the class, and using Shadows (VB.NET) to re-implement the properties (with the serialization instructions), but it results in a lot of duplicate code and just looks terrible.</p>
<p>The ideal solution I'm looking for is basically a method to keep all the serialization instructions in a separate file.</p>
|
[
{
"answer_id": 214673,
"author": "benPearce",
"author_id": 4490,
"author_profile": "https://Stackoverflow.com/users/4490",
"pm_score": 0,
"selected": false,
"text": "PropertyInfo[] properties = control.GetType().GetProperties();\nforeach (PropertyInfo property in properties)\n{\n object o = property.GetValue(control, null);\n // write value of o.ToString() out as an attribute on a XmlNode\n // where attribute name is property.Name\n}\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10932/"
] |
214,661
|
<p>Essentially what I want is a BlockingQueue of size=1. I have a "listener" thread that simply waits, blocking until an object is put into the queue, and then retrieves it--and a "producer" thread that actually puts the object into the queue.</p>
<p>I can implement this with some synchronized blocks and a BlockingQueue implementation, but that seems like overkill. Is there a better, simpler way to do what I want?</p>
<p>Example interface:</p>
<pre><code>public interface Wait<T> {
/**
* If "put" has never been called on this object, then this method will
* block and wait until it has. Once "put" has been called with some T, this
* method will return that T immediately.
*/
public T get() throws InterruptedException;
/**
* @param object The object to return to callers of get(). If called more
* than once, will throw an {@link IllegalStateException}.
*/
public void put(T object);
}
</code></pre>
|
[
{
"answer_id": 214673,
"author": "benPearce",
"author_id": 4490,
"author_profile": "https://Stackoverflow.com/users/4490",
"pm_score": 0,
"selected": false,
"text": "PropertyInfo[] properties = control.GetType().GetProperties();\nforeach (PropertyInfo property in properties)\n{\n object o = property.GetValue(control, null);\n // write value of o.ToString() out as an attribute on a XmlNode\n // where attribute name is property.Name\n}\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29173/"
] |
214,688
|
<p>Apparently, they're "confusing". Is that seriously the reason? Can you think of any others?</p>
|
[
{
"answer_id": 215371,
"author": "Cristian Libardo",
"author_id": 16526,
"author_profile": "https://Stackoverflow.com/users/16526",
"pm_score": -1,
"selected": false,
"text": "int myValue;\nReadFromSomewhere(ref myValue);\n int myValue = ReadFromSomewhere();\n"
},
{
"answer_id": 215918,
"author": "user23117",
"author_id": 23117,
"author_profile": "https://Stackoverflow.com/users/23117",
"pm_score": 1,
"selected": false,
"text": "Customer GetCustomerById(int id, out string errorMessage);\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18658/"
] |
214,700
|
<p>In the following case I'm calling a <code>Func</code> with pointer passed to it, but in the called function, the parameter shows the pointer value as something totally bogus. Something like below.</p>
<pre><code>bool flag = Func(pfspara);--> pfspara = 0x0091d910
bool Func(PFSPARA pfspara) --> pfspara = 0x00000005
{
return false;
}
</code></pre>
<p>Why does <code>pfspara</code> change to some bogus pointer? I can't reproduce the problem in debug, only in production.</p>
<p>Thanks.</p>
|
[
{
"answer_id": 214711,
"author": "Rasmus Faber",
"author_id": 5542,
"author_profile": "https://Stackoverflow.com/users/5542",
"pm_score": 3,
"selected": false,
"text": "bool Func(PFSPARA pfspara)\n{\n printf(\"%x\\n\", pfspara);\n return false;\n}\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13432/"
] |
214,714
|
<p>I'm trying to get my head around mutable vs immutable objects. Using mutable objects gets a lot of bad press (e.g. returning an array of strings from a method) but I'm having trouble understanding what the negative impacts are of this. What are the best practices around using mutable objects? Should you avoid them whenever possible?</p>
|
[
{
"answer_id": 214718,
"author": "Daniel Spiewak",
"author_id": 9815,
"author_profile": "https://Stackoverflow.com/users/9815",
"pm_score": 9,
"selected": true,
"text": "Person equals Map<Person, String> map = ...\nPerson p = new Person();\nmap.put(p, \"Hey, there!\");\n\np.setName(\"Daniel\");\nmap.get(p); // => null\n Person hashCode"
},
{
"answer_id": 18922685,
"author": "supercat",
"author_id": 363751,
"author_profile": "https://Stackoverflow.com/users/363751",
"pm_score": 1,
"selected": false,
"text": "foo int[] arr int[3] foo arr foo arr foo foo arr foo.arr foo foo arr arr foo foo arr arr arr foo.arr foo foo int[] String"
},
{
"answer_id": 62935284,
"author": "yoAlex5",
"author_id": 4770877,
"author_profile": "https://Stackoverflow.com/users/4770877",
"pm_score": 0,
"selected": false,
"text": "Unmodifiable Immutable shared resource read-only immutable final primitives let struct primitive reference value reference immutable primitives value reference clone deep shallow"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6651/"
] |
214,722
|
<p>I'm using the contentEditable attribute on a DIV element in Firefox 3.03. Setting it to true allows me to edit the text content of the DIV, as expected.</p>
<p>Then, when I set contentEditable to "false", the div is no longer editable, also as expected. </p>
<p>However the flashing caret (text input cursor) remains visible even though the text is no longer editable. The caret is now also visible when I click on most other text in the same page, even in normal text paragraphs.</p>
<p>Has anyone seen this before? Is there any way to force the caret hidden? </p>
<p>(When I either resize the browser or click within another application, and come back, the caret magically disappears.)</p>
|
[
{
"answer_id": 215170,
"author": "Borgar",
"author_id": 27388,
"author_profile": "https://Stackoverflow.com/users/27388",
"pm_score": 4,
"selected": true,
"text": "if ($.browser.mozilla) { // replace with browser detection of your choice\n window.getSelection().removeAllRanges();\n}\n if ($.browser.msie) {\n element.contentEditable = false;\n}\nelse {\n $(element).removeAttr( 'contenteditable' );\n}\n"
},
{
"answer_id": 3012230,
"author": "Lincy Chandy",
"author_id": 363167,
"author_profile": "https://Stackoverflow.com/users/363167",
"pm_score": 0,
"selected": false,
"text": "-moz-user-input contenteditable=false none : The element does not respond to user input.\nenabled : The element can accepts user input. This is default.\ndisabled : The element does not accept user input.\n // to disallow users to enter input\n<asp:TextBox ID=\"uxFromDate\" runat=\"server\" style=\"-moz-user-input: disabled;\"></asp:TextBox>\n\n// to allow users to enter input\n<asp:TextBox ID=\"uxFromDate\" runat=\"server\" style=\"-moz-user-input: enabled ;\"></asp:TextBox>\n"
},
{
"answer_id": 19005611,
"author": "Gustavo",
"author_id": 694610,
"author_profile": "https://Stackoverflow.com/users/694610",
"pm_score": 0,
"selected": false,
"text": " getDoc().designMode = \"off\";\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5023/"
] |
214,730
|
<p>I'm creating a gem which has</p>
<ul>
<li>several scripts in the bin directory</li>
<li>the utility classes in the lib directory</li>
<li>and several tests in the test directory</li>
</ul>
<pre>
supertool
bin
toolA
toolB
lib
supertool
supertool.rb
helper.rb
test
tc_main.rb
tc_etc.rb
</pre>
<p>Now, to run the tests before I even install the gem, I have the following snippet at the top of my tests:</p>
<pre><code>base = File.basename(Dir.pwd)
if base == 'test' || base =~ /supertool/
Dir.chdir('..') if base == 'test'
$LOAD_PATH.unshift(Dir.pwd + '/lib')
Dir.chdir('test') if base =~ /supertool/
end
</code></pre>
<p>This seems tedious though, especially if I have to put these in the scripts in the bin directory too. Is there a better way of setting up the environment so we can test gems before they are installed? I'm sure it's something simple that I just can't find. A simple link to the right place would help a lot :)</p>
|
[
{
"answer_id": 259783,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 3,
"selected": true,
"text": "ruby tc_main.rb ruby test/tc_main.rb test_helper.rb $LOAD_PATH << File.expand_path( File.dirname(__FILE__) + '/../lib' )\n require 'test_helper'\n require '../test_helper' \n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26374/"
] |
214,741
|
<p>What is a <code>StackOverflowError</code>, what causes it, and how should I deal with them?</p>
|
[
{
"answer_id": 214756,
"author": "Khoth",
"author_id": 20686,
"author_profile": "https://Stackoverflow.com/users/20686",
"pm_score": 6,
"selected": false,
"text": "int foo()\n{\n // more stuff\n foo();\n}\n"
},
{
"answer_id": 11531095,
"author": "Vikram",
"author_id": 801919,
"author_profile": "https://Stackoverflow.com/users/801919",
"pm_score": 3,
"selected": false,
"text": "StackOverflowError OutOfMemoryError StackOverflowError class StackOverflowDemo\n{\n public static void unboundedRecursiveCall() {\n unboundedRecursiveCall();\n }\n\n public static void main(String[] args) \n {\n unboundedRecursiveCall();\n }\n}\n StackOverflowError"
},
{
"answer_id": 14366600,
"author": "Yiling",
"author_id": 1212682,
"author_profile": "https://Stackoverflow.com/users/1212682",
"pm_score": 2,
"selected": false,
"text": "private static LinkedListNode doReverseRecursively(LinkedListNode x, LinkedListNode first){\n\n LinkedListNode second = first.next;\n\n first.next = x;\n\n if(second != null){\n return doReverseRecursively(first, second);\n }else{\n return first;\n }\n}\n\n\npublic static LinkedListNode reverseRecursively(LinkedListNode head){\n return doReverseRecursively(null, head);\n}\n public static LinkedListNode reverseIteratively(LinkedListNode head){\n return doReverseIteratively(null, head);\n}\n\n\nprivate static LinkedListNode doReverseIteratively(LinkedListNode x, LinkedListNode first) {\n\n while (first != null) {\n LinkedListNode second = first.next;\n first.next = x;\n x = first;\n\n if (second == null) {\n break;\n } else {\n first = second;\n }\n }\n return first;\n}\n\n\npublic static LinkedListNode reverseIteratively(LinkedListNode head){\n return doReverseIteratively(null, head);\n}\n"
},
{
"answer_id": 29279234,
"author": "Varun",
"author_id": 3454208,
"author_profile": "https://Stackoverflow.com/users/3454208",
"pm_score": 7,
"selected": false,
"text": "StackOverflowError StackOverflowError StackOverflowError public class StackOverflowErrorExample {\n\n public static void recursivePrint(int num) {\n System.out.println(\"Number: \" + num);\n if (num == 0)\n return;\n else\n recursivePrint(++num);\n }\n\n public static void main(String[] args) {\n StackOverflowErrorExample.recursivePrint(1);\n }\n}\n recursivePrint 0 -Xss1M Number: 1\nNumber: 2\nNumber: 3\n...\nNumber: 6262\nNumber: 6263\nNumber: 6264\nNumber: 6265\nNumber: 6266\nException in thread \"main\" java.lang.StackOverflowError\n at java.io.PrintStream.write(PrintStream.java:480)\n at sun.nio.cs.StreamEncoder.writeBytes(StreamEncoder.java:221)\n at sun.nio.cs.StreamEncoder.implFlushBuffer(StreamEncoder.java:291)\n at sun.nio.cs.StreamEncoder.flushBuffer(StreamEncoder.java:104)\n at java.io.OutputStreamWriter.flushBuffer(OutputStreamWriter.java:185)\n at java.io.PrintStream.write(PrintStream.java:527)\n at java.io.PrintStream.print(PrintStream.java:669)\n at java.io.PrintStream.println(PrintStream.java:806)\n at StackOverflowErrorExample.recursivePrint(StackOverflowErrorExample.java:4)\n at StackOverflowErrorExample.recursivePrint(StackOverflowErrorExample.java:9)\n at StackOverflowErrorExample.recursivePrint(StackOverflowErrorExample.java:9)\n at StackOverflowErrorExample.recursivePrint(StackOverflowErrorExample.java:9)\n ...\n StackOverflowError -Xss -Xss -Xss<size>[g|G|m|M|k|K]"
},
{
"answer_id": 35351814,
"author": "John S.",
"author_id": 4975918,
"author_profile": "https://Stackoverflow.com/users/4975918",
"pm_score": 0,
"selected": false,
"text": "public static void main(String[] args) {\n System.out.println(add5(1));\n}\n\npublic static int add5(int a) {\n return add5(a) + 5;\n}\n add5(a)"
},
{
"answer_id": 43116131,
"author": "Rahul Sah",
"author_id": 4501631,
"author_profile": "https://Stackoverflow.com/users/4501631",
"pm_score": 3,
"selected": false,
"text": "StackOverflowError StackOverflowError public class Factorial {\n public static int factorial(int n){\n if(n == 1){\n return 1;\n }\n else{\n return n * factorial(n-1);\n }\n }\n\n public static void main(String[] args){\n System.out.println(\"Main method started\");\n int result = Factorial.factorial(-1);\n System.out.println(\"Factorial ==>\"+result);\n System.out.println(\"Main method ended\");\n }\n}\n Main method started\nException in thread \"main\" java.lang.StackOverflowError\nat com.program.stackoverflow.Factorial.factorial(Factorial.java:9)\nat com.program.stackoverflow.Factorial.factorial(Factorial.java:9)\nat com.program.stackoverflow.Factorial.factorial(Factorial.java:9)\n"
},
{
"answer_id": 49611422,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "java.lang.StackOverflowError doubleValue() floatValue() public class Rational extends Number implements Comparable<Rational> {\n private int num;\n private int denom;\n\n public Rational(int num, int denom) {\n this.num = num;\n this.denom = denom;\n }\n\n public int compareTo(Rational r) {\n if ((num / denom) - (r.num / r.denom) > 0) {\n return +1;\n } else if ((num / denom) - (r.num / r.denom) < 0) {\n return -1;\n }\n return 0;\n }\n\n public Rational add(Rational r) {\n return new Rational(num + r.num, denom + r.denom);\n }\n\n public Rational sub(Rational r) {\n return new Rational(num - r.num, denom - r.denom);\n }\n\n public Rational mul(Rational r) {\n return new Rational(num * r.num, denom * r.denom);\n }\n\n public Rational div(Rational r) {\n return new Rational(num * r.denom, denom * r.num);\n }\n\n public int gcd(Rational r) {\n int i = 1;\n while (i != 0) {\n i = denom % r.denom;\n denom = r.denom;\n r.denom = i;\n }\n return denom;\n }\n\n public String toString() {\n String a = num + \"/\" + denom;\n return a;\n }\n\n public double doubleValue() {\n return (double) doubleValue();\n }\n\n public float floatValue() {\n return (float) floatValue();\n }\n\n public int intValue() {\n return (int) intValue();\n }\n\n public long longValue() {\n return (long) longValue();\n }\n}\n public class Main {\n\n public static void main(String[] args) {\n\n Rational a = new Rational(2, 4);\n Rational b = new Rational(2, 6);\n\n System.out.println(a + \" + \" + b + \" = \" + a.add(b));\n System.out.println(a + \" - \" + b + \" = \" + a.sub(b));\n System.out.println(a + \" * \" + b + \" = \" + a.mul(b));\n System.out.println(a + \" / \" + b + \" = \" + a.div(b));\n\n Rational[] arr = {new Rational(7, 1), new Rational(6, 1),\n new Rational(5, 1), new Rational(4, 1),\n new Rational(3, 1), new Rational(2, 1),\n new Rational(1, 1), new Rational(1, 2),\n new Rational(1, 3), new Rational(1, 4),\n new Rational(1, 5), new Rational(1, 6),\n new Rational(1, 7), new Rational(1, 8),\n new Rational(1, 9), new Rational(0, 1)};\n\n selectSort(arr);\n\n for (int i = 0; i < arr.length - 1; ++i) {\n if (arr[i].compareTo(arr[i + 1]) > 0) {\n System.exit(1);\n }\n }\n\n\n Number n = new Rational(3, 2);\n\n System.out.println(n.doubleValue());\n System.out.println(n.floatValue());\n System.out.println(n.intValue());\n System.out.println(n.longValue());\n }\n\n public static <T extends Comparable<? super T>> void selectSort(T[] array) {\n\n T temp;\n int mini;\n\n for (int i = 0; i < array.length - 1; ++i) {\n\n mini = i;\n\n for (int j = i + 1; j < array.length; ++j) {\n if (array[j].compareTo(array[mini]) < 0) {\n mini = j;\n }\n }\n\n if (i != mini) {\n temp = array[i];\n array[i] = array[mini];\n array[mini] = temp;\n }\n }\n }\n}\n 2/4 + 2/6 = 4/10\nException in thread \"main\" java.lang.StackOverflowError\n2/4 - 2/6 = 0/-2\n at com.xetrasu.Rational.doubleValue(Rational.java:64)\n2/4 * 2/6 = 4/24\n at com.xetrasu.Rational.doubleValue(Rational.java:64)\n2/4 / 2/6 = 12/8\n at com.xetrasu.Rational.doubleValue(Rational.java:64)\n at com.xetrasu.Rational.doubleValue(Rational.java:64)\n at com.xetrasu.Rational.doubleValue(Rational.java:64)\n at com.xetrasu.Rational.doubleValue(Rational.java:64)\n at com.xetrasu.Rational.doubleValue(Rational.java:64)\n StackOverflowError"
},
{
"answer_id": 60416391,
"author": "Kaliappan",
"author_id": 1872207,
"author_profile": "https://Stackoverflow.com/users/1872207",
"pm_score": 2,
"selected": false,
"text": "public class Example3 {\n\n public static void main(String[] args) {\n\n main(new String[1]);\n }\n\n}\n"
},
{
"answer_id": 62813612,
"author": "MrIo",
"author_id": 13695519,
"author_profile": "https://Stackoverflow.com/users/13695519",
"pm_score": 2,
"selected": false,
"text": "$ ulimit -u int array[10000][10000]; StackOverflowError ulimit -s 32768 alloc()"
},
{
"answer_id": 65977273,
"author": "Yuresh Karunanayake",
"author_id": 8009264,
"author_profile": "https://Stackoverflow.com/users/8009264",
"pm_score": 1,
"selected": false,
"text": "class Human {\n Human(){\n new Animal();\n }\n}\n\nclass Animal extends Human {\n Animal(){\n super();\n }\n}\n\npublic class Test01 {\n public static void main(String[] args) {\n new Animal();\n }\n}\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29182/"
] |
214,746
|
<p>I am writing an .NET wrapper API for the Netflix API.</p>
<p>At this point I can choose to represent URLs as either strings or URI objects. Seems to me there is a good case for both.</p>
<p>So if you were using an API, which would you prefer?</p>
|
[
{
"answer_id": 214801,
"author": "Domenic",
"author_id": 3191,
"author_profile": "https://Stackoverflow.com/users/3191",
"pm_score": 0,
"selected": false,
"text": "string Uri UriFormatException Uri"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5274/"
] |
214,748
|
<p>Please bear with me here, I'm a student and new to Java Server Pages.
If I'm being a complete idiot, can someone give me a good link to a tutorial on JSP, since I've been unable to find info on this anywhere. </p>
<p>Okay, here goes... </p>
<p>I'm using Netbeans and trying to pass an object that connects to a database between the pages, otherwise I'd have to reconnect to the database every time a new page is displayed. </p>
<p>Using Netbeans, you can view each page as "jsp", in "design" view, or view the Java code. In the Java code is the class that extends an AbstractPageBean. The problem is that I'd like to pass parameters, but there is no object representing the class and so I can't just access the instance variables. </p>
<p>Can anyone tell me how to do this? </p>
|
[
{
"answer_id": 214835,
"author": "extraneon",
"author_id": 24582,
"author_profile": "https://Stackoverflow.com/users/24582",
"pm_score": 3,
"selected": true,
"text": "public class FooRepo {\n public static Foo getFoo(Long id) {\n // Read resultSet into foo\n }\n }\n Foo = FooRepo.getFoo( id as stored in JSP );\n// display foo\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25280/"
] |
214,764
|
<p>In my Java development I have had great benefit from the <a href="http://en.wikipedia.org/wiki/JAD_%28JAva_Decompiler%29" rel="noreferrer">Jad/JadClipse</a> decompiler. It made it possible to <em>know</em> why a third-party library failed rather than the usual guesswork.</p>
<p>I am looking for a similar setup for C# and Visual Studio. That is, a setup where I can point to any class or variable in my code and get a code view for that particular class.</p>
<p>What is the best setup for this? I want to be able to use the usual "jump to declaration/implementation" that I use to navigate my own code. It doesn't <em>have</em> to be free, but it would be a bonus if it was.</p>
<p>It should support Visual Studio 2008 or Visual Studio 2005 and .NET 2 and 3(.5).</p>
|
[
{
"answer_id": 214784,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 1,
"selected": false,
"text": "bin"
},
{
"answer_id": 214788,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 5,
"selected": true,
"text": "Reflector.VisualStudio.exe /install\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24610/"
] |
214,777
|
<p>For example, I'm trying to convert 2008-09-26T01:51:42.000Z to 09/26/2008. What's the simplest way of accomplishing this?</p>
|
[
{
"answer_id": 214786,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 5,
"selected": false,
"text": ">>> import time\n>>> timestamp = \"2008-09-26T01:51:42.000Z\"\n>>> ts = time.strptime(timestamp[:19], \"%Y-%m-%dT%H:%M:%S\")\n>>> time.strftime(\"%m/%d/%Y\", ts)\n'09/26/2008'\n time"
},
{
"answer_id": 215083,
"author": "olt",
"author_id": 19759,
"author_profile": "https://Stackoverflow.com/users/19759",
"pm_score": 2,
"selected": false,
"text": "2008-09-26T01:51:42.000Z"
},
{
"answer_id": 215313,
"author": "Jeremy Cantrell",
"author_id": 18866,
"author_profile": "https://Stackoverflow.com/users/18866",
"pm_score": 7,
"selected": true,
"text": "import dateutil.parser\n\nd = dateutil.parser.parse('2008-09-26T01:51:42.000Z')\nprint(d.strftime('%m/%d/%Y')) #==> '09/26/2008'\n"
},
{
"answer_id": 2904561,
"author": "Dhaval dave",
"author_id": 339255,
"author_profile": "https://Stackoverflow.com/users/339255",
"pm_score": -1,
"selected": false,
"text": "def datechange(datestr):\ndateobj=datestr.split('-')\ny=dateobj[0]\nm=dateobj[1]\nd=dateobj[2]\ndatestr=d +'-'+ m +'-'+y\nreturn datestr\n"
},
{
"answer_id": 39155014,
"author": "mhoang",
"author_id": 6758992,
"author_profile": "https://Stackoverflow.com/users/6758992",
"pm_score": 6,
"selected": false,
"text": ">>> from datetime import datetime\n>>> date_format = \"%Y-%m-%dT%H:%M:%S.%fZ\" \n>>> datetime.strptime('2008-09-26T01:51:42.000Z', date_format)\ndatetime.datetime(2008, 9, 26, 1, 51, 42)\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10708/"
] |
214,825
|
<p>My colleague insists on explicitly specifying the namespace in code as opposed to using the <a href="http://msdn.microsoft.com/en-us/library/sf0df423.aspx" rel="noreferrer">using directive</a>. In other words he wants to use the fully qualified name for each type every time this type occurs in code. Something like </p>
<pre><code>public class MyClass
{
public static void Main()
{
System.Console.WriteLine("Foo");
}
}
</code></pre>
<p>instead of:</p>
<pre><code>using System;
public class MyClass
{
public static void Main()
{
Console.WriteLine("Foo");
}
}
</code></pre>
<p>You can imagine the consequences.</p>
<p>The pros he gives: </p>
<ol>
<li>It's simpler to copy and paste code into other source files. </li>
<li>It is more readable (you see the namespaces right away). </li>
</ol>
<p>My cons:</p>
<ol>
<li>I have to write more </li>
<li>The code is less readable (I guess de gustibus non disputandum est) </li>
<li>No one does it! </li>
</ol>
<p>What do you think about this?</p>
|
[
{
"answer_id": 214827,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 0,
"selected": false,
"text": "Law of Demeter jQuery JavaScript"
},
{
"answer_id": 214828,
"author": "Jesper Blad Jensen",
"author_id": 11559,
"author_profile": "https://Stackoverflow.com/users/11559",
"pm_score": 3,
"selected": false,
"text": "using"
},
{
"answer_id": 214845,
"author": "rslite",
"author_id": 15682,
"author_profile": "https://Stackoverflow.com/users/15682",
"pm_score": 0,
"selected": false,
"text": "Namespace1.Namespace2.Namespace3.Type var = new Namespace1.Namespace2.Namespace3.Type(par1, par2, par3);\n Type var = new Type(par1, par2, par3);\n"
},
{
"answer_id": 214945,
"author": "user10178",
"author_id": 10178,
"author_profile": "https://Stackoverflow.com/users/10178",
"pm_score": 1,
"selected": false,
"text": "using diagAlias = System.Diagnostics;\n\nnamespace ConsoleApplication1\n{\n class Program\n {\n static void Main(string[] args)\n {\n diagAlias.Debug.Write(\"\");\n }\n }\n}\n"
},
{
"answer_id": 215005,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 4,
"selected": false,
"text": "Module Module1\n\n Sub Main()\n Dim Rgx As New System.Text.RegularExpressions.Regex(\"Pattern\", _\n System.Text.RegularExpressions.RegexOptions.IgnoreCase _\n Or System.Text.RegularExpressions.RegexOptions.Singleline _\n Or System.Text.RegularExpressions.RegexOptions.IgnorePatternWhitespace)\n\n\n For Each result As System.Text.RegularExpressions.Match In Rgx.Matches(\"Find pattern here.\")\n 'Do Something\n Next\n End Sub\n\nEnd Module\n Imports System.Text.RegularExpressions\n\nModule Module1\n\n Sub Main()\n Dim Rgx As New Regex(\"Pattern\", _\n RegexOptions.IgnoreCase _\n Or RegexOptions.Singleline _\n Or RegexOptions.IgnorePatternWhitespace)\n\n\n For Each result As Match In Rgx.Matches(\"Find pattern here.\")\n 'Do Something\n Next\n End Sub\n\nEnd Module\n"
},
{
"answer_id": 215734,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 0,
"selected": false,
"text": "using System.Xml.Serialization.XmlSerializationReader"
},
{
"answer_id": 2030887,
"author": "Brian",
"author_id": 18192,
"author_profile": "https://Stackoverflow.com/users/18192",
"pm_score": 0,
"selected": false,
"text": "using"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28722/"
] |
214,843
|
<p>I have two projects in CPP. One defines a function which I'd like to invoke from the other.
I added a reference to the first project.
I still get the message of "identifier not found".
Assuming that the CPP file in the first project doesn't have a header, how do I make the second project know about its functions?</p>
|
[
{
"answer_id": 214846,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 1,
"selected": false,
"text": "extern extern function_in_first_project(int args_go_here);\n"
},
{
"answer_id": 216307,
"author": "Nathan Fellman",
"author_id": 1084,
"author_profile": "https://Stackoverflow.com/users/1084",
"pm_score": 0,
"selected": false,
"text": "#include \"first_project_header_file.h\"\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214843",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
214,850
|
<p>What is the best solution to sanitize output HTML in Rails (to avoid XSS attacks)?</p>
<p>I have two options: white_list plugin or sanitize method from Sanitize Helper <a href="http://api.rubyonrails.com/classes/ActionView/Helpers/SanitizeHelper.html" rel="nofollow noreferrer">http://api.rubyonrails.com/classes/ActionView/Helpers/SanitizeHelper.html</a> . For me until today the white_list plugin worked better and in the past, Sanitize was very buggy, but as part of the Core, probably it will be under development and be supported for a while.</p>
|
[
{
"answer_id": 237778,
"author": "derfred",
"author_id": 10286,
"author_profile": "https://Stackoverflow.com/users/10286",
"pm_score": 2,
"selected": true,
"text": "<%= h @user.profile %>\n"
},
{
"answer_id": 239336,
"author": "Gareth",
"author_id": 31582,
"author_profile": "https://Stackoverflow.com/users/31582",
"pm_score": 0,
"selected": false,
"text": "</td></tr></span></div>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18642/"
] |
214,852
|
<p>Is there a way to make a python module load a dll in my application directory rather than the version that came with the python installation, without making changes to the python installation (which would then require I made an installer, and be careful I didn't break other apps for people by overwrting python modules and changing dll versions globaly...)?</p>
<p>Specifically I would like python to use my version of the sqlite3.dll, rather than the version that came with python (which is older and doesn't appear to have the fts3 module).</p>
|
[
{
"answer_id": 214855,
"author": "André",
"author_id": 9683,
"author_profile": "https://Stackoverflow.com/users/9683",
"pm_score": 0,
"selected": false,
"text": "PYTHONPATH"
},
{
"answer_id": 214868,
"author": "Glyph",
"author_id": 13564,
"author_profile": "https://Stackoverflow.com/users/13564",
"pm_score": 5,
"selected": false,
"text": "sys.path libfoo.dll foo.pyd import os\nos.environ['PATH'] = 'my-app-dir' + os.pathsep + os.environ['PATH']\n my-app-dir sqlite3.dll"
},
{
"answer_id": 64303856,
"author": "Andrei Smeltsov",
"author_id": 4667032,
"author_profile": "https://Stackoverflow.com/users/4667032",
"pm_score": 4,
"selected": false,
"text": "os.environ['PATH'] os.add_dll_directory import os\nos.add_dll_directory('my-app-dir')\n import os\nos.environ['PATH'] = 'my-app-dir' + os.pathsep + os.environ['PATH']\n"
},
{
"answer_id": 74645015,
"author": "Olivier Le Doeuff",
"author_id": 12334315,
"author_profile": "https://Stackoverflow.com/users/12334315",
"pm_score": 0,
"selected": false,
"text": ".pyd def add_cuda_to_path():\n if os.name != \"nt\":\n return\n path = os.getenv(\"PATH\")\n if not path:\n return\n path_split = path.split(\";\")\n for folder in path_split:\n if \"cuda\" in folder.lower() or \"tensorrt\" in folder.lower():\n os.add_dll_directory(folder)\n .dll add_cuda_to_path()\nimport my_module_that_depends_on_cuda\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6266/"
] |
214,862
|
<p>I have an Internet Explorer only web application.</p>
<p>I'm exploring what we can do to automate the testing. </p>
<p>Selenium looks like a good tool, but to be able to activate links etc. I need to tell it where they are. The application wasn't built with this kind of testing in mind, so there generally aren't <code>id</code> attributes on the key elements.</p>
<p>No problem, I think, I can use XPath expressions. But finding the correct XPath for, say, a button, is a royal pain if done by inspecting the source of the page.</p>
<p>With Firefox / Firebug, I can select the element then use "Copy XPath" to get the expression.</p>
<p>I have the IE Developer Toolbar and it's frustratingly close. I can click to select the element of interest and display all sorts of information about it. but I can't see any convenient way of determining the XPath for it.</p>
<p>So is there any way of doing this with IE?</p>
|
[
{
"answer_id": 215091,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 4,
"selected": true,
"text": "function getNode(node)\n{\n var nodeExpr = node.tagName;\n if (nodeExpr == null) // Eg. node = #text\n return null;\n if (node.id != '')\n {\n nodeExpr += \"[@id='\" + node.id + \"']\";\n // We don't really need to go back up to //HTML, since IDs are supposed\n // to be unique, so they are a good starting point.\n return \"/\" + nodeExpr;\n }\n// We don't really need this\n//~ if (node.className != '')\n//~ {\n//~ nodeExpr += \"[@class='\" + node.className + \"']\";\n//~ }\n // Find rank of node among its type in the parent\n var rank = 1;\n var ps = node.previousSibling;\n while (ps != null)\n {\n if (ps.tagName == node.tagName)\n {\n rank++;\n }\n ps = ps.previousSibling;\n }\n if (rank > 1)\n {\n nodeExpr += '[' + rank + ']';\n }\n else\n {\n // First node of its kind at this level. Are there any others?\n var ns = node.nextSibling;\n while (ns != null)\n {\n if (ns.tagName == node.tagName)\n {\n // Yes, mark it as being the first one\n nodeExpr += '[1]';\n break;\n }\n ns = ns.nextSibling;\n }\n }\n return nodeExpr;\n}\n\nvar currentNode;\n// Standard (?)\nif (window.getSelection != undefined) \n currentNode = window.getSelection().anchorNode;\n// IE (if no selection, that's BODY)\nelse \n currentNode = document.selection.createRange().parentElement();\nif (currentNode == null)\n{\n alert(\"No selection\");\n return;\n}\nvar path = [];\n// Walk up the Dom\nwhile (currentNode != undefined)\n{\n var pe = getNode(currentNode);\n if (pe != null)\n {\n path.push(pe);\n if (pe.indexOf('@id') != -1)\n break; // Found an ID, no need to go upper, absolute path is OK\n }\n currentNode = currentNode.parentNode;\n}\nvar xpath = \"/\" + path.reverse().join('/');\nalert(xpath);\n// Copy to clipboard\n// IE\nif (window.clipboardData) clipboardData.setData(\"Text\", xpath);\n// FF's code to handle clipboard is much more complex \n// and might need to change prefs to allow changing the clipboard content.\n// I omit it here as it isn't part of the original request.\n javascript:function getNode(node){var nodeExpr=node.tagName;if(!nodeExpr)return null;if(node.id!=''){nodeExpr+=\"[@id='\"+node.id+\"']\";return \"/\"+nodeExpr;}var rank=1;var ps=node.previousSibling;while(ps){if(ps.tagName==node.tagName){rank++;}ps=ps.previousSibling;}if(rank>1){nodeExpr+='['+rank+']';}else{var ns=node.nextSibling;while(ns){if(ns.tagName==node.tagName){nodeExpr+='[1]';break;}ns=ns.nextSibling;}}return nodeExpr;}\njavascript:function o__o(){var currentNode=document.selection.createRange().parentElement();var path=[];while(currentNode){var pe=getNode(currentNode);if(pe){path.push(pe);if(pe.indexOf('@id')!=-1)break;}currentNode=currentNode.parentNode;}var xpath=\"/\"+path.reverse().join('/');clipboardData.setData(\"Text\", xpath);}o__o();\n javascript:function o__o(){function getNode(node){var nodeExpr=node.tagName;if(nodeExpr==null)return null;if(node.id!=''){nodeExpr+=\"[@id='\"+node.id+\"']\";return \"/\"+nodeExpr;}var rank=1;var ps=node.previousSibling;while(ps!=null){if(ps.tagName==node.tagName){rank++;}ps=ps.previousSibling;}if(rank>1){nodeExpr+='['+rank+']';}else{var ns=node.nextSibling;while(ns!=null){if(ns.tagName==node.tagName){nodeExpr+='[1]';break;}ns=ns.nextSibling;}}return nodeExpr;}var currentNode=window.getSelection().anchorNode;if(currentNode==null){alert(\"No selection\");return;}var path=[];while(currentNode!=undefined){var pe=getNode(currentNode);if(pe!=null){path.push(pe);if(pe.indexOf('@id')!=-1)break;}currentNode=currentNode.parentNode;}var xpath=\"/\"+path.reverse().join('/');alert(xpath);}o__o();\n"
},
{
"answer_id": 217711,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 2,
"selected": false,
"text": "javascript: alert(\"Hello world!\"); alert var"
},
{
"answer_id": 5452009,
"author": "Pěna",
"author_id": 679290,
"author_profile": "https://Stackoverflow.com/users/679290",
"pm_score": 2,
"selected": false,
"text": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Text;\n\nnamespace Anotation.Toolbar\n{\n class XPath\n {\n public static string getXPath(mshtml.IHTMLElement element)\n {\n if (element == null)\n return \"\";\n mshtml.IHTMLElement currentNode = element;\n ArrayList path = new ArrayList();\n\n while (currentNode != null)\n {\n string pe = getNode(currentNode);\n if (pe != null)\n {\n path.Add(pe);\n if (pe.IndexOf(\"@id\") != -1)\n break; // Found an ID, no need to go upper, absolute path is OK\n }\n currentNode = currentNode.parentElement;\n }\n path.Reverse();\n return join(path, \"/\");\n }\n\n private static string join(ArrayList items, string delimiter)\n {\n StringBuilder sb = new StringBuilder();\n foreach (object item in items)\n {\n if (item == null)\n continue;\n\n sb.Append(delimiter);\n sb.Append(item);\n }\n return sb.ToString();\n }\n\n private static string getNode(mshtml.IHTMLElement node)\n {\n string nodeExpr = node.tagName;\n if (nodeExpr == null) // Eg. node = #text\n return null;\n if (node.id != \"\" && node.id != null)\n {\n nodeExpr += \"[@id='\" + node.id + \"']\";\n // We don't really need to go back up to //HTML, since IDs are supposed\n // to be unique, so they are a good starting point.\n return \"/\" + nodeExpr;\n }\n\n // Find rank of node among its type in the parent\n int rank = 1;\n mshtml.IHTMLDOMNode nodeDom = node as mshtml.IHTMLDOMNode;\n mshtml.IHTMLDOMNode psDom = nodeDom.previousSibling;\n mshtml.IHTMLElement ps = psDom as mshtml.IHTMLElement;\n while (ps != null)\n {\n if (ps.tagName == node.tagName)\n {\n rank++;\n }\n psDom = psDom.previousSibling;\n ps = psDom as mshtml.IHTMLElement;\n }\n if (rank > 1)\n {\n nodeExpr += \"[\" + rank + \"]\";\n }\n else\n { // First node of its kind at this level. Are there any others?\n mshtml.IHTMLDOMNode nsDom = nodeDom.nextSibling;\n mshtml.IHTMLElement ns = nsDom as mshtml.IHTMLElement;\n while (ns != null)\n {\n if (ns.tagName == node.tagName)\n { // Yes, mark it as being the first one\n nodeExpr += \"[1]\";\n break;\n }\n nsDom = nsDom.nextSibling;\n ns = nsDom as mshtml.IHTMLElement;\n }\n }\n return nodeExpr;\n }\n }\n}\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21755/"
] |
214,881
|
<p>Can you add new statements (like <code>print</code>, <code>raise</code>, <code>with</code>) to Python's syntax?</p>
<p>Say, to allow..</p>
<pre><code>mystatement "Something"
</code></pre>
<p>Or,</p>
<pre><code>new_if True:
print "example"
</code></pre>
<p>Not so much if you <em>should</em>, but rather if it's possible (short of modifying the python interpreters code)</p>
|
[
{
"answer_id": 215042,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 2,
"selected": false,
"text": "Python/ast.c"
},
{
"answer_id": 215697,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 6,
"selected": false,
"text": "myprint \"This gets logged to file\"\n print >>open('/tmp/logfile.txt','a'), \"This gets logged to file\"\n import tokenize\n\nLOGFILE = '/tmp/log.txt'\ndef translate(readline):\n for type, name,_,_,_ in tokenize.generate_tokens(readline):\n if type ==tokenize.NAME and name =='myprint':\n yield tokenize.NAME, 'print'\n yield tokenize.OP, '>>'\n yield tokenize.NAME, \"open\"\n yield tokenize.OP, \"(\"\n yield tokenize.STRING, repr(LOGFILE)\n yield tokenize.OP, \",\"\n yield tokenize.STRING, \"'a'\"\n yield tokenize.OP, \")\"\n yield tokenize.OP, \",\"\n else:\n yield type,name\n import new\ndef myimport(filename):\n mod = new.module(filename)\n f=open(filename)\n data = tokenize.untokenize(translate(f.readline))\n exec data in mod.__dict__\n return mod\n some_mod = myimport(\"some_mod.py\") import some_mod import codecs, cStringIO, encodings\nfrom encodings import utf_8\n\nclass StreamReader(utf_8.StreamReader):\n def __init__(self, *args, **kwargs):\n codecs.StreamReader.__init__(self, *args, **kwargs)\n data = tokenize.untokenize(translate(self.stream.readline))\n self.stream = cStringIO.StringIO(data)\n\ndef search_function(s):\n if s!='mylang': return None\n utf8=encodings.search_function('utf8') # Assume utf8 encoding\n return codecs.CodecInfo(\n name='mylang',\n encode = utf8.encode,\n decode = utf8.decode,\n incrementalencoder=utf8.incrementalencoder,\n incrementaldecoder=utf8.incrementaldecoder,\n streamreader=StreamReader,\n streamwriter=utf8.streamwriter)\n\ncodecs.register(search_function)\n # coding: mylang\nmyprint \"this gets logged to file\"\nfor i in range(10):\n myprint \"so does this : \", i, \"times\"\nmyprint (\"works fine\" \"with arbitrary\" + \" syntax\" \n \"and line continuations\")\n"
},
{
"answer_id": 216795,
"author": "Constantin",
"author_id": 20310,
"author_profile": "https://Stackoverflow.com/users/20310",
"pm_score": 4,
"selected": false,
"text": "sys.settrace() goto comefrom from goto import goto, label\nfor i in range(1, 10):\n for j in range(1, 20):\n print i, j\n if j == 3:\n goto .end # breaking out from nested loop\nlabel .end\nprint \"Finished\"\n"
},
{
"answer_id": 220857,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "import EasyExtend\nEasyExtend.new_langlet(\"mystmts\", prompt = \"my> \", source_ext = \"mypy\")\n small_stmt: (expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt |\n import_stmt | global_stmt | exec_stmt | assert_stmt | my_stmt )\n\nmy_stmt: 'mystatement' expr\n def call_my_stmt(expression):\n \"defines behaviour for my_stmt\"\n print \"my stmt called with\", expression\n\n class LangletTransformer(Transformer):\n @transform\n def my_stmt(self, node):\n _expr = find_node(node, symbol.expr)\n return any_stmt(CST_CallFunc(\"call_my_stmt\", [_expr]))\n\n __publish__ = [\"call_my_stmt\"]\n python run_mystmts.py\n __________________________________________________________________________________\n\n mystmts\n\n On Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)]\n __________________________________________________________________________________\n\n my> mystatement 40+2\n my stmt called with 42\n"
},
{
"answer_id": 4572994,
"author": "jcomeau_ictx",
"author_id": 493161,
"author_profile": "https://Stackoverflow.com/users/493161",
"pm_score": 4,
"selected": false,
"text": "\njcomeau@intrepid:~/$ cat demo.py; ./demo.py\n#!/usr/bin/python -i\n'load everything needed under \"package\", such as package.common.normalize()'\nimport os, sys, readline, traceback\nif __name__ == '__main__':\n class t:\n @staticmethod\n def localfunction(*args):\n print 'this is a test'\n if args:\n print 'ignoring %s' % repr(args)\n\n def displayhook(whatever):\n if hasattr(whatever, 'localfunction'):\n return whatever.localfunction()\n else:\n print whatever\n\n def excepthook(exctype, value, tb):\n if exctype is SyntaxError:\n index = readline.get_current_history_length()\n item = readline.get_history_item(index)\n command = item.split()\n print 'command:', command\n if len(command[0]) == 1:\n try:\n eval(command[0]).localfunction(*command[1:])\n except:\n traceback.print_exception(exctype, value, tb)\n else:\n traceback.print_exception(exctype, value, tb)\n\n sys.displayhook = displayhook\n sys.excepthook = excepthook\n>>> t\nthis is a test\n>>> t t\ncommand: ['t', 't']\nthis is a test\nignoring ('t',)\n>>> ^D\n\n"
},
{
"answer_id": 9108164,
"author": "Eli Bendersky",
"author_id": 8206,
"author_profile": "https://Stackoverflow.com/users/8206",
"pm_score": 9,
"selected": true,
"text": "until until until while until num == 0 while num != 0 num = 3\nuntil num == 0 do\n puts num\n num -= 1\nend\n 3\n2\n1\n num = 3\nuntil num == 0:\n print(num)\n num -= 1\n until pgen Grammar/Grammar until while while_stmt until_stmt compound_stmt: if_stmt | while_stmt | until_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef | decorated\nif_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]\nwhile_stmt: 'while' test ':' suite ['else' ':' suite]\nuntil_stmt: 'until' test ':' suite\n while until else until else compound_stmt until_stmt while_stmt make Grammar/Grammar pgen Include/graminit.h Python/graminit.c Parser/Python.asdl until while | While(expr test, stmt* body, stmt* orelse)\n| Until(expr test, stmt* body)\n make Parser/asdl_c.py Grammar/Grammar Parser/asdl_c.py Parser/asdl_c.py Include/Python-ast.h Python/Python-ast.c Python/ast.c ast_for_stmt while switch until_stmt case while_stmt:\n return ast_for_while_stmt(c, ch);\ncase until_stmt:\n return ast_for_until_stmt(c, ch);\n ast_for_until_stmt static stmt_ty\nast_for_until_stmt(struct compiling *c, const node *n)\n{\n /* until_stmt: 'until' test ':' suite */\n REQ(n, until_stmt);\n\n if (NCH(n) == 4) {\n expr_ty expression;\n asdl_seq *suite_seq;\n\n expression = ast_for_expr(c, CHILD(n, 1));\n if (!expression)\n return NULL;\n suite_seq = ast_for_suite(c, CHILD(n, 3));\n if (!suite_seq)\n return NULL;\n return Until(expression, suite_seq, LINENO(n), n->n_col_offset, c->c_arena);\n }\n\n PyErr_Format(PyExc_SystemError,\n \"wrong number of tokens for 'until' statement: %d\",\n NCH(n));\n return NULL;\n}\n ast_for_while_stmt until else ast_for_expr ast_for_suite until Until n NCH CHILD Include/node.h until until condition:\n # do stuff\n while not condition:\n # do stuff\n Until ast_for_until_stmt Not While Python/compile.c while compiler_visit_stmt Until case While_kind:\n return compiler_while(c, s);\ncase Until_kind:\n return compiler_until(c, s);\n Until_kind _stmt_kind Include/Python-ast.h compiler_until compiler_visit_stmt grep VISIT Python/compile.c #define VISIT(C, TYPE, V) {\\\n if (!compiler_visit_ ## TYPE((C), (V))) \\\n return 0; \\\n compiler_visit_stmt compiler_body compiler_until static int\ncompiler_until(struct compiler *c, stmt_ty s)\n{\n basicblock *loop, *end, *anchor = NULL;\n int constant = expr_constant(s->v.Until.test);\n\n if (constant == 1) {\n return 1;\n }\n loop = compiler_new_block(c);\n end = compiler_new_block(c);\n if (constant == -1) {\n anchor = compiler_new_block(c);\n if (anchor == NULL)\n return 0;\n }\n if (loop == NULL || end == NULL)\n return 0;\n\n ADDOP_JREL(c, SETUP_LOOP, end);\n compiler_use_next_block(c, loop);\n if (!compiler_push_fblock(c, LOOP, loop))\n return 0;\n if (constant == -1) {\n VISIT(c, expr, s->v.Until.test);\n ADDOP_JABS(c, POP_JUMP_IF_TRUE, anchor);\n }\n VISIT_SEQ(c, stmt, s->v.Until.body);\n ADDOP_JABS(c, JUMP_ABSOLUTE, loop);\n\n if (constant == -1) {\n compiler_use_next_block(c, anchor);\n ADDOP(c, POP_BLOCK);\n }\n compiler_pop_fblock(c, LOOP, loop);\n compiler_use_next_block(c, end);\n\n return 1;\n}\n compiler_while dis make until >>> until num == 0:\n... print(num)\n... num -= 1\n...\n3\n2\n1\n dis import dis\n\ndef myfoo(num):\n until num == 0:\n print(num)\n num -= 1\n\ndis.dis(myfoo)\n 4 0 SETUP_LOOP 36 (to 39)\n >> 3 LOAD_FAST 0 (num)\n 6 LOAD_CONST 1 (0)\n 9 COMPARE_OP 2 (==)\n 12 POP_JUMP_IF_TRUE 38\n\n5 15 LOAD_NAME 0 (print)\n 18 LOAD_FAST 0 (num)\n 21 CALL_FUNCTION 1\n 24 POP_TOP\n\n6 25 LOAD_FAST 0 (num)\n 28 LOAD_CONST 2 (1)\n 31 INPLACE_SUBTRACT\n 32 STORE_FAST 0 (num)\n 35 JUMP_ABSOLUTE 3\n >> 38 POP_BLOCK\n >> 39 LOAD_CONST 0 (None)\n 42 RETURN_VALUE\n until myfoo(3) Traceback (most recent call last):\n File \"zy.py\", line 9, in\n myfoo(3)\n File \"zy.py\", line 5, in myfoo\n print(num)\nSystemError: no locals when loading 'print'\n PySymtable_Build PyAST_Compile Python/symtable.c symtable_visit_stmt Python/symtable.c until while case While_kind:\n VISIT(st, expr, s->v.While.test);\n VISIT_SEQ(st, stmt, s->v.While.body);\n if (s->v.While.orelse)\n VISIT_SEQ(st, stmt, s->v.While.orelse);\n break;\ncase Until_kind:\n VISIT(st, expr, s->v.Until.test);\n VISIT_SEQ(st, stmt, s->v.Until.body);\n break;\n Python/symtable.c Until_kind symtable_visit_stmt myfoo(3)"
},
{
"answer_id": 27841742,
"author": "kdb",
"author_id": 2075630,
"author_profile": "https://Stackoverflow.com/users/2075630",
"pm_score": 2,
"selected": false,
"text": "with # ====== Implementation of \"mywith\" decorator ======\n\ndef mywith(stream):\n def decorator(function):\n try: function(stream)\n finally: stream.close()\n return decorator\n\n# ====== Using the decorator ======\n\n@mywith(open(\"test.py\",\"r\"))\ndef _(infile):\n for l in infile.readlines():\n print(\">>\", l.rstrip())\n _ None def _(infile): ...\n_ = mywith(open(...))(_) # mywith returns None.\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/745/"
] |
214,884
|
<p>I have a class on which I want to allow several (~20+) configuration options.
Each option turns on or off a piece of functionality, or otherwise alters operations.
To facilitate this, I coded a separate options class with default values. However, I had to litter my code with guard conditions to determine how methods should behave. I am almost done, but now the code seems to smell.</p>
<p>Is there a preferred method/pattern to implement a class like this?</p>
<p><strong>EDIT:</strong> More specifically, I am working on a parsing class.
Each option configures mutually exclusive portions of the basic parsing algorithm.
For example I have several areas in my class that look like the below:</p>
<pre><code> if (this.Option.UseIdAttribute)
attributeIDs = new Hashtable();
else
attributeIDs = null;
public Element GetElementById(string id)
{
if (string.IsNullOrEmpty (id))
throw new ArgumentNullException("id");
if (attributeIDs == null)
throw new Exception(ExceptionUseIdAttributeFalse);
return attributeIDs[id.ToLower()] as Element;
}
</code></pre>
|
[
{
"answer_id": 214949,
"author": "extraneon",
"author_id": 24582,
"author_profile": "https://Stackoverflow.com/users/24582",
"pm_score": 0,
"selected": false,
"text": " public class MyClass {\n\n interface Command {\n void execute(int a);\n }\n\n static class DoThisSimpleCommand implements Command {\n void execute(int a) {\n // do this simple\n }\n }\n\n static class DoThisAnotherWayCommand implements Command {\n void execute(int a) {\n // do this another way\n }\n }\n\n private Command doThisCommand;\n\n MyClass() {\n initDoThisCommand();\n }\n\n private void initDoThisCommand() {\n if (config.getDoThisMethod().equals(\"simple\")) {\n doThisCommand = new DoThisSimpleCommand();\n } else {\n doThisCommand = new DoThisAnotherWayCommand();\n }\n }\n\n void doThis(int a) {\n doThisCommand.execute(a);\n }\n}\n"
},
{
"answer_id": 214963,
"author": "Chii",
"author_id": 17335,
"author_profile": "https://Stackoverflow.com/users/17335",
"pm_score": 2,
"selected": false,
"text": "Class Salad {\n private Veggie v;\n private Egg e;\n private Meat m;\n // etc etc, lots of properties\n //constructor like this is nice\n Salad(SaladBuilder builder) {\n //query the builder to actually build the salad object. \n //getVeggie() will either return the supplied value, \n //or a default if none exists. \n this.v = builder.getVeggie(); \n //rest of code omitted\n }\n\n //otherwise this constructor is fine, but needs a builder.build() method\n Salad(Veggie v, Meat m, Egg e) { //code omitted\n }\n}\n\nclass SaladBuilder {\n //some default, or left to null depending on what is needed\n private Veggie v = SOME_DEFAULT_VEGGIE;\n private Egg e; \n private Meat m;\n // etc etc, lots of properties.\n\n //similar functions for each ingredient, \n //or combination of ingredients that only make sense together \n public SaladBuilder addIngredient(Meat m) {\n this.m = m;\n return this;\n }\n\n public SaladBuilder addIngredient(Veggie v) {\n this.v = v;\n return this;\n }\n\n public Salad build(){\n // essentially, creates the salad object, but make sure optionals\n // are taken care of here.\n return new Salad(getBeggie(), getMeat(), getEgg());\n }\n}\n Salad s = new SaladBuilder().addIngredient(v).addIngredient(m).build();\n"
},
{
"answer_id": 214978,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": false,
"text": "public void ActionABC()\n{\n if (options.DoA)\n {\n A();\n }\n\n if (options.DoB)\n {\n B();\n }\n\n if (options.DoC)\n {\n C();\n }\n}\n\npublic void ActionCAB()\n{\n if (options.DoC)\n {\n C();\n }\n\n if (options.DoA)\n {\n A();\n }\n\n if (options.DoB)\n {\n B();\n }\n}\n"
},
{
"answer_id": 215049,
"author": "johnstok",
"author_id": 27929,
"author_profile": "https://Stackoverflow.com/users/27929",
"pm_score": 1,
"selected": false,
"text": "IdMap elementsById = (options.useIdAttribute) ? new IdMapImpl() : new NullIdMap();\n\npublic Element getElementById(final string id) {\n return elementsById.get(id);\n}\n interface IdMap {\n Element get(String id);\n}\n\nclass NullIdMap implements IdMap {\n public Element get(final String id) {\n throw new Exception(/* Error message */);\n }\n}\n\nclass IdMapImpl implements IdMap {\n Map<String, Element> elements = new HashMap<String, Element>();\n\n public Element get(final String id) {\n rejectEmpty(id);\n return elements.get(id.toLowerCase());\n }\n}\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14484/"
] |
214,886
|
<p>I want to keep my website/s in version control (Subversion specifically) and use <code>svn co</code> to update it when there are stable versions to update, but I'm concerned about the security of doing so, as all the <code>.svn</code> folders will be public, and these include all sorts of private data, not least of which is complete source code to my website! </p>
<p>Is there anything I can I do to prevent this?</p>
|
[
{
"answer_id": 214887,
"author": "Matthew Scharley",
"author_id": 15537,
"author_profile": "https://Stackoverflow.com/users/15537",
"pm_score": 3,
"selected": false,
"text": ".htaccess RewriteEngine On\nRewriteRule /\\.svn /some-non-existant-404-causing-page\n\n<IfModule autoindex_module>\n IndexIgnore .svn\n</IfModule>\n mod_rewrite .svn .svn"
},
{
"answer_id": 214908,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 6,
"selected": true,
"text": "<DirectoryMatch \\.svn>\n Order allow,deny\n Deny from all\n</DirectoryMatch>\n AliasMatch \\.svn /non-existant-page\n"
},
{
"answer_id": 215157,
"author": "CesarB",
"author_id": 28258,
"author_profile": "https://Stackoverflow.com/users/28258",
"pm_score": 2,
"selected": false,
"text": "rsync -vv --rsh='ssh -l username' -rltzpy --exclude .svn/ --exclude CVS/ --exclude Attic/ --delete-after --delete-excluded --chmod=og-w,Fa-x\n"
},
{
"answer_id": 3207922,
"author": "Gilles 'SO- stop being evil'",
"author_id": 387076,
"author_profile": "https://Stackoverflow.com/users/387076",
"pm_score": 3,
"selected": false,
"text": "RedirectMatch .htaccess .htaccess"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15537/"
] |
214,891
|
<p>Please write a list of tasks that a copy constructor and assignment operator need to do in C++ to keep exception safety, avoid memory leaks etc. </p>
|
[
{
"answer_id": 214925,
"author": "Nazgob",
"author_id": 3579,
"author_profile": "https://Stackoverflow.com/users/3579",
"pm_score": -1,
"selected": false,
"text": "Array(const Array& rhs)\n {\n mData = NULL;\n mSize = rhs.size();\n *this = rhs;\n }\n\n Array& operator=(const Array& rhs)\n {\n if(this == &rhs)\n {\n return *this;\n }\n\n int len = rhs.size();\n\n delete[] mData;\n\n mData = new T[len];\n\n for(int i = 0; i < len; ++i)\n {\n mData[i] = rhs[i];\n }\n\n mSize = len;\n\n return *this;\n }\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1640962/"
] |
214,899
|
<p>Is it possible, with Javascript or some other technology to determine which hyperlink a user has clicked on, without changing the hyperlink source code.</p>
<p>For example:
Can you click on a 'tag' button, then click on a hyperlink hosted in a different iframe, and be able to calculate which hyperlink the user clicked on, without changing any of the source code in that iframe?</p>
|
[
{
"answer_id": 214962,
"author": "bobince",
"author_id": 18936,
"author_profile": "https://Stackoverflow.com/users/18936",
"pm_score": 0,
"selected": false,
"text": "<iframe id=\"framedpage\" src=\"framedpage.html\"></iframe>\n<button type=\"button\" id=\"tagbutton\">Tag</button>\n<script type=\"text/javascript\">\n function framedclicks_bind() {\n var f= document.getElementById('framedpage');\n var fdoc= f.contentDocument;\n if (!fdoc) fdoc= f.contentWindow.document; // for IE\n if (fdoc)\n for (var i= fdoc.links.length; i-->0;)\n fdoc.links[i].onclick= framedclicks_click; // bind to all links\n }\n function framedclicks_click() {\n alert('You clicked on '+this.href);\n return false; // don't follow link\n }\n document.getElementById('tagbutton').onclick= framedclicks_bind;\n</script>\n"
},
{
"answer_id": 218291,
"author": "pawel",
"author_id": 4879,
"author_profile": "https://Stackoverflow.com/users/4879",
"pm_score": 0,
"selected": false,
"text": "document.onclick = function(e){\n e = e || window.event;\n var t = e.target || e.srcElement;\n if(t.nodeName=='A'){\n alert( t.href );\n }\n}\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13911/"
] |
214,903
|
<p>I have a small command line program that uses the Team System API. When the correct Team System isn't installed on the machine, the program prints a traceback with System.IO.FileNotFoundException, but it also <strong>crashes</strong> and shows the standard error messasge:</p>
<blockquote>
<p>XXX has encountered a problem and
needs to close. We are sorry for the
inconvenience.</p>
</blockquote>
<p>I just want my program to print a "The program requires Team System 2008" message to the console and quit without crashing.</p>
<p>From what I understand this whole loading process is happening before the first line of my C# code is run. Is there any way to control this?</p>
|
[
{
"answer_id": 214921,
"author": "Joe",
"author_id": 13087,
"author_profile": "https://Stackoverflow.com/users/13087",
"pm_score": 0,
"selected": false,
"text": "public class Program\n{\n static void Main()\n {\n try\n {\n WrapperClass.CallApi(...);\n }\n catch(FileNotFoundException)\n {\n ... you can e.g. show a MessageBox and exit here ... \n }\n }\n}\n\ninternal class WrapperClass\n{\n public void CallApi(...)\n {\n ... you can reference types from the Team System assembly in WrapperClass\n }\n}\n"
},
{
"answer_id": 214970,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 3,
"selected": true,
"text": "[MethodImpl(MethodImplOptions.NoInlining)]\nstatic int Main() { // add \"args\" etc if needed\n try {\n return Main2();\n } catch (Exception ex) {\n Console.Error.WriteLine(ex.Message);\n return 1;\n }\n}\nstatic int Main2() { // add \"args\" etc if needed\n // your real code\n}\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214903",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15109/"
] |
214,913
|
<p>I can enumerate many features of functional programming, but when my friend asked me Could you define functional programming for me? I couldn't.</p>
|
[
{
"answer_id": 215057,
"author": "Cervo",
"author_id": 16219,
"author_profile": "https://Stackoverflow.com/users/16219",
"pm_score": -1,
"selected": false,
"text": "list is some list of items\nOutList is some empty list\nforeach item in list\n OutList.append(function(item))\nreturn OutList\n + AggregateItemsInList(List, combinefunction, StepFunction)\n function incNormal(x) {\n return x + 1\n}\n\nfunction incTwo(x) {\n return x + 2\n}\n\nAggregateItemsInList(List, +, incNormal)\n AggegateItemsInList(List, +, incTwo)\n AggregateItemsInList(List, *, incNormal)\n function AddScores (studenta, studentb) {\n return studenta.score + studentb.score\n}\n\nAggregateItemsInList(ListOfStudents, AddScores, incOne)\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11439/"
] |
214,915
|
<p>I'm trying to assign application pool to one web site in IIS7 using vb script:</p>
<pre><code>' Connect to the WMI WebAdministration namespace.'
Set oWebAdmin = GetObject("winmgmts:root\WebAdministration")
' Retrieve the application and display its Web site name and path.'
Set oApp = oWebAdmin.Get("Application.SiteName='Default Web Site',Path='/site'")
' Specify a new application pool name and save it.'
oApp.ApplicationPool = "NewAppPool"
oApp.Put_
</code></pre>
<p>the above script is not working!</p>
<p>Is there is a better way to assign application pool to web site under IIS (Using script)?</p>
|
[
{
"answer_id": 214935,
"author": "Jim Fiorato",
"author_id": 650,
"author_profile": "https://Stackoverflow.com/users/650",
"pm_score": 1,
"selected": false,
"text": "Set oWebAdmin = GetObject(\"winmgmts:root\\WebAdministration\")\nSet oSite = oWebAdmin.Get(\"Site.Name='Site'\")\noSite.ApplicationDefaults.ApplicationPool = \"NewAppPool\"\noSite.Put_\n"
},
{
"answer_id": 32730049,
"author": "Silvio Sabino",
"author_id": 5365846,
"author_profile": "https://Stackoverflow.com/users/5365846",
"pm_score": 0,
"selected": false,
"text": "Set oWebAdmin = GetObject(\"Application.Path='/site',SiteName='Default Web Site'\")\n Set oWebAdmin = GetObject(\"Application.SiteName='Default Web Site',Path='/site'\")\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
214,927
|
<p>When using C++ namespaces, do you prefer to explicitly name them, like this:</p>
<pre><code>std::cout << "Hello, world!\n";
</code></pre>
<p>Or do you prefer <code>using namespace</code>:</p>
<pre><code>using namespace std;
cout << "Hello, world!\n";
</code></pre>
<p>And if if you prefer the latter, do you declare your usings at file or function scope?</p>
<p>Personally I prefer to explicitly name them - it's more typing but when using a mixture of namespaces (e.g. <code>std</code> and <code>boost</code>) I find it more readable.</p>
|
[
{
"answer_id": 214933,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 5,
"selected": true,
"text": "using namespace using namespace"
},
{
"answer_id": 214961,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 4,
"selected": false,
"text": ":: using"
},
{
"answer_id": 215019,
"author": "Nemanja Trifunovic",
"author_id": 8899,
"author_profile": "https://Stackoverflow.com/users/8899",
"pm_score": 2,
"selected": false,
"text": "using"
},
{
"answer_id": 215136,
"author": "xtofl",
"author_id": 6610,
"author_profile": "https://Stackoverflow.com/users/6610",
"pm_score": 2,
"selected": false,
"text": "using using namespace void bar() {\n\n // do stuff without vector\n\n { using std::vector;\n // do stuff with vector\n }\n\n // do stuff without vector\n}\n std using namespace std using class A {\n void f( A );\n void f( bool );\n};\n\nclass B : public A {\n using A::f; // without this, we get a compilation error in foo()\n void f(bool);\n};\n\nvoid foo() {\n B b;\n b.f( A() ); // here's a compilation error when no `using` is used in B\n}\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9236/"
] |
214,998
|
<p>How to dynamically bind data to <code><%Html.Dropdownlist....</code> in ASP.NET MVC?</p>
|
[
{
"answer_id": 215023,
"author": "hangy",
"author_id": 11963,
"author_profile": "https://Stackoverflow.com/users/11963",
"pm_score": 4,
"selected": false,
"text": "<%= Html.DropDownList(string.Empty, \n \"myDropDownList\", \n new SelectList((IEnumerable)ViewData[\"stuff\"], \n \"DescriptionProperty\", \n \"ValueProperty\")) \n%>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29215/"
] |
215,011
|
<p>How do I make sure the correct encoding (UTF-8) is used by Grails?</p>
|
[
{
"answer_id": 217352,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "\nresponse.setContentType(\"text/html; charset=UTF-8\");\nrequest.setCharacterEncoding(\"UTF-8\");\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6583/"
] |
215,026
|
<p>I am trying to run some unit tests in a C# Windows Forms application (Visual Studio 2005), and I get the following error:</p>
<blockquote>
<p>System.IO.FileLoadException: Could not load file or assembly 'Utility, Version=1.2.0.200, Culture=neutral, PublicKeyToken=764d581291d764f7' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)**</p>
<p>at x.Foo.FooGO()</p>
<p>at x.Foo.Foo2(String groupName_) in Foo.cs:line 123</p>
<p>at x.Foo.UnitTests.FooTests.TestFoo() in FooTests.cs:line 98**</p>
<p>System.IO.FileLoadException: Could not load file or assembly 'Utility, Version=1.2.0.203, Culture=neutral, PublicKeyToken=764d581291d764f7' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)</p>
</blockquote>
<p>I look in my references, and I only have a reference to <code>Utility version 1.2.0.203</code> (the other one is old).</p>
<p>Any suggestions on how I figure out what is trying to reference this old version of this DLL file?</p>
<p>Besides, I don't think I even have this old assembly on my hard drive.
Is there any tool to search for this old versioned assembly?</p>
|
[
{
"answer_id": 215054,
"author": "Lars Truijens",
"author_id": 1242,
"author_profile": "https://Stackoverflow.com/users/1242",
"pm_score": 10,
"selected": true,
"text": "gacutil /i \"path/to/my.dll\"\n"
},
{
"answer_id": 220029,
"author": "Seth Petry-Johnson",
"author_id": 23632,
"author_profile": "https://Stackoverflow.com/users/23632",
"pm_score": 7,
"selected": false,
"text": "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Fusion\\EnableLog"
},
{
"answer_id": 12681453,
"author": "Thomas",
"author_id": 9970,
"author_profile": "https://Stackoverflow.com/users/9970",
"pm_score": 2,
"selected": false,
"text": "<bindingRedirect oldVersion=\"1.0.0.0\" newVersion=\"2.0.11.0\"/>\n"
},
{
"answer_id": 13187622,
"author": "Yaniv.H",
"author_id": 1152687,
"author_profile": "https://Stackoverflow.com/users/1152687",
"pm_score": 6,
"selected": false,
"text": "<assemblyBinding xmlns=\"urn:schemas-microsoft-com:asm.v1\">\n <dependentAssembly>\n <assemblyIdentity name=\"Castle.Core\" publicKeyToken=\"407dd0808d44fbdc\" culture=\"neutral\" />\n <bindingRedirect oldVersion=\"0.0.0.0-65535.65535.65535.65535\" newVersion=\"3.1.0.0\" />\n </dependentAssembly>\n</assemblyBinding>\n"
},
{
"answer_id": 15336470,
"author": "shan",
"author_id": 2042501,
"author_profile": "https://Stackoverflow.com/users/2042501",
"pm_score": 2,
"selected": false,
"text": "Utility, Version=1.2.0.200 Utility, Version=1.2.0.203 Utility, Version=1.2.0.203(new version) Utility, Version=1.2.0.200(old version)"
},
{
"answer_id": 17374996,
"author": "Ben Pretorius",
"author_id": 821243,
"author_profile": "https://Stackoverflow.com/users/821243",
"pm_score": 3,
"selected": false,
"text": "Update-Package"
},
{
"answer_id": 22203322,
"author": "frattaro",
"author_id": 1661469,
"author_profile": "https://Stackoverflow.com/users/1661469",
"pm_score": 5,
"selected": false,
"text": "<dependentAssembly>\n <assemblyIdentity name=\"Newtonsoft.Json\" publicKeyToken=\"30ad4fe6b2a6aeed\" />\n <bindingRedirect oldVersion=\"0.0.0.0-4.5.0.0\" newVersion=\"6.0.0.0\" />\n</dependentAssembly>\n <dependentAssembly>\n <assemblyIdentity name=\"Newtonsoft.Json\" publicKeyToken=\"30ad4fe6b2a6aeed\" />\n <bindingRedirect oldVersion=\"0.0.0.0-4.0.0.0\" newVersion=\"4.5.0.0\" />\n</dependentAssembly>\n"
},
{
"answer_id": 27344805,
"author": "Tomas Kubes",
"author_id": 518530,
"author_profile": "https://Stackoverflow.com/users/518530",
"pm_score": 1,
"selected": false,
"text": "Could not load file or assembly 'DotNetOpenAuth.Core, Version=4.0.0.0,\nCulture=neutral, PublicKeyToken=2780ccd10d57b246' or one of its dependencies.\nThe located assembly's manifest definition does not match the assembly reference.\n(Exception from HRESULT: 0x80131040)\n <dependentAssembly>\n <assemblyIdentity name=\"DotNetOpenAuth.AspNet\" publicKeyToken=\"2780ccd10d57b246\" culture=\"neutral\" />\n <bindingRedirect oldVersion=\"0.0.0.0-4.3.0.0\" newVersion=\"4.3.0.0\" />\n </dependentAssembly>\n <dependentAssembly>\n <assemblyIdentity name=\"DotNetOpenAuth.Core\" publicKeyToken=\"2780ccd10d57b246\" culture=\"neutral\" />\n <bindingRedirect oldVersion=\"0.0.0.0-4.3.0.0\" newVersion=\"4.3.0.0\" />\n</dependentAssembly>\n"
},
{
"answer_id": 39947114,
"author": "Levi Fuller",
"author_id": 2535344,
"author_profile": "https://Stackoverflow.com/users/2535344",
"pm_score": 5,
"selected": false,
"text": "obj bin"
},
{
"answer_id": 40614345,
"author": "Mike Gledhill",
"author_id": 391605,
"author_profile": "https://Stackoverflow.com/users/391605",
"pm_score": 2,
"selected": false,
"text": "<Reference Include=\"DocumentFormat.OpenXml, Version=2.5.5631.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL\" />\n <Reference Include=\"DocumentFormat.OpenXml, Version=2.0.5022.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL\" />\n"
},
{
"answer_id": 50878397,
"author": "Jaggan_j",
"author_id": 2093481,
"author_profile": "https://Stackoverflow.com/users/2093481",
"pm_score": 1,
"selected": false,
"text": "PM> Install-Package YourPackageName -Version YourVersionNumber \n//Example\nPM> Install-Package Microsoft.Extensions.FileProviders.Physical -Version 2.1.0\n"
},
{
"answer_id": 54354004,
"author": "codeMonkey",
"author_id": 4009972,
"author_profile": "https://Stackoverflow.com/users/4009972",
"pm_score": 5,
"selected": false,
"text": "<assemblyBinding> Get-Project -All | Add-BindingRedirect\n"
},
{
"answer_id": 55742326,
"author": "mimo",
"author_id": 1212547,
"author_profile": "https://Stackoverflow.com/users/1212547",
"pm_score": 0,
"selected": false,
"text": "XXX.dll XXX-new.dll"
},
{
"answer_id": 56359672,
"author": "Ogglas",
"author_id": 3850405,
"author_profile": "https://Stackoverflow.com/users/3850405",
"pm_score": 0,
"selected": false,
"text": "System.ValueTuple .NET Framework 4.7.2 Runtime bindingRedirect"
},
{
"answer_id": 57609562,
"author": "Mi1anovic",
"author_id": 4788184,
"author_profile": "https://Stackoverflow.com/users/4788184",
"pm_score": 2,
"selected": false,
"text": "<dependentAssembly>\n <assemblyIdentity name=\"Microsoft.IdentityModel.Logging\" publicKeyToken=\"31bf3856ad364e35\" culture=\"neutral\" />\n <bindingRedirect oldVersion=\"0.0.0.0-5.5.0.0\" newVersion=\"5.5.0.0\" />\n</dependentAssembly>\n <dependentAssembly>\n <assemblyIdentity name=\"Microsoft.IdentityModel.Logging\" publicKeyToken=\"31bf3856ad364e35\" culture=\"neutral\" />\n <bindingRedirect oldVersion=\"0.0.0.0-3.14.0.0\" newVersion=\"5.5.0.0\" />\n</dependentAssembly>\n"
},
{
"answer_id": 58266127,
"author": "Mostafa Vatanpour",
"author_id": 5193370,
"author_profile": "https://Stackoverflow.com/users/5193370",
"pm_score": 0,
"selected": false,
"text": "publicKeyToken <Reference Include=\"Utility, Version=0.0.0.0, Culture=neutral, PublicKeyToken=e71b9933bfee3534, processorArchitecture=MSIL\">\n <SpecificVersion>False</SpecificVersion>\n <HintPath>dlls\\Utility.dll</HintPath>\n</Reference>\n <Reference Include=\"Utility, Version=1.0.1.100, Culture=neutral, processorArchitecture=MSIL\">\n <SpecificVersion>False</SpecificVersion>\n <HintPath>dlls\\Utility.dll</HintPath>\n</Reference>\n SpecificVersion False"
},
{
"answer_id": 63128705,
"author": "NITHIN SUHAS",
"author_id": 5879675,
"author_profile": "https://Stackoverflow.com/users/5879675",
"pm_score": 0,
"selected": false,
"text": " <dependentAssembly>\n <assemblyIdentity name=\"System.IO\" publicKeyToken=\"B03F5F7F11D50A3A\" culture=\"neutral\" />\n <bindingRedirect oldVersion=\"0.0.0.0-4.1.2.0\" newVersion=\"4.3.0.0\" />\n </dependentAssembly>\n"
},
{
"answer_id": 65125941,
"author": "ChrisBeamond",
"author_id": 10391656,
"author_profile": "https://Stackoverflow.com/users/10391656",
"pm_score": 2,
"selected": false,
"text": "<dependentAssembly>\n <assemblyIdentity name=\"System.ComponentModel.Annotations\" publicKeyToken=\"b03f5f7f11d50a3a\" culture=\"neutral\"/>\n <bindingRedirect oldVersion=\"0.0.0.0-4.2.1.0\" newVersion=\"4.2.1.0\"/>\n</dependentAssembly>\n"
},
{
"answer_id": 65252938,
"author": "toralux",
"author_id": 3751540,
"author_profile": "https://Stackoverflow.com/users/3751540",
"pm_score": 2,
"selected": false,
"text": " <Project Sdk=\"Microsoft.NET.Sdk\">\n <PropertyGroup>\n <Version>1.0.0</Version>\n </PropertyGroup>\n - task: DotNetCoreCLI@2\n displayName: 'pack'\n inputs:\n command: pack\n nobuild: true\n configurationToPack: 'Release'\n includesource: true\n includesymbols: true\n packagesToPack: 'MyNugetProject1.csproj;**/MyNugetProject2.csproj'\n versioningScheme: 'byEnvVar'\n versionEnvVar: 'GitVersion.SemVer'\n <Version>1.0.0</Version>"
},
{
"answer_id": 66398938,
"author": "Marek Schwarz",
"author_id": 6406719,
"author_profile": "https://Stackoverflow.com/users/6406719",
"pm_score": 3,
"selected": false,
"text": "<assemblyBinding xmlns=\"urn:schemas-microsoft-com:asm.v1\">\n <dependentAssembly>\n <assemblyIdentity name=\"Microsoft.Extensions.Logging.Abstractions\" publicKeyToken=\"adb9793829ddae60\" culture=\"neutral\" />\n <bindingRedirect oldVersion=\"0.0.0.0-3.1.3.0\" newVersion=\"3.1.3.0\" />\n </dependentAssembly>\n <dependentAssembly>\n <assemblyIdentity name=\"Microsoft.Extensions.DependencyInjection\" publicKeyToken=\"adb9793829ddae60\" culture=\"neutral\" />\n <bindingRedirect oldVersion=\"0.0.0.0-3.1.3.0\" newVersion=\"3.1.3.0\" />\n </dependentAssembly>\n <dependentAssembly>\n <assemblyIdentity name=\"System.ComponentModel.Annotations\" publicKeyToken=\"b03f5f7f11d50a3a\" culture=\"neutral\" />\n <bindingRedirect oldVersion=\"0.0.0.0-4.2.1.0\" newVersion=\"4.2.1.0\" />\n </dependentAssembly>\n</assemblyBinding>\n"
},
{
"answer_id": 73557076,
"author": "bounav",
"author_id": 2472,
"author_profile": "https://Stackoverflow.com/users/2472",
"pm_score": 1,
"selected": false,
"text": "Version File Explorer's > Properies > Details [Reflection.AssemblyName]::GetAssemblyName('C:\\Source\\Project\\Web\\bin\\System.Memory.dll').Version\n\nMajor Minor Build Revision\n----- ----- ----- --------\n4 0 1 2\n app.config <dependentAssembly>\n <assemblyIdentity name=\"System.Memory\" culture=\"neutral\" publicKeyToken=\"cc7b13ffcd2ddd51\"/>\n <bindingRedirect oldVersion=\"0.0.0.0-4.0.1.2\" newVersion=\"4.0.1.2\"/>\n</dependentAssembly>\n System.Memory.dll 4.6.31308.01"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4653/"
] |
215,030
|
<p>The picture below explains all:</p>
<p><a href="http://img133.imageshack.us/img133/4206/accentar9.png" rel="nofollow noreferrer">alt text http://img133.imageshack.us/img133/4206/accentar9.png</a></p>
<p>The variable textInput comes from <code>File.ReadAllText(path);</code> and characters like : ' é è ... do not display. When I run my UnitTest, all is fine! I see them... Why?</p>
|
[
{
"answer_id": 215059,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "System.IO.StreamReader System.Text.Encoding.Default string text = System.IO.File.ReadAllText(\"path\", Encoding.GetEncoding(1252));\n System.Text.Encoding"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13913/"
] |
215,052
|
<p>What is the best choice for a Python GUI application to display large number of thumbnails, e.g. 10000 or more? For performance reasons such thumbnail control must support virtual items, i.e. request application for those thumbnails only which are currently visible to user. </p>
|
[
{
"answer_id": 215257,
"author": "Toni Ruža",
"author_id": 6267,
"author_profile": "https://Stackoverflow.com/users/6267",
"pm_score": 2,
"selected": false,
"text": "class GridData(wx.grid.PyGridTableBase):\n def GetColLabelValue(self, col):\n pass\n\n def GetNumberRows(self):\n pass\n\n def GetNumberCols(self):\n pass\n\n def IsEmptyCell(self, row, col):\n pass\n\n def GetValue(self, row, col):\n pass\n class CellRenderer(wx.grid.PyGridCellRenderer):\n def Draw(self, grid, attr, dc, rect, row, col, isSelected):\n pass\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29219/"
] |
215,056
|
<p>I just added asp.net calendar control in new page under sample folder in asp.net mvc beta application. when i execute the particaular page that i need and it shows the error following </p>
<p>Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.</p>
<p>that points to here . It's in site.master of asp.net mvc </p>
<pre><code><div id="logindisplay">
<% Html.RenderPartial("LoginUserControl"); %>
</div>
</code></pre>
<p>usually to avoid this error, we give </p>
<pre><code><pages validateRequest="false" enableEventValidation="false" viewStateEncryptionMode ="Never" >
</code></pre>
<p>but, it doesn't work for me.</p>
|
[
{
"answer_id": 215078,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 2,
"selected": false,
"text": "<pages enableeventvalidation=\"false\" viewstateencryptionmode=\"Never\">\n"
},
{
"answer_id": 894988,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "I have been struggling with this issue too since lasts few days and finally found the problem.\n\nThis error will show up in there are multiple <form> tags are being rendered on a page (be it html <form></form> or Html.BeginForm()).\nCheck the user controls being rendered, the content page section and also the Master page.\nMake sure there is only one form rendered on a page.\n\nThis should fix your problem, if the issue persists, check for the for submit buttons rendered on the page (<input type=\"submit\" …/>)\n\nCheers!\nMayank Srivastava\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29215/"
] |
215,063
|
<p>I want to be able to use a function such as <code>writefln()</code> but without having to add <code>import std.stdio</code> at the top of the file.</p>
<p>Another way to explain it is the way you do it in C++. You can type <code>std::cout << "Test";</code> and that will stop you from having to add <code>using namespace std;</code>. I want to do the same thing, but in D.</p>
|
[
{
"answer_id": 215067,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 2,
"selected": false,
"text": "import using namespace #include"
},
{
"answer_id": 593068,
"author": "zildjohn01",
"author_id": 66341,
"author_profile": "https://Stackoverflow.com/users/66341",
"pm_score": 3,
"selected": false,
"text": "static import std.stdio;\n\nvoid main()\n{\n writefln(\"hello!\"); // error, writefln is undefined\n std.stdio.writefln(\"hello!\"); // ok, writefln is fully qualified\n}\n"
},
{
"answer_id": 3527743,
"author": "Alexander Malakhov",
"author_id": 264047,
"author_profile": "https://Stackoverflow.com/users/264047",
"pm_score": 0,
"selected": false,
"text": "import std.stdio: writef, writefln;\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
215,110
|
<p>What is the best way to graph scatter plots in C++? </p>
<p>Do you write data to a file and use another tool? Is there a library like matplotlib in Python?</p>
|
[
{
"answer_id": 215117,
"author": "freespace",
"author_id": 8297,
"author_profile": "https://Stackoverflow.com/users/8297",
"pm_score": 6,
"selected": true,
"text": "gnuplot x y plot \"data.txt\" using 1:2 \n gnuplot"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14069/"
] |
215,114
|
<p>I am using running a simple find all and paginating with willpaginate, but I'd also like to have the query sorted by the user. The first solution that came to mind was just use a params[:sort]</p>
<pre><code>http://localhost:3000/posts/?sort=created_at+DESC
@posts = Post.paginate :page => params[:page], :order => params[:sort]
</code></pre>
<p>But the problem with his approach is that the query is defaulting as sorting by ID and I want it to be created_at. </p>
<p>Is this a safe approach to sorting and is there a way to default to created_at?</p>
|
[
{
"answer_id": 215126,
"author": "Avdi",
"author_id": 20487,
"author_profile": "https://Stackoverflow.com/users/20487",
"pm_score": 2,
"selected": false,
"text": "fetch params.fetch(:sort){ :created_at }\n || params[:sort] || :created_at\n fetch false"
},
{
"answer_id": 215145,
"author": "Rômulo Ceccon",
"author_id": 23193,
"author_profile": "https://Stackoverflow.com/users/23193",
"pm_score": 2,
"selected": false,
"text": "@posts = Post.paginate :page => params[:page], :order => params[:sort] || \"created_at\"\n \"created_at; DROP DATABASE mydatabase;\" sort_params = { \"by_date\" => \"created_at\", \"by_name\" => \"name\" }\n\n@posts = Post.paginate :page => params[:page], :order => sort_params[params[:sort] || \"by_date\"]\n http://localhost:3000/posts/?sort=by_date\n"
},
{
"answer_id": 215158,
"author": "Matt",
"author_id": 29228,
"author_profile": "https://Stackoverflow.com/users/29228",
"pm_score": 5,
"selected": true,
"text": "named_scope :ordered, lambda {|*args| {:order => (args.first || 'created_at DESC')} }\n @posts = Post.ordered.paginate :page => params[:page]\n named_scope created_at DESC @posts = Post.ordered('title ASC').paginate :page => params[:page]\n sort_params = { \"by_date\" => \"created_at\", \"by_name\" => \"name\" }\n@posts = Post.ordered(sort_params[params[:sort]]).paginate :page => params[:page]\n params[:sort] sort_params nil named_scope"
},
{
"answer_id": 216640,
"author": "Scott",
"author_id": 7399,
"author_profile": "https://Stackoverflow.com/users/7399",
"pm_score": 1,
"selected": false,
"text": "@posts = Post.paginate :page=>page, :order=>order\n...\n\ndef page\n params[:page] || 1\nend\n\ndef order\n params[:order] || 'created_at ASC'\nend\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10258/"
] |
215,115
|
<p>I have an old ASP.NET 1.1 site that I am maintaining. We are working with Google to place analytics code on all pages. Since I can't take advantage of master pages in 1.1, I have my pages include headers/footers/sidebars with User Controls.</p>
<p>What came to mind first is to place the JavaScript in my footer ascx control so it appears on every page. But I don't think I can link to a JavaScript file from a user control. </p>
<p>Any ideas on what I can do to get this js code placed on every page in my site?</p>
|
[
{
"answer_id": 215121,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 3,
"selected": false,
"text": "<asp:SomeControl ID=\"SomeControl1\" runat=\"server>\n <script src=\"some.js\" type=\"text/javascript\"></script>\n</asp:SomeControl>\n protected void Page_Load(object sender, EventArgs e)\n{\n Literal some_js = new Literal();\n some_js = \"<script type='text/javascript' src='some.js'></script>\";\n this.Header.Controls.Add(some_js);\n}\n"
},
{
"answer_id": 215358,
"author": "Pradeep Kumar Mishra",
"author_id": 22710,
"author_profile": "https://Stackoverflow.com/users/22710",
"pm_score": 2,
"selected": true,
"text": "HtmlGenericControl jscriptFile = new HtmlGenericControl();\njscriptFile.TagName = \"script\";\njscriptFile.Attributes.Add(\"type\", \"text/javascript\");\njscriptFile.Attributes.Add(\"language\", \"javascript\"); \njscriptFile.Attributes.Add(\"src\", ResolveUrl(\"myscriptFile.js\"));\nthis.Page.Header.Controls.Add(myJs);\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3047/"
] |
215,119
|
<p>Is there a reliable equivalent of xkill for Windows?</p>
<p>For those who don't know what xkill is: it is a Unix tool which basically kills the process of any windows you click on.</p>
<p>A Windows port can be downloaded <a href="http://solo-dev.deviantart.com/art/Windows-xKill-100737525" rel="noreferrer">here</a>.</p>
|
[
{
"answer_id": 215172,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 3,
"selected": false,
"text": "taskkill /im ProcessName.exe /f\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8954/"
] |
215,132
|
<p>I have a ListCtrl that displays a list of items for the user to select. This works fine except that when the ctrl is not large enough to show all the items, I want it to expand downwards with a vertical scoll bar rather than using a horizontal scroll bar as it expands to the right.</p>
<p>The ListCtrl's creation:</p>
<pre><code>self.subjectList = wx.ListCtrl(self, self.ID_SUBJECT, style = wx.LC_LIST | wx.LC_SINGLE_SEL | wx.LC_VRULES)
</code></pre>
<p>Items are inserted using wx.ListItem:</p>
<pre><code>item = wx.ListItem()
item.SetText(subject)
item.SetData(id)
item.SetWidth(200)
self.subjectList.InsertItem(item)
</code></pre>
|
[
{
"answer_id": 215216,
"author": "Toni Ruža",
"author_id": 6267,
"author_profile": "https://Stackoverflow.com/users/6267",
"pm_score": 3,
"selected": true,
"text": "import wx\n\nclass Test(wx.Frame):\n def __init__(self):\n wx.Frame.__init__(self, None)\n self.test = wx.ListCtrl(self, style = wx.LC_REPORT | wx.LC_NO_HEADER)\n\n for i in range(5):\n self.test.InsertColumn(i, 'Col %d' % (i + 1))\n self.test.SetColumnWidth(i, 200)\n\n\n for i in range(0, 100, 5):\n index = self.test.InsertStringItem(self.test.GetItemCount(), \"\")\n for j in range(5):\n self.test.SetStringItem(index, j, str(i+j)*30)\n\n self.Show()\n\napp = wx.PySimpleApp()\napp.TopWindow = Test()\napp.MainLoop()\n"
},
{
"answer_id": 215335,
"author": "Toni Ruža",
"author_id": 6267,
"author_profile": "https://Stackoverflow.com/users/6267",
"pm_score": 1,
"selected": false,
"text": "import wx\n\nclass Test(wx.Frame):\n def __init__(self):\n wx.Frame.__init__(self, None)\n self.test = wx.ListCtrl(self, style = wx.LC_ICON | wx.LC_AUTOARRANGE)\n\n for i in range(100):\n self.test.InsertStringItem(self.test.GetItemCount(), str(i))\n\n self.Show()\n\napp = wx.PySimpleApp()\napp.TopWindow = Test()\napp.MainLoop()\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6266/"
] |
215,139
|
<p>Can someone tell me how i can change the .xml file that a flash movie loads using c#. ie: i would like an ActionScript variable that defines the location of the flash movie. I would like to be able to change this variable using c# if possible.</p>
<p>i dont really know how it would look, but something like:</p>
<pre><code><object xmlpath='" + myCSharpVar + "'" ...></object>
</code></pre>
<p>I just starting this, but my ultimate goal is to create a .swf movie that can load an xml file that specifies images, etc. However i want to use the same .swf file in multiple places and only have to change a ref to what xml file it uses - and my Flash/ActionScript skills are very rusty.</p>
<p>To clear it up a bit, in AS you can do something like: </p>
<pre><code>loader.load( new URLRequest("IWantThisNameDynamic.xml") );
</code></pre>
<p>how can i define that xml file in my c# code?</p>
|
[
{
"answer_id": 215176,
"author": "Argelbargel",
"author_id": 2992,
"author_profile": "https://Stackoverflow.com/users/2992",
"pm_score": 2,
"selected": true,
"text": "\n <object ...>\n <param name=\"flashvars\" value=\"&xmlpath=<path to xml>\"/>\n </object>\n"
},
{
"answer_id": 215556,
"author": "Philippe",
"author_id": 27219,
"author_profile": "https://Stackoverflow.com/users/27219",
"pm_score": 0,
"selected": false,
"text": "AxShockwaveFlash movie; // already exists\nstring xmlPath = \"some path\";\nmovie.FlashVars = \"xmlPath=\" + xmlPath; // url-encoded variables\n var xmlPath:String = _level0.xmlPath;\n var xmlPath:String = loaderInfo.parameters.xmlPath;\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26685/"
] |
215,144
|
<p>I wanted to derive a class from Predicate<IMyInterface>, but it appears as if Predicate<> is sealed. In my case I wanted to simply return the inverted (!) result of the designated function. I have other ways to accomplish the goal. My question is what might the MS designers have been thinking when deciding to seal Predicate<>?</p>
<p>Without much thought I came up with:
(a) simplified their testing, just a time vs cost trade off
(b) "no good" could come from deriving from Predicate<></p>
<p>What do you think?</p>
<p>Update: There are n predicates that are dynamically added to a list of Predicates during an initialization phase. Each is mutually exclusive (if Abc is added, NotAbc wont be added). I observed a pattern that looks like:</p>
<pre><code>bool Happy(IMyInterface I) {...}
bool NotHappy(IMyInterface I) { return !Happy(I); }
bool Hungry(IMyInterface I) {...}
bool NotHungry(IMyInterface I) { return !Hungry(I); }
bool Busy(IMyInterface I) {...}
bool NotBusy(IMyInterface I) { return !Busy(I); }
bool Smart(IMyInterface I) {...}
bool NotSmart(IMyInterface I) {...} //Not simply !Smart
</code></pre>
<p>Its not that I can't solve the problem, its that I wonder why I couldn't solve it a certain way.</p>
|
[
{
"answer_id": 215152,
"author": "Omer van Kloeten",
"author_id": 4979,
"author_profile": "https://Stackoverflow.com/users/4979",
"pm_score": 2,
"selected": false,
"text": "Predicate<T> p;\nPredicate<T> inverted = t => !p(t);\n"
},
{
"answer_id": 215153,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": false,
"text": "Predicate<T> public static Predicate<T> Invert<T>(Predicate<T> original)\n{\n return t => !original(t);\n}\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27068/"
] |
215,160
|
<p>I have the following javascript:</p>
<pre><code>$.ajax({
type: "POST",
dataType: "json",
url: "/Home/Submit",
data: {
email: strEmail,
message: strMessage
},
success: function(result) {
//alert('here');
alert(result.message);
},
error: function(error) {
alert(error);
}
});
</code></pre>
<p>This makes a call to this function:<BR></p>
<pre><code>public JsonResult Submit(string Email, string Message) {
return Json(new {
message = "yep"
});
}
</code></pre>
<p>This works fine in debug mode on the inbuilt webserver.</p>
<p>However if I go to the virtual dir directly it does not and hits the error bit. I attached to the process and the code behind never gets hit. </p>
<p>I am using Vista. </p>
<p>Additionally how do you get the error description in the bit where it says alert(error);</p>
<p>Thanks,</p>
<p>Alex</p>
|
[
{
"answer_id": 215152,
"author": "Omer van Kloeten",
"author_id": 4979,
"author_profile": "https://Stackoverflow.com/users/4979",
"pm_score": 2,
"selected": false,
"text": "Predicate<T> p;\nPredicate<T> inverted = t => !p(t);\n"
},
{
"answer_id": 215153,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": false,
"text": "Predicate<T> public static Predicate<T> Invert<T>(Predicate<T> original)\n{\n return t => !original(t);\n}\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23066/"
] |
215,183
|
<p>For example, I want just the "filename" of a file in a field. Say I have myimage.jpg I only want to display "myimage" How do I get just that? </p>
|
[
{
"answer_id": 215244,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 4,
"selected": true,
"text": "<cfset FileName = ListDeleteAt(FileFullName, ListLen(FileFullName, \".\"), \".\")>\n <cfset ExtensionIndex = ListLen(FileFullName, \".\")>\n<cfif ExtensionIndex gt 1>\n <cfset FileExt = ListGetAt(ExtensionIndex , \".\")>\n <cfset FileName = ListDeleteAt(FileFullName, ExtensionIndex, \".\")>\n<cfelse>\n <cfset FileExt = \"\">\n <cfset FileName = FileFullName>\n</cfif>\n ListFindNoCase(FileExt, \"doc,xls,ppt,jpg\") <cfset FileExtRe = \"(?:\\.(?:doc|xls|ppt|jpg))?$\">\n<cfset FileName = REReplaceNoCase(FileFullName, FileExtRe, \"\")>\n GetFileFromPath() GetDirectoryFromPath()"
},
{
"answer_id": 215258,
"author": "Guy C",
"author_id": 4045,
"author_profile": "https://Stackoverflow.com/users/4045",
"pm_score": 1,
"selected": false,
"text": "<cfset Position = Find(\".\", Reverse(FullFileName))>\n <cfset Filename = Left(FullFileName, Len(FullFileName) - Position>\n"
},
{
"answer_id": 215406,
"author": "Peter Boughton",
"author_id": 9360,
"author_profile": "https://Stackoverflow.com/users/9360",
"pm_score": 2,
"selected": false,
"text": "<cfset FileName = rereplace( FullFileName , '\\.[^.]+$' , '' ) />\n <cfset FileName = rereplace( FullFileName , '\\.(jpg|png|gif|bmp)$' , '' ) />\n<cfset FileName = rereplace( FullFileName , '\\.[^.]{1,5}$' , '' ) />\n"
},
{
"answer_id": 216547,
"author": "ale",
"author_id": 21960,
"author_profile": "https://Stackoverflow.com/users/21960",
"pm_score": 3,
"selected": false,
"text": "fullFileName=listLast(fieldname,\"\\/\")\n theFileName=listFirst(fullFileName,\".\") \n listAllButLast() fileName=reverse(listRest(reverse(fullFileName),\".\"))\n fileName=listDeleteAt(fullFileName,listLen(fullFileName,\".\"),\".\")\n <cfif listLen(fullFileName,\".\") GT 1>"
},
{
"answer_id": 26514784,
"author": "Tristan Lee",
"author_id": 3980391,
"author_profile": "https://Stackoverflow.com/users/3980391",
"pm_score": 1,
"selected": false,
"text": "org.apache.commons.io.FilenameUtils filepath = \"some/dir/archive.tar.gz\";\noUtils = createObject(\"java\", \"org.apache.commons.io.FilenameUtils\");\n\nwriteDump(oUtils.getFullPath(filepath)); // \"some/dir/\"\nwriteDump(oUtils.getName(filepath)); // \"archive.tar.gz\"\nwriteDump(oUtils.getBaseName(filepath)); // \"archive.tar\"\nwriteDump(oUtils.getExtension(filepath)); // \"gz\"\nwriteDump(oUtils.getPath(filepath)); // \"some/dir/\"\nwriteDump(oUtils.getPathNoEndSeparator(filepath)); // \"some/dir\"\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26121/"
] |
215,211
|
<p>Is there a way to change the colors used by plain Win32 menus (background, text, and highlight) for a single process, <em>without</em> using SetSysColors?</p>
<p>(SetSysColors does a global change, which is bad, and if you crash or forget to set the colors back with SetSysColors again before exiting, they will not be restored until you logout.)</p>
|
[
{
"answer_id": 215249,
"author": "Serge Wautier",
"author_id": 12379,
"author_profile": "https://Stackoverflow.com/users/12379",
"pm_score": 4,
"selected": false,
"text": "MENUINFO mi = { 0 }; \nmi.cbSize = sizeof(mi); \nmi.fMask = MIM_BACKGROUND|MIM_APPLYTOSUBMENUS; \nmi.hbrBack = hBrush; \n\nHMENU hMenu = ::GetMenu(hWnd); \nSetMenuInfo(hMenu, &mi); \n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28258/"
] |
215,213
|
<p>I'm trying this:</p>
<pre><code>Type ThreadContextType = typeof(Application).GetNestedType("ThreadContext", System.Reflection.BindingFlags.NonPublic);
MethodInfo FDoIdleMi = ThreadContextType.GetMethod("FDoIdle", BindingFlags.NonPublic |
BindingFlags.Instance, null, new Type[] { typeof(Int32) }, null);
</code></pre>
<p>ThreadContextType is ok but FDoIdleMi is null. I know there is something wrong in the GetMethod call because FDoIdle comes from the UnsafeNativeMethods.IMsoComponent interface.</p>
<p>How to do that? Thanks.</p>
|
[
{
"answer_id": 215230,
"author": "Charlie",
"author_id": 18529,
"author_profile": "https://Stackoverflow.com/users/18529",
"pm_score": 3,
"selected": true,
"text": "Type type = typeof( Application ).GetNestedType( \"ThreadContext\",\n BindingFlags.NonPublic );\nMethodInfo doIdle = type.GetMethod(\n \"System.Windows.Forms.UnsafeNativeMethods.IMsoComponent.FDoIdle\",\n BindingFlags.NonPublic | BindingFlags.Instance );\n GetMethods(...)"
},
{
"answer_id": 215237,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 1,
"selected": false,
"text": "using System;\nusing System.Linq;\nusing System.Reflection;\nusing System.Windows.Forms;\n\npublic class Test \n{\n static void Main()\n {\n Type clazz = typeof(Application).GetNestedType(\"ThreadContext\", BindingFlags.NonPublic);\n Type iface = typeof(Form).Assembly.GetType(\"System.Windows.Forms.UnsafeNativeMethods+IMsoComponent\");\n InterfaceMapping map = clazz.GetInterfaceMap(iface);\n MethodInfo method = map.TargetMethods.Where(m => m.Name.EndsWith(\".FDoIdle\")).Single();\n Console.WriteLine(method.Name);\n }\n}\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29244/"
] |
215,219
|
<p>I have a really long 3 column table. I would like to </p>
<pre><code><table>
<tr><td>Column1</td><td>Column2</td></tr>
<tr><td>Column1</td><td>Column2</td></tr>
<tr><td>Start</td><td>Hiding</td></tr>
<tr><td>Column1</td><td>Column2</td></tr>
<tr><td>Column1</td><td>Column2</td></tr>
<tr><td>Column1</td><td>Column2</td></tr>
<tr><td>End</td><td>Hiding</td></tr>
<tr><td>Column1</td><td>Column2</td></tr>
<tr><td>Column1</td><td>Column2</td></tr>
</table>
</code></pre>
<p>This is the result I'm trying to obtain using jQuery.</p>
<pre><code>Column1 Column2
Column1 Column2
...Show Full Table...
Column1 Column2
Column1 Column2
</code></pre>
<p>I would like to use jQuery's show/hide feature to minimize the table but still show part of the top and bottom rows. The middle rows should be replace with text like "Show Full Table" and when clicked will expand to show the full table from start to finish.</p>
<p>What is the best way to do this in jQuery?</p>
<p>BTW I've already tried adding a class "Table_Middle" to some of the rows but it doesn't hide it completely the space it occupied is still there and I don't have the text to give the user a way to expand the table fully.</p>
<p><strong>[EDIT] Added Working Example HTML inspired by Parand's posted answer</strong></p>
<p><strong><em>The example below is a complete working example, you don't even need to download jquery. Just paste into a blank HTML file.</em></strong></p>
<p><em>It degrades nicely to show only the full table if Javascript is turned off. If Javascript is on then it hides the middle table rows and adds the show/hide links.</em></p>
<pre><code><html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Example Show/Hide Middle rows of a table using jQuery</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#HiddenRowsNotice").html("<tr><td colspan='2'> <a href='#'>>> some rows hidden <<</a></td></tr>");
$("#ShowHide").html("<tr><td colspan='2'><a href='#'>show/hide middle rows</a></td></tr>");
$("#HiddenRows").hide();
$('#ShowHide,#HiddenRowsNotice').click( function() {
$('#HiddenRows').toggle();
$('#HiddenRowsNotice').toggle();
});
});
</script>
</head>
<body>
<table>
<tbody id="ShowHide"></tbody>
<tr><th>Month Name</th><th>Month</th></tr>
<tbody>
<tr><td>Jan</td><td>1</td></tr>
</tbody>
<tbody id="HiddenRowsNotice"></tbody>
<tbody id="HiddenRows">
<tr><td>Feb</td><td>2</td></tr>
<tr><td>Mar</td><td>3</td></tr>
<tr><td>Apr</td><td>4</td></tr>
</tbody>
<tbody>
<tr><td>May</td><td>5</td></tr>
</tbody>
</table>
</body>
</html>
</code></pre>
<p>[EDIT] Link my <a href="http://www.developerbuzz.com/2008/10/use-jquery-to-show-and-hide-part-of.html" rel="nofollow noreferrer">blog post</a> and working example.</p>
|
[
{
"answer_id": 215227,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 2,
"selected": false,
"text": "<tbody> none table-row-group block"
},
{
"answer_id": 215231,
"author": "Parand",
"author_id": 13055,
"author_profile": "https://Stackoverflow.com/users/13055",
"pm_score": 7,
"selected": true,
"text": "<table>\n <tbody>\n <tr><td>Column1</td><td>Column2</td></tr>\n <tr><td>Column1</td><td>Column2</td></tr>\n <tr class=\"Show_Rows\"><td>Start</td><td>Hiding</td></tr>\n </tbody>\n <tbody class=\"Table_Middle\" style=\"display:none\">\n <tr><td>Column1</td><td>Column2</td></tr>\n <tr><td>Column1</td><td>Column2</td></tr>\n <tr><td>Column1</td><td>Column2</td></tr>\n </tbody>\n <tbody>\n <tr class=\"Show_Rows\"><td>End</td><td>Hiding</td></tr>\n <tr><td>Column1</td><td>Column2</td></tr>\n <tr><td>Column1</td><td>Column2</td></tr>\n </tbody>\n</table>\n\n\n$('#something').click( function() {\n $('.Table_Middle').hide();\n $('.Show_Rows').show();\n});\n\n$('.Show_Rows').click( function() { \n $('.Show_Rows').hide();\n $('.Table_Middle').show();\n});\n"
},
{
"answer_id": 215238,
"author": "SpoonMeiser",
"author_id": 1577190,
"author_profile": "https://Stackoverflow.com/users/1577190",
"pm_score": 1,
"selected": false,
"text": "<table>\n <thead>\n <tr>\n <th>Col1</th>\n <th>Col2</th>\n <th>Col3</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>data1</td>\n <td>data1</td>\n <td>data1</td>\n </tr>\n ...\n </tbody>\n <tbody id=\"hidden-rows\">\n <tr>\n <td colspan=\"3\">\n <a href=\"#\" onclick=\"$('#hidden-rows').hide();$('#extra-rows').show();\">\n Show hidden rows\n </a>\n </td>\n </tr>\n </tbody>\n <tbody id=\"extra-rows\" style=\"display: none;\">\n <tr>\n <td>data1</td>\n <td>data1</td>\n <td>data1</td>\n </tr>\n ...\n </tbody>\n <tbody>\n <tr>\n <td>data1</td>\n <td>data1</td>\n <td>data1</td>\n </tr>\n ...\n </tbody>\n</table>\n $(document).ready(function() {\n $('tr.Table_Middle').hide();\n});\n"
},
{
"answer_id": 215243,
"author": "Dan Herbert",
"author_id": 392,
"author_profile": "https://Stackoverflow.com/users/392",
"pm_score": 2,
"selected": false,
"text": "<tr /> Table_Middle colspan // jQuery chaining is useful here\n $(\".Table_Middle\").hide()\n .eq(0)\n .before('<tr colspan=\"X\" class=\"showFull\">Show Full Table<tr/>');\n\n$(\".showFull\").click(function() {\n $(this).toggle();\n $(\".Table_Middle\").toggle();\n});\n"
},
{
"answer_id": 217315,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 2,
"selected": false,
"text": "<table id=\"myTable\">\n <tbody>\n <tr><td>Cell</td><td>Cell</td></tr>\n <tr><td>Cell</td><td>Cell</td></tr>\n <tr><td>Cell</td><td>Cell</td></tr>\n <tr><td>Cell</td><td>Cell</td></tr>\n <tr><td>Cell</td><td>Cell</td></tr>\n </tbody>\n</table>\n class <table class=\"hidey_2\"> var showTopAndBottom = 2,\n minRows = 4,\n $rows = $('#myTable tr').length),\n length = $rows.length\n;\nif (length > minRows) {\n $rows\n .slice(showTopAndBottom, length - showTopAndBottom)\n .hide()\n ;\n $rows\n .eq(showTopAndBottom - 1)\n .after(\n // this colspan could be worked out by counting the cells in another row\n $(\"<tr><td colspan=\\\"2\\\">Show</td></tr>\").click(function() {\n $(this)\n .remove()\n .nextAll()\n .show()\n ;\n })\n )\n ;\n}\n"
},
{
"answer_id": 1615615,
"author": "Elzo Valugi",
"author_id": 95353,
"author_profile": "https://Stackoverflow.com/users/95353",
"pm_score": 2,
"selected": false,
"text": "$(\"#table tr\").slice(1, 4).hide();\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3747/"
] |
215,236
|
<p>In Java, is there a programmatic way to find out how many concurrent threads are supported by a CPU?</p>
<p><strong>Update</strong></p>
<p>To clarify, I'm not trying to hammer the CPU with threads and I am aware of Runtime.getRuntime().availableProcessors() function, which provides me part of the information I'm looking for.</p>
<p>I want to find out if there's a way to automatically tune the size of thread pool so that:</p>
<ul>
<li>if I'm running on a 1-year old server, I get 2 threads (1 thread per CPU x an arbitrary multiplier of 2)</li>
<li>if I switch to an Intel i7 quad core two years from now (which supports 2 threads per core), I get 16 threads (2 logical threads per CPU x 4 CPUs x the arbitrary multiplier of 2).</li>
<li>if, instead, I use a eight core Ultrasparc T2 server (which supports 8 threads per core), I get 128 threads (8 threads per CPU x 8 CPUs x the arbitrary multiplier of 2)</li>
<li>if I deploy the same software on a cluster of 30 different machines, potentially purchased at different years, I don't need to read the CPU specs and set configuration options for every single one of them.</li>
</ul>
|
[
{
"answer_id": 215259,
"author": "pipTheGeek",
"author_id": 28552,
"author_profile": "https://Stackoverflow.com/users/28552",
"pm_score": 4,
"selected": false,
"text": "availableProcessors() availableProcessors()"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20689/"
] |
215,248
|
<p>I'm using a ListView in C# to make a grid. I would like to find out a way to be able to highlight a specific cell, programatically. I only need to highlight one cell.</p>
<p>I've experimented with Owner Drawn subitems, but using the below code, I get highlighted cells, but no text! Are there any ideas on how to get this working? Thanks for your help.</p>
<pre><code>//m_PC.Location is the X,Y coordinates of the highlighted cell.
void listView1_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
{
if ((e.ItemIndex == m_PC.Location.Y) && (e.Item.SubItems.IndexOf(e.SubItem) == m_PC.Location.X))
e.SubItem.BackColor = Color.Blue;
else
e.SubItem.BackColor = Color.White;
e.DrawBackground();
e.DrawText();
}
</code></pre>
|
[
{
"answer_id": 215269,
"author": "Charlie",
"author_id": 18529,
"author_profile": "https://Stackoverflow.com/users/18529",
"pm_score": 5,
"selected": true,
"text": "// create a new list item with a subitem that has white text on a blue background\nListViewItem lvi = new ListViewItem( \"item text\" );\nlvi.UseItemStyleForSubItems = false;\nlvi.SubItems.Add( new ListViewItem.ListViewSubItem( lvi,\n \"subitem\", Color.White, Color.Blue, lvi.Font ) );\n UseItemStyleForSubItems"
},
{
"answer_id": 215425,
"author": "Mike Christiansen",
"author_id": 29249,
"author_profile": "https://Stackoverflow.com/users/29249",
"pm_score": 2,
"selected": false,
"text": "listView1.Items[1].UseItemStyleForSubItems = false;\nif (listView1.Items[1].SubItems[10].BackColor == Color.DarkBlue)\n{\n listView1.Items[1].SubItems[10].BackColor = Color.White;\n listView1.Items[1].SubItems[10].ForeColor = Color.Black;\n}\nelse\n{\n listView1.Items[1].SubItems[10].BackColor = Color.DarkBlue;\n listView1.Items[1].SubItems[10].ForeColor = Color.White;\n}\n"
},
{
"answer_id": 13020781,
"author": "Chris Asquith",
"author_id": 1766780,
"author_profile": "https://Stackoverflow.com/users/1766780",
"pm_score": 1,
"selected": false,
"text": "public void HighLightListViewRows(ListView xLst)\n {\n for (int i = 0; i < xLst.Items.Count; i++)\n {\n if (xLst.Items[i].SubItems[0].Text.ToString() == \"Medicare\")\n {\n for (int x = 0; x < xLst.Items[i].SubItems.Count; x++)\n {\n xLst.Items[i].SubItems[x].BackColor = Color.Yellow;\n }\n }\n }\n }\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29249/"
] |
215,252
|
<p>I get a "UUID mismatch" warning at the console when I try to build and run my app on my iPhone.</p>
<blockquote>
<p>warning: UUID mismatch detected with
the loaded library - on disk is:
/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS2.1.sdk/usr/lib/liblockdown.dylib
=uuid-mismatch-with-loaded-file,file="/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS2.1.sdk/usr/lib/liblockdown.dylib</p>
</blockquote>
<p>Anyone has this issue and managed to resolve the warning ?</p>
|
[
{
"answer_id": 2374659,
"author": "Sam Soffes",
"author_id": 118631,
"author_profile": "https://Stackoverflow.com/users/118631",
"pm_score": 2,
"selected": false,
"text": "$ sudo /Developer/Library/uninstall-devtools --mode=all\n"
},
{
"answer_id": 4289323,
"author": "Andrew Vilcsak",
"author_id": 418817,
"author_profile": "https://Stackoverflow.com/users/418817",
"pm_score": 7,
"selected": true,
"text": "/Developer/Platforms/iPhoneOS.platform/DeviceSupport/\n"
},
{
"answer_id": 4380646,
"author": "brian.clear",
"author_id": 181947,
"author_profile": "https://Stackoverflow.com/users/181947",
"pm_score": 3,
"selected": false,
"text": "/Developer/Platforms/iPhoneOS.platform/DeviceSupport/4.2.1 (8C148)\n /Developer/Platforms/iPhoneOS.platform/DeviceSupport/4.2.1 (8C148)\n /Developer/Platforms/iPhoneOS.platform/DeviceSupport/4.2.1 (8C148)\n Theres 380 files in \n\n/Developer/Platforms/iPhoneOS.platform/DeviceSupport/4.2.1 (8C148)\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1987/"
] |
215,267
|
<p>We've been using Trac for task/defect tracking and things were going well enough, but this morning it started serving up a 500 error. Looking in the Apache error_log, I get a stack trace that culminates in:</p>
<pre>
PythonHandler trac.web.modpython_frontend:
ExtractionError: Can't extract file(s) to egg cache
The following error occurred while trying to extract file(s) to the Python egg
cache:
[Errno 13] Permission denied: '/.python-eggs'
The Python egg cache directory is currently set to:
/.python-eggs
Perhaps your account does not have write access to this directory? You can
change the cache directory by setting the PYTHON_EGG_CACHE environment
variable to point to an accessible directory
</pre>
<p>So I explicitly set PYTHON_EGG_CACHE to /srv/trac/plugin-cache. I restarted Apache. Yet I get the same error (it still says "egg cache directory current set to: \n\n /.python_eggs.")</p>
<p>How should I proceed? Is the simplest thing to do to reinstall Trac? If I go that route, what steps do I need to take to ensure that I don't lose existing data?</p>
|
[
{
"answer_id": 215298,
"author": "agnul",
"author_id": 6069,
"author_profile": "https://Stackoverflow.com/users/6069",
"pm_score": 4,
"selected": true,
"text": "export PYTHON_EGG_CACHE=/tmp/python_eggs\n"
},
{
"answer_id": 215303,
"author": "Bob Nadler",
"author_id": 2514,
"author_profile": "https://Stackoverflow.com/users/2514",
"pm_score": 1,
"selected": false,
"text": "SetEnv PYTHON_EGG_CACHE /.python-eggs"
},
{
"answer_id": 215401,
"author": "Simon",
"author_id": 22404,
"author_profile": "https://Stackoverflow.com/users/22404",
"pm_score": 1,
"selected": false,
"text": "PYTHON_EGG_CACHE"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10116/"
] |
215,271
|
<p>I've got a <strong>large</strong> array of primitive types (double).
How do I sort the elements in <strong>descending order</strong>?</p>
<p>Unfortunately the Java API doesn't support sorting of <strong>primitive</strong> types with a Comparator.</p>
<p>The first approach that probably comes to mind is to convert it to a list of objects (boxing):</p>
<pre><code>double[] array = new double[1048576];
Arrays.stream(array).boxed().sorted(Collections.reverseOrder())…
</code></pre>
<p>This solution is probably good enough for many (or even most) use cases but <strong>boxing</strong> each primitive in the array is <strong>too slow and causes a lot of GC pressure</strong> if the array is large!</p>
<p>Another approach would be to sort and then reverse:</p>
<pre><code>double[] array = new double[1048576];
...
Arrays.sort(array);
// reverse the array
for (int i = 0; i < array.length / 2; i++) {
// swap the elements
double temp = array[i];
array[i] = array[array.length - (i + 1)];
array[array.length - (i + 1)] = temp;
}
</code></pre>
<p><strong>This approach can also be too slow</strong> if the array is already sorted quite well.</p>
<p>What's a better alternative if the arrays are large and performance is the major optimization goal?</p>
|
[
{
"answer_id": 215280,
"author": "Jason Cohen",
"author_id": 4926,
"author_profile": "https://Stackoverflow.com/users/4926",
"pm_score": 2,
"selected": false,
"text": "toList() Arrays.sort()"
},
{
"answer_id": 215283,
"author": "Eli Courtwright",
"author_id": 1694,
"author_profile": "https://Stackoverflow.com/users/1694",
"pm_score": 1,
"selected": false,
"text": "Arrays.asList double[] arr = new double[]{6.0, 5.0, 11.0, 7.0};\nList xs = Arrays.asList(arr);\nSystem.out.println(xs.size()); // prints 1\n List<Double> double[] Arrays.sort Object[] Arrays.asList Double[]"
},
{
"answer_id": 217477,
"author": "user29480",
"author_id": 29480,
"author_profile": "https://Stackoverflow.com/users/29480",
"pm_score": 5,
"selected": false,
"text": "for (int left=0, right=b.length-1; left<right; left++, right--) {\n // exchange the first and last\n int temp = b[left]; b[left] = b[right]; b[right] = temp;\n}\n"
},
{
"answer_id": 358528,
"author": "lakshmanaraj",
"author_id": 44541,
"author_profile": "https://Stackoverflow.com/users/44541",
"pm_score": 0,
"selected": false,
"text": "double temp;\n\nfor(int i=0,j=array.length-1; i < (array.length/2); i++, j--) {\n\n // swap the elements\n temp = array[i];\n array[i] = array[j];\n array[j] = temp;\n}\n"
},
{
"answer_id": 423602,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "double[] array = new double[1048576];\n Arrays.sort(array,Collections.reverseOrder());\n"
},
{
"answer_id": 7414867,
"author": "Sean Patrick Floyd",
"author_id": 342852,
"author_profile": "https://Stackoverflow.com/users/342852",
"pm_score": 3,
"selected": false,
"text": "Arrays.asList() Collections.reverse() int[] intArr = { 1, 2, 3, 4, 5 };\nfloat[] floatArr = { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f };\ndouble[] doubleArr = { 1.0d, 2.0d, 3.0d, 4.0d, 5.0d };\nbyte[] byteArr = { 1, 2, 3, 4, 5 };\nshort[] shortArr = { 1, 2, 3, 4, 5 };\nCollections.reverse(Ints.asList(intArr));\nCollections.reverse(Floats.asList(floatArr));\nCollections.reverse(Doubles.asList(doubleArr));\nCollections.reverse(Bytes.asList(byteArr));\nCollections.reverse(Shorts.asList(shortArr));\nSystem.out.println(Arrays.toString(intArr));\nSystem.out.println(Arrays.toString(floatArr));\nSystem.out.println(Arrays.toString(doubleArr));\nSystem.out.println(Arrays.toString(byteArr));\nSystem.out.println(Arrays.toString(shortArr));\n"
},
{
"answer_id": 25070560,
"author": "Green Beret",
"author_id": 873708,
"author_profile": "https://Stackoverflow.com/users/873708",
"pm_score": -1,
"selected": false,
"text": "Double[] d = {5.5, 1.3, 8.8};\nArrays.sort(d, Collections.reverseOrder());\nSystem.out.println(Arrays.toString(d));\n"
},
{
"answer_id": 27095994,
"author": "Brandon",
"author_id": 1237044,
"author_profile": "https://Stackoverflow.com/users/1237044",
"pm_score": 6,
"selected": true,
"text": "double[] array = new double[1048576];\n...\nPrimitive.sort(array, (d1, d2) -> Double.compare(d2, d1), false);\n <dependency>\n <groupId>net.mintern</groupId>\n <artifactId>primitive</artifactId>\n <version>1.2.1</version>\n</dependency>\n false sort"
},
{
"answer_id": 36643885,
"author": "madfree",
"author_id": 6017611,
"author_profile": "https://Stackoverflow.com/users/6017611",
"pm_score": 2,
"selected": false,
"text": "import java.util.Arrays;\n\npublic class SimpleDescending {\n\n public static void main(String[] args) {\n\n // unsorted array\n int[] integerList = {55, 44, 33, 88, 99};\n\n // Getting the natural (ascending) order of the array\n Arrays.sort(integerList);\n\n // Getting the last item of the now sorted array (which represents the maximum, in other words: highest number)\n int max = integerList.length-1;\n\n // reversing the order with a simple for-loop\n System.out.println(\"Array in descending order:\");\n for(int i=max; i>=0; i--) {\n System.out.println(integerList[i]);\n }\n\n // You could make the code even shorter skipping the variable max and use\n // \"int i=integerList.length-1\" instead of int \"i=max\" in the parentheses of the for-loop\n }\n}\n"
},
{
"answer_id": 39102936,
"author": "user462990",
"author_id": 462990,
"author_profile": "https://Stackoverflow.com/users/462990",
"pm_score": 0,
"selected": false,
"text": "int getOrder (double num, double[] array){\n double[] b = new double[array.length];\n for (int i = 0; i < array.length; i++){\n b[i] = array[i];\n }\n Arrays.sort(b);\n for (int i = 0; i < b.length; i++){\n if ( num < b[i]) return i;\n }\n return b.length;\n}\n double[] b = array; // makes b point to array. so beware!\n"
},
{
"answer_id": 40461663,
"author": "Shravan Kumar",
"author_id": 6396218,
"author_profile": "https://Stackoverflow.com/users/6396218",
"pm_score": 2,
"selected": false,
"text": "Before sorting the given array multiply each element by -1 \n for(int i=0;i<arr.length;i++)\n arr[i]=-arr[i];\nArrays.sort(arr);\nfor(int i=0;i<arr.length;i++)\n arr[i]=-arr[i];\n"
},
{
"answer_id": 41906001,
"author": "tanghao",
"author_id": 2693476,
"author_profile": "https://Stackoverflow.com/users/2693476",
"pm_score": 0,
"selected": false,
"text": "double[] nums = Arrays.stream(nums).boxed().\n .sorted((i1, i2) -> Double.compare(i2, i1))\n .mapToDouble(Double::doubleValue)\n .toArray();\n"
},
{
"answer_id": 46674965,
"author": "Catalin Pit",
"author_id": 8428191,
"author_profile": "https://Stackoverflow.com/users/8428191",
"pm_score": -1,
"selected": false,
"text": "public static int[] sortDescending(int[] array)\n{\n int[] newArr = new int[array.length];\n\n for(int i = 0; i < array.length; i++)\n {\n newArr[i] = array[i];\n }\n\n boolean flag = true;\n int tempValue;\n\n while(flag) \n {\n flag = false;\n\n for(int i = 0; i < newArr.length - 1; i++) \n {\n if(newArr[i] < newArr[i+1])\n {\n tempValue = newArr[i];\n newArr[i] = newArr[i+1];\n newArr[i+1] = tempValue;\n flag = true;\n }\n }\n }\n\n return newArr;\n}\n"
},
{
"answer_id": 48996951,
"author": "alamshahbaz16497",
"author_id": 9080948,
"author_profile": "https://Stackoverflow.com/users/9080948",
"pm_score": 0,
"selected": false,
"text": "double[] arr = {13.6, 7.2, 6.02, 45.8, 21.09, 9.12, 2.53, 100.4};\n\nDouble[] boxedarr = Arrays.stream( arr ).boxed().toArray( Double[]::new );\nArrays.sort(boxedarr, Collections.reverseOrder());\nSystem.out.println(Arrays.toString(boxedarr));\n"
},
{
"answer_id": 52737272,
"author": "MJA",
"author_id": 2268647,
"author_profile": "https://Stackoverflow.com/users/2268647",
"pm_score": 0,
"selected": false,
"text": "int[] arr = {3,2,1,3};\nList<Integer> list = new ArrayList<>();\nArrays.stream(arr).forEach(i -> list.add(i));\nlist.stream().sorted(Comparator.reverseOrder()).forEach(System.out::println);\n"
},
{
"answer_id": 53379879,
"author": "Shubham Gaur",
"author_id": 5212179,
"author_profile": "https://Stackoverflow.com/users/5212179",
"pm_score": 0,
"selected": false,
"text": "double s =-1;\n double[] n = {111.5, 111.2, 110.5, 101.3, 101.9, 102.1, 115.2, 112.1};\n for(int i = n.length-1;i>=0;--i){\n int k = i-1;\n while(k >= 0){\n if(n[i]>n[k]){\n s = n[k];\n n[k] = n[i];\n n[i] = s;\n }\n k --;\n }\n }\n System.out.println(Arrays.toString(n));\n it gives time complexity O(n^2) but i hope its work\n"
},
{
"answer_id": 58489083,
"author": "Murtaza Patrawala",
"author_id": 9499784,
"author_profile": "https://Stackoverflow.com/users/9499784",
"pm_score": 4,
"selected": false,
"text": "int arr = new int[]{1,2,3,4,5};\nArrays.stream(arr).boxed().sorted(Collections.reverseOrder()).mapToInt(Integer::intValue).toArray();\n"
},
{
"answer_id": 64168465,
"author": "Ankit Marothi",
"author_id": 3611104,
"author_profile": "https://Stackoverflow.com/users/3611104",
"pm_score": 0,
"selected": false,
"text": "package Algorithms.BranchAndBound;\n\nimport java.util.Arrays;\nimport java.util.Comparator;\n\npublic class KnapSack01 {\n private class ItemVals {\n double weight;\n double cost;\n double ratio;\n\n public ItemVals(double weight, double cost) {\n this.weight = weight;\n this.cost = cost;\n this.ratio = weight/cost;\n }\n }\n\n public ItemVals[] createSortedItemVals(double[] weight, double[] cost) {\n ItemVals[] itemVals = new ItemVals[weight.length];\n for(int i = 0; i < weight.length; i++) {\n ItemVals itemval = new ItemVals(weight[i], cost[i]);\n itemVals[i] = itemval;\n }\n Arrays.sort(itemVals, new Comparator<ItemVals>() {\n @Override\n public int compare(ItemVals o1, ItemVals o2) {\n return Double.compare(o2.ratio, o1.ratio);\n }\n });\n return itemVals;\n }\n\n public void printItemVals(ItemVals[] itemVals) {\n for (int i = 0; i < itemVals.length; i++) {\n System.out.println(itemVals[i].ratio);\n }\n }\n\n public static void main(String[] args) {\n KnapSack01 knapSack01 = new KnapSack01();\n double[] weight = {2, 3.14, 1.98, 5, 3};\n double[] cost = {40, 50, 100, 95, 30};\n ItemVals[] itemVals = knapSack01.createSortedItemVals(weight, cost);\n knapSack01.printItemVals(itemVals);\n }\n}\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4308/"
] |
215,302
|
<p>I am trying to create a file in the <code>/tmp</code> directory (working on a Linux UBUNTU 7.10), that has read/write/execute access for any user.</p>
<p>So I am using the</p>
<pre><code>open(fileName,O_CREAT|O_RDWR,0777)
</code></pre>
<p>function to create the file (from a C program) in <code>user1</code> account and I would like <code>user2</code> to be able to write to the specific file.</p>
<p>However, when I check the <code>/tmp</code> directory, using</p>
<pre><code>ls -l
</code></pre>
<p>I see that I do not have the <strong>write access permission</strong> for <code>user2</code> (considering the fact that <code>user1</code> created it, I have write access for <code>user1</code>, but <code>user2</code>, who is considered to be "others" does not have any access).</p>
<p>I have tried to use mode <code>0766</code> in the <code>open</code> function (and such combinations of <code>7</code> and <code>6</code> for modes), so that I may get write access for <code>user2</code>, but I still don't have the required access.</p>
|
[
{
"answer_id": 215318,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 2,
"selected": false,
"text": " mode_t oldmask = umask(0);\n fd = open(...);\n oldmask = umask(oldmask);\n assert(oldmask == 0);\n"
},
{
"answer_id": 215330,
"author": "Jaime Soriano",
"author_id": 28855,
"author_profile": "https://Stackoverflow.com/users/28855",
"pm_score": 2,
"selected": false,
"text": "#include <sys/types.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n\nint main() {\n creat(\"/tmp/foo\", 0);\n chmod(\"/tmp/foo\", 0666);\n}\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23486/"
] |
215,316
|
<p>I've got a tomcat 6 web app running with Apache httpd as the front end. I'm using mod_proxy and mod_proxy_ajp to forward the requests to tomcat. My server is running Ubuntu. Now I'm trying to use mod_rewrite to remove the leading www, so that my canonical website URL is <code>http://example.com</code> rather than <code>http://www.example.com</code></p>
<p>I've read a number of tutorials on using mod_rewrite, but I can't get any rewriting to work. I've tried putting the rewrite rule in an <code>.htaccess</code> file (after modifying my <code>/etc/apache/sites-available/default</code> file to set AllowOverride all). I've tried putting the rewrite rule in <code>apache2.conf</code>, <code>httpd.conf</code>, and <code>rewrite.conf</code>. I've tried all of these with rewrite logging turned on. The log file gets created, but Apache has written nothing to it. I thought maybe mod_proxy was somehow preventing the rewrite rules from being used, so I tried disabling that as well...and I still get no rewrite, and nothing to the log.</p>
<p>At this point I have absolutely no idea what to try next. How do I go about troubleshooting why Apache isn't using my rewrite rules?</p>
<p>For reference, here are my rewrite directives:</p>
<pre><code><IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www.example.com$ [NC]
RewriteRule ^(.*)$ http://example.com/$1 [R=301,L]
RewriteLog "/var/log/apache2/rewrite.log"
RewriteLogLevel 3
</IfModule>
</code></pre>
<p>the responses below are helpful to my particular case, but probably not as helpful to the community-at-large as answers about how you troubleshoot Apache directives in general. For example, is there a way to enable logging to the point where it would tell me which directives are being applied in which order as the request comes in?</p>
<p><strong>Edit 2</strong>: I've gotten things to work now. My virtual hosts weren't quite set up right, and I also didn't quite have the rewrite regex right. Here is the final rewrite directives I got to work:</p>
<pre><code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.*)$ http://example.com$1 [L,R=301]
</IfModule>
</code></pre>
|
[
{
"answer_id": 215345,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 0,
"selected": false,
"text": "RewriteRule .* www.google.com [RL]"
},
{
"answer_id": 215359,
"author": "K Prime",
"author_id": 29270,
"author_profile": "https://Stackoverflow.com/users/29270",
"pm_score": 1,
"selected": false,
"text": " RewriteEngine on\n RewriteCond %{HTTP_HOST} ^www.domain.com$ [NC]\n RewriteRule ^(.*)$ \"http\\:\\/\\/domain\\.com\\/$1\" [R=301,L]\n\n</IfModule>\n"
},
{
"answer_id": 215365,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 0,
"selected": false,
"text": "<VirtualHost *:80>\n ServerName www.domain.com\n Redirect permanent / http://domain.com\n</VirtualHost>\n\n\n<VirtualHost *:80>\n ServerName domain.com\n #The rest of the configuration (proxying, etc.)\n</VirtualHost>\n"
},
{
"answer_id": 215445,
"author": "Leonel Martins",
"author_id": 26673,
"author_profile": "https://Stackoverflow.com/users/26673",
"pm_score": 3,
"selected": true,
"text": "debug debug [RequestLogLevel][2] 9 # To force the use of \nRewriteEngine On\nRewriteCond %{HTTP_HOST} !^www\\.example\\.com [NC]\nRewriteCond %{HTTP_HOST} !^$\nRewriteRule ^/(.*) http://www.example.com/$1 [L,R]\n example.com www.example.com"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29262/"
] |
215,361
|
<p>I need a regex that matches all strings ending in .cs, but if they end in .g.cs they should not match. I'm using .NET regular expressions.</p>
|
[
{
"answer_id": 215366,
"author": "thr",
"author_id": 452521,
"author_profile": "https://Stackoverflow.com/users/452521",
"pm_score": 4,
"selected": true,
"text": "(?<!\\.g)\\.cs$\n ^.*(?<!\\.g)\\.cs$\n"
},
{
"answer_id": 215502,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 2,
"selected": false,
"text": "^(.*[^g]|.*[^.]g|)\\.cs$\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7532/"
] |
215,383
|
<p>I have a custom UIView that generates a set of subviews and display them in rows and columns like tiles. What I am trying to achieve is to allow the user to touch the screen and as the finger move, the tiles beneath it disappears. </p>
<p>The code below is the custom UIView that contains the tiles:</p>
<pre><code>- (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
int i, j;
int maxCol = floor(self.frame.size.width/TILE_SPACING);
int maxRow = floor(self.frame.size.height/TILE_SPACING);
CGRect frame = CGRectMake(0, 0, TILE_WIDTH, TILE_HEIGHT);
UIView *tile;
for (i = 0; i<maxCol; i++) {
for (j = 0; j < maxRow; j++) {
frame.origin.x = i * (TILE_SPACING) + TILE_PADDING;
frame.origin.y = j * (TILE_SPACING) + TILE_PADDING;
tile = [[UIView alloc] initWithFrame:frame];
[self addSubview:tile];
[tile release];
}
}
}
return self;
}
- (void)touchesBegan: (NSSet *)touches withEvent:(UIEvent *)event {
UIView *tile = [self hitTest:[[touches anyObject] locationInView:self] withEvent:nil];
if (tile != self)
[tile setHidden:YES];
}
- (void)touchesMoved: (NSSet *)touches withEvent:(UIEvent *)event {
UIView *tile = [self hitTest:[[touches anyObject] locationInView:self] withEvent:nil];
if (tile != self)
[tile setHidden:YES];
}
</code></pre>
<p>This approach works but however if the tiles get denser (i.e. small tiles and more tiles on the screen). The iPhone is less responsive as the finger move. It may be the hitTest taking a toll on the processor as it struggles to keep up but would like some opinions.</p>
<p>My questions are:</p>
<ol>
<li><p>Is this an efficient way / right way to implement the touchesMoved?</p></li>
<li><p>If it isn't, what would be the recommended approach?</p></li>
<li><p>I tried moving the functionality into a custom Tile class (a sub UIView) which the class above would create and add as a subview. This subview Tile can handle the TouchesBegan but as the finger move, the other tiles does not receive the TouchesBegan even since the touches are still part of the initial touch sequence. Is there a way to implement it through the subview Tile class, how do other tiles receive the TouchesBegan/TouchesMoved event as the finger move?</p></li>
</ol>
|
[
{
"answer_id": 215531,
"author": "Ben Gottlieb",
"author_id": 6694,
"author_profile": "https://Stackoverflow.com/users/6694",
"pm_score": 5,
"selected": true,
"text": " \n\n //In your init method, make sure each tile doesn't respond to clicks on its own\n ...\n tile.userInteractionEnabled = NO;\n ...\n\n\n - (void) touchesMoved: (NSSet *)touches withEvent:(UIEvent *)event {\n CGPoint tappedPt = [[touches anyObject] locationInView: self];\n int xPos = tappedPt.x / (TILE_SPACING + TILE_PADDING);\n int yPos = tappedPt.y / (TILE_SPACING + TILE_PADDING);\n int tilesAcross = (self.bounds.size.width / (TILE_SPACING + TILE_PADDING));\n int index = xPos + yPos * tilesAcross;\n\n if (index < self.subviews.count) {\n UIView *tappedTile = [self.subviews objectAtIndex: index];\n tappedTile.hidden = YES;\n }\n }\n\n\n //In your init method, make sure each tile doesn't respond to clicks on its own\n ...\n tile.userInteractionEnabled = NO;\n ...\n\n\n - (void) touchesMoved: (NSSet *)touches withEvent:(UIEvent *)event {\n CGPoint tappedPt = [[touches anyObject] locationInView: self];\n int xPos = tappedPt.x / (TILE_SPACING + TILE_PADDING);\n int yPos = tappedPt.y / (TILE_SPACING + TILE_PADDING);\n int tilesAcross = (self.bounds.size.width / (TILE_SPACING + TILE_PADDING));\n int index = xPos + yPos * tilesAcross;\n\n if (index < self.subviews.count) {\n UIView *tappedTile = [self.subviews objectAtIndex: index];\n tappedTile.hidden = YES;\n }\n }\n"
},
{
"answer_id": 472095,
"author": "Corey Floyd",
"author_id": 48311,
"author_profile": "https://Stackoverflow.com/users/48311",
"pm_score": 3,
"selected": false,
"text": "for (UIView* aSubview in self.subviews) {\n\n if([aSubview pointInside: [self convertPoint:touchPoint toView:aSubview] withEvent:event]){\n\n //Do stuff\n }\n}\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1987/"
] |
215,392
|
<p>I am busy writing my thesis (so, I guess this could count as a homework question). Now, one of the things that came up was the Unix <code>select</code> system call. I would like to add a reference to the appropriate man page, but all I can find that seems the slight bit official is the Single Unix Specification site that wants my money first. Sure, the Linux guys all have man pages, but they have real geeky urls that don't look like they will stay around forever. What to do? So far I am referring to <em>See SELECT(2) UNIX man page</em>...</p>
|
[
{
"answer_id": 215402,
"author": "warren",
"author_id": 4418,
"author_profile": "https://Stackoverflow.com/users/4418",
"pm_score": 0,
"selected": false,
"text": "man <command>"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215392",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2260/"
] |
215,399
|
<p>Suppose I have a class where I want the user to be able to have a reference to one of my members. Which is preferred?</p>
<pre><code>class Member;
class ClassWithWeakPtr
{
private:
boost::shared_ptr<Member> _member;
public:
boost::weak_ptr<Member> GetMember();
};
</code></pre>
<p>or</p>
<pre><code>class Member;
class ClassWithCppReference
{
private:
Member _member;
public:
Member& GetMember() {return _member;}
};
</code></pre>
<p>What do you think? When is one better than another?</p>
|
[
{
"answer_id": 215428,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 4,
"selected": false,
"text": "shared_ptr<> weak_ptr<> use weak_ptr<> shared_ptr<> ClassWithCppReference GetMember()"
},
{
"answer_id": 215553,
"author": "Sol",
"author_id": 27029,
"author_profile": "https://Stackoverflow.com/users/27029",
"pm_score": 2,
"selected": false,
"text": "_member shared_ptr weak_ptr shared_ptr"
},
{
"answer_id": 1164758,
"author": "Tobias",
"author_id": 118854,
"author_profile": "https://Stackoverflow.com/users/118854",
"pm_score": 0,
"selected": false,
"text": "const Member& GetMember() const;\nMember& GetMember(); // ideally, only if clients can modify it without\n // breaking any invariants of the Class\n\nweak_ptr< Member > GetMemberWptr(); // only if there is a specific need\n // for holding a weak pointer.\n GetMember() Class member GetMember()"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8123/"
] |
215,412
|
<p>Is there a way to programmatically change the screen resolution or enable/disable multiple monitors in Windows XP? For example to change from 1024x768 with one monitor to 1280x1024 on two monitors? I would be most interested in a win32 function to do this but anything that can be tied to a windows shortcut would suffice.</p>
|
[
{
"answer_id": 9828304,
"author": "a7drew",
"author_id": 4239,
"author_profile": "https://Stackoverflow.com/users/4239",
"pm_score": -1,
"selected": false,
"text": "#NoEnv ; Recommended for performance and compatibility with future AutoHotkey releases.\n#Warn ; Recommended for catching common errors.\nSendMode Input ; Recommended for new scripts due to its superior speed and reliability.\nSetWorkingDir %A_ScriptDir% ; Ensures a consistent starting directory.\n#1::\nSend {LWin}\nWinWaitActive Start menu\nSend Adjust Screen Resolution\nSend {enter}\nWinWaitActive Screen Resolution\nControlClick ComboBox3\nSend {PgDn}\nSend {Up} ; Select \"Show desktop only on 1\"\nSend {enter}\nSleep 3000 ; workaround - cannot select accept/revert window?\nSend {left}\nSend {enter} ; accept changes\nReturn\n#2::\nSend {LWin}\nWinWaitActive Start menu\nSend Adjust Screen Resolution\nSend {enter}\nWinWaitActive Screen Resolution\nControlClick ComboBox3\nSend {PgDn}\nSend {Up}\nSend {Up} ; Select \"Extend these displays\"\nSend {enter}\nSleep 3000 ; workaround - cannot select accept/revert window?\nSend {left}\nSend {enter} ; accept changes\nReturn\n"
},
{
"answer_id": 67980430,
"author": "koppor",
"author_id": 873282,
"author_profile": "https://Stackoverflow.com/users/873282",
"pm_score": 0,
"selected": false,
"text": "import win32api\nimport win32con\nimport pywintypes\n\ndevmode = pywintypes.DEVMODEType()\ndevmode.PelsWidth = 1920\ndevmode.PelsHeight = 1080\n\ndevmode.Fields = win32con.DM_PELSWIDTH | win32con.DM_PELSHEIGHT\nwin32api.ChangeDisplaySettings(devmode, 0)\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6320/"
] |
215,430
|
<p>I have to use unsigned integers that could span to more than 4 bytes, what type should I use?</p>
<p>PS Sorry for the "noobism" but that's it :D</p>
<p>NB: I need integers because i have to do divisions and care only for the integer parts and this way int are useful</p>
|
[
{
"answer_id": 215459,
"author": "An̲̳̳drew",
"author_id": 17035,
"author_profile": "https://Stackoverflow.com/users/17035",
"pm_score": 2,
"selected": false,
"text": "long long unsigned long long"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22963/"
] |
215,458
|
<p>The calculations in my code are well-tested, but because there is so much GUI code, my overall code coverage is lower than I'd like. Are there any guidelines on unit-testing GUI code? Does it even make sense?</p>
<p>For example, there are graphs in my app. I haven't been able to figure out how to automate the testing of the graphs. It takes a human eye, AFAIK, to check if the graph is correct.</p>
<p>(I'm using Java Swing)</p>
|
[
{
"answer_id": 1001011,
"author": "Dema",
"author_id": 407003,
"author_profile": "https://Stackoverflow.com/users/407003",
"pm_score": 3,
"selected": false,
"text": " Scenario: Dialog manipulation\n Given the frame \"SwingSet\" is visible\n When I click the menu \"File/About\"\n Then I should see the dialog \"About Swing!\"\n When I click the button \"OK\"\n Then I should not see the dialog \"About Swing!\"\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2959/"
] |
215,471
|
<p>In VS2008 I have written a C# service, an installer, and have created a setup package to install it. The service needs to load an xml file to operate. Where is the best place to put this file in the various filesystem folders offered by the VS setup project, and how do I then refer to these paths from my code?</p>
<p>I should point out the the service runs as <code>LocalService</code>, which means that the ApplicationData folder offered by the "User's Application Data Folder" item in the VS setup project is not accessible, even when "Install for all users" is used during installation. I could easily hack around this, but would like to understand best practice.</p>
|
[
{
"answer_id": 215538,
"author": "mohammedn",
"author_id": 29268,
"author_profile": "https://Stackoverflow.com/users/29268",
"pm_score": 3,
"selected": true,
"text": "string path = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);\n"
},
{
"answer_id": 7052450,
"author": "rudolf_franek",
"author_id": 872496,
"author_profile": "https://Stackoverflow.com/users/872496",
"pm_score": 1,
"selected": false,
"text": "/myKey=\"[TARGETDIR]\\\" Context.Parameters[\"myKey\"]"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14357/"
] |
215,497
|
<p>In Java, are there clear rules on when to use each of access modifiers, namely the default (package private), <code>public</code>, <code>protected</code> and <code>private</code>, while making <code>class</code> and <code>interface</code> and dealing with inheritance?</p>
|
[
{
"answer_id": 215505,
"author": "David Segonds",
"author_id": 13673,
"author_profile": "https://Stackoverflow.com/users/13673",
"pm_score": 14,
"selected": true,
"text": "public protected private"
},
{
"answer_id": 12401576,
"author": "Mechanical snail",
"author_id": 319931,
"author_profile": "https://Stackoverflow.com/users/319931",
"pm_score": 7,
"selected": false,
"text": "private protected public public protected private public private private[this] class Test {\n public static void main(final String ... args) {\n System.out.println(Example.leakPrivateClass()); // OK\n Example.leakPrivateClass().secretMethod(); // error\n }\n}\n\nclass Example {\n private static class NestedClass {\n public void secretMethod() {\n System.out.println(\"Hello\");\n }\n }\n public static NestedClass leakPrivateClass() {\n return new NestedClass();\n }\n}\n Test.java:4: secretMethod() in Example.NestedClass is defined in an inaccessible class or interface\n Example.leakPrivateClass().secretMethod(); // error\n ^\n1 error\n"
},
{
"answer_id": 13102616,
"author": "Ravi",
"author_id": 1162620,
"author_profile": "https://Stackoverflow.com/users/1162620",
"pm_score": 6,
"selected": false,
"text": "public protected private"
},
{
"answer_id": 13938807,
"author": "Hoa Nguyen",
"author_id": 619860,
"author_profile": "https://Stackoverflow.com/users/619860",
"pm_score": 7,
"selected": false,
"text": "private default package-private protected package scope + child public +—-———————————————+————————————+———————————+\n| | Same | Different |\n| | Package | Packages |\n+—————————————————+————————————+———————————+\n| private | D | |\n+—————————————————+————————————+———————————+\n| package-private | | |\n| (no modifier) | D R I | |\n+—————————————————+————————————+———————————+\n| protected | D R I | I |\n+—————————————————+————————————+———————————+\n| public | D R I | R I |\n+—————————————————+————————————+———————————+\n"
},
{
"answer_id": 14247032,
"author": "Abdull",
"author_id": 923560,
"author_profile": "https://Stackoverflow.com/users/923560",
"pm_score": 8,
"selected": false,
"text": "____________________________________________________________________\n | highest precedence <---------> lowest precedence\n*———————————————+———————————————+———————————+———————————————+———————\n \\ xCanBeSeenBy | this | any class | this subclass | any\n \\__________ | class | in same | in another | class\n \\ | nonsubbed | package | package | \nModifier of x \\ | | | | \n————————————————*———————————————+———————————+———————————————+———————\npublic | ✔ | ✔ | ✔ | ✔ \n————————————————+———————————————+———————————+———————————————+———————\nprotected | ✔ | ✔ | ✔ | ✘ \n————————————————+———————————————+———————————+———————————————+———————\npackage-private | | | |\n(no modifier) | ✔ | ✔ | ✘ | ✘ \n————————————————+———————————————+———————————+———————————————+———————\nprivate | ✔ | ✘ | ✘ | ✘ \n____________________________________________________________________\n"
},
{
"answer_id": 20009675,
"author": "Eng.Fouad",
"author_id": 597657,
"author_profile": "https://Stackoverflow.com/users/597657",
"pm_score": 6,
"selected": false,
"text": "protected Father Son package fatherpackage;\n\npublic class Father\n{\n\n}\n\n-------------------------------------------\n\npackage sonpackage;\n\npublic class Son extends Father\n{\n\n}\n foo() Father package fatherpackage;\n\npublic class Father\n{\n protected void foo(){}\n}\n foo() foo() fatherpackage package fatherpackage;\n\npublic class SomeClass\n{\n public void someMethod(Father f, Son s)\n {\n f.foo();\n s.foo();\n }\n}\n this super package sonpackage;\n\npublic class Son extends Father\n{\n public void sonMethod()\n {\n this.foo();\n super.foo();\n }\n}\n package fatherpackage;\n\npublic class Father\n{\n public void fatherMethod(Father f)\n {\n f.foo(); // valid even if foo() is private\n }\n}\n\n-------------------------------------------\n\npackage sonpackage;\n\npublic class Son extends Father\n{\n public void sonMethod(Son s)\n {\n s.foo();\n }\n}\n foo() fatherpackage package fatherpackage;\n\npublic class Son extends Father\n{\n public void sonMethod(Father f)\n {\n f.foo();\n }\n}\n foo() fatherpackage package sonpackage;\n\npublic class Son extends Father\n{\n public void sonMethod(Father f)\n {\n f.foo(); // compilation error\n }\n}\n package sonpackage;\n\npublic class SomeClass\n{\n public void someMethod(Son s) throws Exception\n {\n s.foo(); // compilation error\n }\n}\n"
},
{
"answer_id": 30462069,
"author": "amila isura",
"author_id": 4395148,
"author_profile": "https://Stackoverflow.com/users/4395148",
"pm_score": 4,
"selected": false,
"text": "String name = \"john\";\n\npublic int age(){\n return age;\n}\n Public class Details{\n\n private String name;\n\n public void setName(String n){\n this.name = n;\n }\n\n public String getName(){\n return this.name;\n }\n}\n public void cal(){\n\n}\n class Van{\n\n protected boolean speed(){\n\n }\n}\n\nclass Car{\n boolean speed(){\n }\n\n}\n"
},
{
"answer_id": 33627846,
"author": "aioobe",
"author_id": 276052,
"author_profile": "https://Stackoverflow.com/users/276052",
"pm_score": 9,
"selected": false,
"text": "i j k l long internalCounter void beforeRender() void saveGame(File dst)"
},
{
"answer_id": 38815021,
"author": "Aftab",
"author_id": 1599792,
"author_profile": "https://Stackoverflow.com/users/1599792",
"pm_score": 4,
"selected": false,
"text": "// Saved in file A.java\npackage pack;\n\nclass A{\n void msg(){System.out.println(\"Hello\");}\n}\n\n// Saved in file B.java\npackage mypack;\nimport pack.*;\n\nclass B{\n public static void main(String args[]){\n A obj = new A(); // Compile Time Error\n obj.msg(); // Compile Time Error\n }\n}\n // Saved in file A.java\n\npackage pack;\npublic class A{\n public void msg(){System.out.println(\"Hello\");}\n}\n\n// Saved in file B.java\n\npackage mypack;\nimport pack.*;\n\nclass B{\n public static void main(String args[]){\n A obj = new A();\n obj.msg();\n }\n}\n class A{\n private int data = 40;\n private void msg(){System.out.println(\"Hello java\");}\n}\n\npublic class Simple{\n public static void main(String args[]){\n A obj = new A();\n System.out.println(obj.data); // Compile Time Error\n obj.msg(); // Compile Time Error\n }\n}\n // Saved in file A.java\npackage pack;\npublic class A{\n protected void msg(){System.out.println(\"Hello\");}\n}\n\n// Saved in file B.java\npackage mypack;\nimport pack.*;\n\nclass B extends A{\n public static void main(String args[]){\n B obj = new B();\n obj.msg();\n }\n}\n"
},
{
"answer_id": 40647093,
"author": "ישו אוהב אותך",
"author_id": 4758255,
"author_profile": "https://Stackoverflow.com/users/4758255",
"pm_score": 3,
"selected": false,
"text": "╔═════════════╦═══════╦═════════╦══════════╦═══════╗\n║ Modifier ║ Class ║ Package ║ Subclass ║ World ║\n╠═════════════╬═══════╬═════════╬══════════╬═══════╣\n║ public ║ Y ║ Y ║ Y ║ Y ║\n║ protected ║ Y ║ Y ║ Y ║ N ║\n║ no modifier ║ Y ║ Y ║ N ║ N ║\n║ private ║ Y ║ N ║ N ║ N ║\n╚═════════════╩═══════╩═════════╩══════════╩═══════╝\n"
},
{
"answer_id": 44771468,
"author": "Pritam Banerjee",
"author_id": 1475228,
"author_profile": "https://Stackoverflow.com/users/1475228",
"pm_score": 2,
"selected": false,
"text": "public private default protected default protected default"
},
{
"answer_id": 48784176,
"author": "Christophe Roussy",
"author_id": 657427,
"author_profile": "https://Stackoverflow.com/users/657427",
"pm_score": 2,
"selected": false,
"text": "Outside world -> Package (SecurityEntryClass ---> Package private classes)\n"
},
{
"answer_id": 59220073,
"author": "yoAlex5",
"author_id": 4770877,
"author_profile": "https://Stackoverflow.com/users/4770877",
"pm_score": 4,
"selected": false,
"text": "class field method field method class class method public default Nested class package"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/625/"
] |
215,515
|
<p>I have a simple class that essentially just holds some values. I have overridden the <code>ToString()</code> method to return a nice string representation.</p>
<p>Now, I want to create a <code>ToXml()</code> method, that will return something like this:</p>
<pre><code><Song>
<Artist>Bla</Artist>
<Title>Foo</Title>
</Song>
</code></pre>
<p>Of course, I could just use a <code>StringBuilder</code> here, but I would like to return an <code>XmlNode</code> or <code>XmlElement</code>, to be used with <code>XmlDocument.AppendChild</code>.</p>
<p>I do not seem to be able to create an <code>XmlElement</code> other than calling <code>XmlDocument.CreateElement</code>, so I wonder if I have just overlooked anything, or if I really either have to pass in either a <code>XmlDocument</code> or <code>ref XmlElement</code> to work with, or have the function return a String that contains the XML I want?</p>
|
[
{
"answer_id": 215565,
"author": "Panos",
"author_id": 8049,
"author_profile": "https://Stackoverflow.com/users/8049",
"pm_score": 4,
"selected": false,
"text": "XmlNode XmlElement, XmlAttribute, XmlCDataSection XmlDocument XmlDocument.AppendChild() XmlDocument.ImportNode()"
},
{
"answer_id": 215568,
"author": "mohammedn",
"author_id": 29268,
"author_profile": "https://Stackoverflow.com/users/29268",
"pm_score": 6,
"selected": false,
"text": "public XElement ToXml()\n{\n XElement element = new XElement(\"Song\",\n new XElement(\"Artist\", \"bla\"),\n new XElement(\"Title\", \"Foo\"));\n\n return element;\n}\n"
},
{
"answer_id": 215659,
"author": "Vlad N",
"author_id": 28472,
"author_profile": "https://Stackoverflow.com/users/28472",
"pm_score": 5,
"selected": true,
"text": "ToXML()"
},
{
"answer_id": 216108,
"author": "Robert Rossney",
"author_id": 19403,
"author_profile": "https://Stackoverflow.com/users/19403",
"pm_score": 1,
"selected": false,
"text": "XmlElement XmlNode XmlDocument XElement XmlSerializer"
},
{
"answer_id": 2152131,
"author": "someone",
"author_id": 260618,
"author_profile": "https://Stackoverflow.com/users/260618",
"pm_score": 2,
"selected": false,
"text": "XmlDocument ToXML XmlDocument returnedDocument = Your_Class.ToXML();\n\nXmlDocument finalDocument = new XmlDocument();\nXmlElement createdElement = finalDocument.CreateElement(\"Desired_Element_Name\");\ncreatedElement.InnerXML = docResult.InnerXML;\nfinalDocument.AppendChild(createdElement);\n"
},
{
"answer_id": 9305175,
"author": "Matt Connolly",
"author_id": 365932,
"author_profile": "https://Stackoverflow.com/users/365932",
"pm_score": 2,
"selected": false,
"text": "XmlNode existing_node; // of some document, where we don't know necessarily know the XmlDocument...\nXmlDocument temp = new XmlDocument();\ntemp.LoadXml(\"<new><elements/></new>\");\nXmlNode new_node = existing_node.OwnerDocument.ImportNode(temp.DocumentElement, true);\nexisting_node.AppendChild(new_node);\n"
},
{
"answer_id": 11848316,
"author": "Shelest",
"author_id": 998872,
"author_profile": "https://Stackoverflow.com/users/998872",
"pm_score": -1,
"selected": false,
"text": "XmlDocumnt xdoc = new XmlDocument;\nXmlNode songNode = xdoc.CreateNode(XmlNodeType.Element, \"Song\", schema)\nxdoc.AppendChild.....\n"
},
{
"answer_id": 13077037,
"author": "K0D4",
"author_id": 1181624,
"author_profile": "https://Stackoverflow.com/users/1181624",
"pm_score": 4,
"selected": false,
"text": "//Node is an XmlNode pulled from an XmlDocument\nXmlElement e = node.OwnerDocument.CreateElement(\"MyNewElement\");\ne.InnerText = \"Some value\";\nnode.AppendChild(e);\n"
},
{
"answer_id": 19300087,
"author": "ChrisH",
"author_id": 1820796,
"author_profile": "https://Stackoverflow.com/users/1820796",
"pm_score": 2,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Xml;\nusing System.IO;\n\nnamespace FWFWLib {\n public abstract class ContainerDoc : XmlDocument {\n\n protected XmlElement root = null;\n protected const string XPATH_BASE = \"/$DATA_TYPE$\";\n protected const string XPATH_SINGLE_FIELD = \"/$DATA_TYPE$/$FIELD_NAME$\";\n\n protected const string DOC_DATE_FORMAT = \"yyyyMMdd\";\n protected const string DOC_TIME_FORMAT = \"HHmmssfff\";\n protected const string DOC_DATE_TIME_FORMAT = DOC_DATE_FORMAT + DOC_TIME_FORMAT;\n\n protected readonly string datatypeName = \"containerDoc\";\n protected readonly string execid = System.Guid.NewGuid().ToString().Replace( \"-\", \"\" );\n\n #region startup and teardown\n public ContainerDoc( string execid, string datatypeName ) {\n root = this.DocumentElement;\n this.datatypeName = datatypeName;\n this.execid = execid;\n if( null == datatypeName || \"\" == datatypeName.Trim() ) {\n throw new InvalidDataException( \"Data type name can not be blank\" );\n }\n Init();\n }\n\n public ContainerDoc( string datatypeName ) {\n root = this.DocumentElement;\n this.datatypeName = datatypeName;\n if( null == datatypeName || \"\" == datatypeName.Trim() ) {\n throw new InvalidDataException( \"Data type name can not be blank\" );\n }\n Init();\n }\n\n private ContainerDoc() { /*...*/ }\n\n protected virtual void Init() {\n string basexpath = XPATH_BASE.Replace( \"$DATA_TYPE$\", datatypeName );\n root = (XmlElement)this.SelectSingleNode( basexpath );\n if( null == root ) {\n root = this.CreateElement( datatypeName );\n this.AppendChild( root );\n }\n SetFieldValue( \"createdate\", DateTime.Now.ToString( DOC_DATE_FORMAT ) );\n SetFieldValue( \"createtime\", DateTime.Now.ToString( DOC_TIME_FORMAT ) );\n }\n #endregion\n\n #region setting/getting data fields\n public virtual void SetFieldValue( string fieldname, object val ) {\n if( null == fieldname || \"\" == fieldname.Trim() ) {\n return;\n }\n fieldname = fieldname.Replace( \" \", \"_\" ).ToLower();\n string xpath = XPATH_SINGLE_FIELD.Replace( \"$FIELD_NAME$\", fieldname ).Replace( \"$DATA_TYPE$\", datatypeName );\n XmlNode node = this.SelectSingleNode( xpath );\n if( null != node ) {\n if( null != val ) {\n node.InnerText = val.ToString();\n }\n } else {\n node = this.CreateElement( fieldname );\n if( null != val ) {\n node.InnerText = val.ToString();\n }\n root.AppendChild( node );\n }\n }\n\n public virtual string FieldValue( string fieldname ) {\n if( null == fieldname ) {\n fieldname = \"\";\n }\n fieldname = fieldname.ToLower().Trim();\n string rtn = \"\";\n XmlNode node = this.SelectSingleNode( XPATH_SINGLE_FIELD.Replace( \"$FIELD_NAME$\", fieldname ).Replace( \"$DATA_TYPE$\", datatypeName ) );\n if( null != node ) {\n rtn = node.InnerText;\n }\n return rtn.Trim();\n }\n\n public virtual string ToXml() {\n return this.OuterXml;\n }\n\n public override string ToString() {\n return ToXml();\n }\n #endregion\n\n #region io\n public void WriteTo( string filename ) {\n TextWriter tw = new StreamWriter( filename );\n tw.WriteLine( this.OuterXml );\n tw.Close();\n tw.Dispose();\n }\n\n public void WriteTo( Stream strm ) {\n TextWriter tw = new StreamWriter( strm );\n tw.WriteLine( this.OuterXml );\n tw.Close();\n tw.Dispose();\n }\n\n public void WriteTo( TextWriter writer ) {\n writer.WriteLine( this.OuterXml );\n }\n #endregion\n\n }\n}\n"
},
{
"answer_id": 72846514,
"author": "Faraz Ahmed",
"author_id": 6002727,
"author_profile": "https://Stackoverflow.com/users/6002727",
"pm_score": 0,
"selected": false,
"text": "string elementWithData = @\"<Song>\n <Artist>Bla</Artist>\n <Title>Foo</Title>\n </Song>\";\n\nXElement e = XElement.Parse(elementWithData);\nvar nodeToCopy = ToXmlNode(e);\n//for using this node in other XmlDocument\nvar xmlNodeToUseInOtherXmlDocument = nodeToCopy.FirstChild;\n static XmlNode ToXmlNode(XElement element)\n{\n using (XmlReader xmlReader = element.CreateReader())\n {\n XmlDocument xmlDoc = new XmlDocument();\n xmlDoc.Load(xmlReader);\n return xmlDoc;\n }\n}\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91/"
] |
215,516
|
<p>I am working on a winforms html editor with multiple editor windows as each editor window will be written to a database field.</p>
<p>I am creating the editor windows as a control array and was hoping to just have one toolbar above them that would handle the events such as apply bold, italic... based on the window I was currently in. Unfortunately obviously the event handler of an event on the toolbar doesn't know what the control selected before it was. </p>
<p>Is there a way to get this or should I be adding an onenter event to each editor window and storing statically the last editor window used.</p>
|
[
{
"answer_id": 215637,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 0,
"selected": false,
"text": "[SerializableAttribute]\n[ComVisibleAttribute(true)]\npublic delegate void EventHandler(\n Object sender,\n EventArgs e\n)\n sender"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16989/"
] |
215,517
|
<p>Does anyone know of any code or tools that can strip literal values out of SQL statements?</p>
<p>The reason for asking is I want to correctly judge the SQL workload in our database and I'm worried I might miss out on bad statements whose resource usage get masked because they are displayed as separate statements. When, in reality, they are pretty much the same thing except for different IDs being passed in. </p>
<p>I'd prefer a database independent solution if any exists. I had thought there might be a nifty Perl module for this but I haven't found any.</p>
<p>Thanks for your help.</p>
|
[
{
"answer_id": 215527,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 0,
"selected": false,
"text": "SQL '' (/'.*'/STRING_LITERAL/) /\\d*/NUMERIC_LITERAL/"
},
{
"answer_id": 215543,
"author": "John Nilsson",
"author_id": 24243,
"author_profile": "https://Stackoverflow.com/users/24243",
"pm_score": -1,
"selected": false,
"text": "sed $ cat sql.txt\nSELECT * FROM USER WHERE USERID = 123 OR USERNAME LIKE 'Name1%'\nSELECT * FROM USER WHERE USERID = 124 OR USERNAME LIKE 'Name2%'\nSELECT * FROM USER WHERE USERID = 125 OR USERNAME LIKE 'Name3%'\nSELECT * FROM USER WHERE USERID = 126 OR USERNAME LIKE 'Name4%'\n\n$ sed -e \"s/\\([0-9]\\+\\)\\|\\('[^']*'\\)/?/g\" sql.txt\nSELECT * FROM USER WHERE USERID = ? OR USERNAME LIKE ?\nSELECT * FROM USER WHERE USERID = ? OR USERNAME LIKE ?\nSELECT * FROM USER WHERE USERID = ? OR USERNAME LIKE ?\nSELECT * FROM USER WHERE USERID = ? OR USERNAME LIKE ?\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29286/"
] |
215,524
|
<p>Some iPhone applications, such as Pandora seem to directly manipulate the hardware volume and respond to physical volume button. How is this done?</p>
<p>AudioSessionServices allows you to get the current hardware output volume with the <code>kAudioSessionProperty_CurrentHardwareOutputVolume</code> property, but it is (allegedly) read-only.</p>
|
[
{
"answer_id": 215614,
"author": "catlan",
"author_id": 23028,
"author_profile": "https://Stackoverflow.com/users/23028",
"pm_score": 4,
"selected": true,
"text": "MPVolumeView *volumeView = [[MPVolumeView alloc] initWithFrame:CGRectMake(25, 378, 270, 30)];\n[self.view addSubview:volumeView];\n[volumeView release];\n"
},
{
"answer_id": 9507066,
"author": "blackjacx",
"author_id": 971329,
"author_profile": "https://Stackoverflow.com/users/971329",
"pm_score": 3,
"selected": false,
"text": "// AVAudiosession Delegate Method\n- (void)endInterruptionWithFlags:(NSUInteger)flags\n{\n // When interruption ends - set the apps audio session active again\n [[AVAudioSession sharedInstance] setActive:YES error:nil];\n\n if( flags == AVAudioSessionInterruptionFlags_ShouldResume ) {\n // Resume playback of song here!!!\n }\n}\n\n// Hardware Button Volume Callback\nvoid audioVolumeChangeListenerCallback (\n void *inUserData,\n AudioSessionPropertyID inID,\n UInt32 inDataSize,\n const void *inData)\n{\n UISlider * volumeSlider = (__bridge UISlider *) inUserData;\n Float32 newGain = *(Float32 *)inData;\n [volumeSlider setValue:newGain animated:YES];\n}\n\n// My UISlider Did Change Callback\n- (IBAction)volChanged:(id)sender\n{\n CGFloat oldVolume = [[MPMusicPlayerController applicationMusicPlayer] volume];\n CGFloat newVolume = ((UISlider*)sender).value;\n\n // Don't change the volume EVERYTIME but in discrete steps. \n // Performance will say \"THANK YOU\"\n if( fabsf(newVolume - oldVolume) > 0.05 || newVolume == 0 || newVolume == 1 )\n [[MPMusicPlayerController applicationMusicPlayer] setVolume:newVolume];\n}\n\n- (void)viewWillAppear:(BOOL)animated\n{\n [super viewWillAppear:animated];\n\n // Set the volume slider to the correct value on appearance of the view \n volSlider.value = [[MPMusicPlayerController applicationMusicPlayer] volume];\n}\n\n- (void)viewDidLoad\n{\n [super viewDidLoad];\n\n self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;\n\n // Activate the session and set teh delegate\n [[AVAudioSession sharedInstance] setActive:YES error:nil];\n [[AVAudioSession sharedInstance] setDelegate:self];\n\n // Create a customizable slider and add it to the view\n volSlider = [[UISlider alloc] init];\n CGRect sliderRect = volSlider.frame;\n sliderRect.origin.y = 50;\n sliderRect.size.width = self.view.bounds.size.width;\n volSlider.frame = sliderRect;\n [volSlider addTarget:self action:@selector(volChanged:) forControlEvents:UIControlEventValueChanged];\n [self.view addSubview:volSlider];\n\n // Regoister the callback to receive notifications from the hardware buttons\n AudioSessionAddPropertyListener (\n kAudioSessionProperty_CurrentHardwareOutputVolume ,\n audioVolumeChangeListenerCallback,\n (__bridge void*)volSlider\n );\n\n [...]\n}\n\n- (void)viewDidUnload\n{\n [super viewDidUnload];\n\n // Remove the Hardware-Button-Listener\n AudioSessionRemovePropertyListenerWithUserData(\n kAudioSessionProperty_CurrentHardwareOutputVolume, \n audioVolumeChangeListenerCallback, \n (__bridge void*)volSlider);\n}\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4468/"
] |
215,537
|
<p>So am I crazy for considering doing a beta/production release on Glassfish V3 Prelude?
Since all of my content is dynamic, I'm not even thinking of bothering to set up apache in front either. Doing so complicates the setup by requiring something like AJP or mod_jk and will not offer us much in terms of capability.</p>
<p>So there will be three war files on deployment.
3 JNDI data sources with about 90 connections parked, scaling up to 160 to a PGSQL datastore....</p>
<p>The three wars comprise a CMS system and a grails application?</p>
<p>Is my logic fatally flawed that I don't need to put apache in front of this setup?</p>
|
[
{
"answer_id": 215614,
"author": "catlan",
"author_id": 23028,
"author_profile": "https://Stackoverflow.com/users/23028",
"pm_score": 4,
"selected": true,
"text": "MPVolumeView *volumeView = [[MPVolumeView alloc] initWithFrame:CGRectMake(25, 378, 270, 30)];\n[self.view addSubview:volumeView];\n[volumeView release];\n"
},
{
"answer_id": 9507066,
"author": "blackjacx",
"author_id": 971329,
"author_profile": "https://Stackoverflow.com/users/971329",
"pm_score": 3,
"selected": false,
"text": "// AVAudiosession Delegate Method\n- (void)endInterruptionWithFlags:(NSUInteger)flags\n{\n // When interruption ends - set the apps audio session active again\n [[AVAudioSession sharedInstance] setActive:YES error:nil];\n\n if( flags == AVAudioSessionInterruptionFlags_ShouldResume ) {\n // Resume playback of song here!!!\n }\n}\n\n// Hardware Button Volume Callback\nvoid audioVolumeChangeListenerCallback (\n void *inUserData,\n AudioSessionPropertyID inID,\n UInt32 inDataSize,\n const void *inData)\n{\n UISlider * volumeSlider = (__bridge UISlider *) inUserData;\n Float32 newGain = *(Float32 *)inData;\n [volumeSlider setValue:newGain animated:YES];\n}\n\n// My UISlider Did Change Callback\n- (IBAction)volChanged:(id)sender\n{\n CGFloat oldVolume = [[MPMusicPlayerController applicationMusicPlayer] volume];\n CGFloat newVolume = ((UISlider*)sender).value;\n\n // Don't change the volume EVERYTIME but in discrete steps. \n // Performance will say \"THANK YOU\"\n if( fabsf(newVolume - oldVolume) > 0.05 || newVolume == 0 || newVolume == 1 )\n [[MPMusicPlayerController applicationMusicPlayer] setVolume:newVolume];\n}\n\n- (void)viewWillAppear:(BOOL)animated\n{\n [super viewWillAppear:animated];\n\n // Set the volume slider to the correct value on appearance of the view \n volSlider.value = [[MPMusicPlayerController applicationMusicPlayer] volume];\n}\n\n- (void)viewDidLoad\n{\n [super viewDidLoad];\n\n self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;\n\n // Activate the session and set teh delegate\n [[AVAudioSession sharedInstance] setActive:YES error:nil];\n [[AVAudioSession sharedInstance] setDelegate:self];\n\n // Create a customizable slider and add it to the view\n volSlider = [[UISlider alloc] init];\n CGRect sliderRect = volSlider.frame;\n sliderRect.origin.y = 50;\n sliderRect.size.width = self.view.bounds.size.width;\n volSlider.frame = sliderRect;\n [volSlider addTarget:self action:@selector(volChanged:) forControlEvents:UIControlEventValueChanged];\n [self.view addSubview:volSlider];\n\n // Regoister the callback to receive notifications from the hardware buttons\n AudioSessionAddPropertyListener (\n kAudioSessionProperty_CurrentHardwareOutputVolume ,\n audioVolumeChangeListenerCallback,\n (__bridge void*)volSlider\n );\n\n [...]\n}\n\n- (void)viewDidUnload\n{\n [super viewDidUnload];\n\n // Remove the Hardware-Button-Listener\n AudioSessionRemovePropertyListenerWithUserData(\n kAudioSessionProperty_CurrentHardwareOutputVolume, \n audioVolumeChangeListenerCallback, \n (__bridge void*)volSlider);\n}\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1129162/"
] |
215,548
|
<p>Background: Over the next month, I'll be giving three talks about or at least including <code>LINQ</code> in the context of <code>C#</code>. I'd like to know which topics are worth giving a fair amount of attention to, based on what people may find hard to understand, or what they may have a mistaken impression of. I won't be specifically talking about <code>LINQ</code> to <code>SQL</code> or the Entity Framework except as examples of how queries can be executed remotely using expression trees (and usually <code>IQueryable</code>).</p>
<p>So, what have you found hard about <code>LINQ</code>? What have you seen in terms of misunderstandings? Examples might be any of the following, but please don't limit yourself!</p>
<ul>
<li>How the <code>C#</code> compiler treats query expressions</li>
<li>Lambda expressions</li>
<li>Expression trees</li>
<li>Extension methods</li>
<li>Anonymous types</li>
<li><code>IQueryable</code></li>
<li>Deferred vs immediate execution</li>
<li>Streaming vs buffered execution (e.g. OrderBy is deferred but buffered)</li>
<li>Implicitly typed local variables</li>
<li>Reading complex generic signatures (e.g. <a href="http://msdn.microsoft.com/en-us/library/bb549267.aspx" rel="nofollow noreferrer">Enumerable.Join</a>)</li>
</ul>
|
[
{
"answer_id": 215572,
"author": "smaclell",
"author_id": 22914,
"author_profile": "https://Stackoverflow.com/users/22914",
"pm_score": 7,
"selected": false,
"text": "LINQ SQL SQL"
},
{
"answer_id": 215580,
"author": "Tim Jarvis",
"author_id": 10387,
"author_profile": "https://Stackoverflow.com/users/10387",
"pm_score": 6,
"selected": false,
"text": "Lambda lambda IEnumerable<T> IQueryable<T>"
},
{
"answer_id": 242932,
"author": "user31939",
"author_id": 31939,
"author_profile": "https://Stackoverflow.com/users/31939",
"pm_score": 3,
"selected": false,
"text": "iQueryable iSingleResult iMultipleResult"
},
{
"answer_id": 261931,
"author": "Pop Catalin",
"author_id": 4685,
"author_profile": "https://Stackoverflow.com/users/4685",
"pm_score": 1,
"selected": false,
"text": "from a in b\nfrom c in d\nwhere a > c\nselect new { a, c }\n"
},
{
"answer_id": 321349,
"author": "Richard Ev",
"author_id": 39709,
"author_profile": "https://Stackoverflow.com/users/39709",
"pm_score": 2,
"selected": false,
"text": "group by"
},
{
"answer_id": 351985,
"author": "Aaron Powell",
"author_id": 11388,
"author_profile": "https://Stackoverflow.com/users/11388",
"pm_score": 4,
"selected": false,
"text": "IEnumerable<T> IQueryable<T>"
},
{
"answer_id": 354031,
"author": "Brian Rasmussen",
"author_id": 38206,
"author_profile": "https://Stackoverflow.com/users/38206",
"pm_score": 1,
"selected": false,
"text": "Distinct Distinct"
},
{
"answer_id": 617900,
"author": "Simon_Weaver",
"author_id": 16940,
"author_profile": "https://Stackoverflow.com/users/16940",
"pm_score": 1,
"selected": false,
"text": "ThenBy() extension method\n"
},
{
"answer_id": 758067,
"author": "Chris",
"author_id": 36269,
"author_profile": "https://Stackoverflow.com/users/36269",
"pm_score": 5,
"selected": false,
"text": "LINQ LINQ to SQL LINQ LINQ"
},
{
"answer_id": 917259,
"author": "DSO",
"author_id": 38087,
"author_profile": "https://Stackoverflow.com/users/38087",
"pm_score": 7,
"selected": false,
"text": "static void Linq_Deferred_Execution_Demo()\n{\n List<String> items = new List<string> { \"Bob\", \"Alice\", \"Trent\" };\n\n var results = from s in items select s;\n\n Console.WriteLine(\"Before add:\");\n foreach (var result in results)\n {\n Console.WriteLine(result);\n }\n\n items.Add(\"Mallory\");\n\n //\n // Enumerating the results again will return the new item, even\n // though we did not re-assign the Linq expression to it!\n //\n\n Console.WriteLine(\"\\nAfter add:\");\n foreach (var result in results)\n {\n Console.WriteLine(result);\n }\n}\n Before add:\nBob\nAlice\nTrent\n\nAfter add:\nBob\nAlice\nTrent\nMallory\n"
},
{
"answer_id": 1016042,
"author": "RCIX",
"author_id": 117069,
"author_profile": "https://Stackoverflow.com/users/117069",
"pm_score": -1,
"selected": false,
"text": "var result = from foo in bars where (\n ((foo.baz != null) ? foo.baz : false) &&\n foo.blah == \"this\")\n select foo;\n"
},
{
"answer_id": 1425548,
"author": "Alex",
"author_id": 114916,
"author_profile": "https://Stackoverflow.com/users/114916",
"pm_score": 2,
"selected": false,
"text": "IQueryable IQueryable"
},
{
"answer_id": 1917835,
"author": "Simon_Weaver",
"author_id": 16940,
"author_profile": "https://Stackoverflow.com/users/16940",
"pm_score": 6,
"selected": false,
"text": "Single() SingleOrDefault() Single(x => x.id == id)\n Where(x => x.id == id).Single()\n"
},
{
"answer_id": 2383203,
"author": "Rob Packwood",
"author_id": 171485,
"author_profile": "https://Stackoverflow.com/users/171485",
"pm_score": 3,
"selected": false,
"text": "from outerloopitem in outerloopitems\nfrom innerloopitem in outerloopitem.childitems\nselect outerloopitem, innerloopitem\n"
},
{
"answer_id": 3816712,
"author": "Valera Kolupaev",
"author_id": 29300,
"author_profile": "https://Stackoverflow.com/users/29300",
"pm_score": 3,
"selected": false,
"text": "Expression<Func<T1, T2, T3, ...>> Func<T1, T2, T3, ...> [TestMethod]\npublic void QueryComplexityTest()\n{\n var users = _dataContext.Users;\n\n Func<User, bool> funcSelector = q => q.UserName.StartsWith(\"Test\");\n Expression<Func<User, bool>> expressionSelector = q => q.UserName.StartsWith(\"Test\");\n\n // Returns IEnumerable, and do filtering of data on client-side\n IQueryable<User> func = users.Where(funcSelector).AsQueryable();\n // Returns IQuerible and do filtering of data on server side\n // SELECT ... FROM [dbo].[User] AS [t0] WHERE [t0].[user_name] LIKE @p0\n IQueryable<User> exp = users.Where(expressionSelector);\n}\n"
},
{
"answer_id": 4434392,
"author": "Amir Karimi",
"author_id": 441889,
"author_profile": "https://Stackoverflow.com/users/441889",
"pm_score": 1,
"selected": false,
"text": "public class Temp\n{\n public Temp(int x, int y)\n {\n this.X = x;\n this.Y = y;\n }\n\n public int X { get; private set; }\n public int Y { get; private set; }\n}\n using (MyDataContext db = new MyDataContext())\n{\n var result = db.Table1.Select(row => \n new Temp(row.A, row.B + row.C)).ToList();\n}\n SELECT [t0].[A] AS [x], [t0].[B] + [t0].[C] AS [y]\nFROM [Table1] AS [t0]\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22656/"
] |
215,557
|
<p>How do I implement a circular list that overwrites the oldest entry when it's full? </p>
<p>For a little background, I want to use a circular list within GWT; so using a 3rd party lib is <strong>not</strong> what I want.</p>
|
[
{
"answer_id": 215575,
"author": "Adam Davis",
"author_id": 2915,
"author_profile": "https://Stackoverflow.com/users/2915",
"pm_score": 7,
"selected": true,
"text": "/* Very simple queue\n * These are FIFO queues which discard the new data when full.\n *\n * Queue is empty when in == out.\n * If in != out, then \n * - items are placed into in before incrementing in\n * - items are removed from out before incrementing out\n * Queue is full when in == (out-1 + QUEUE_SIZE) % QUEUE_SIZE;\n *\n * The queue will hold QUEUE_ELEMENTS number of items before the\n * calls to QueuePut fail.\n */\n\n/* Queue structure */\n#define QUEUE_ELEMENTS 100\n#define QUEUE_SIZE (QUEUE_ELEMENTS + 1)\nint Queue[QUEUE_SIZE];\nint QueueIn, QueueOut;\n\nvoid QueueInit(void)\n{\n QueueIn = QueueOut = 0;\n}\n\nint QueuePut(int new)\n{\n if(QueueIn == (( QueueOut - 1 + QUEUE_SIZE) % QUEUE_SIZE))\n {\n return -1; /* Queue Full*/\n }\n\n Queue[QueueIn] = new;\n\n QueueIn = (QueueIn + 1) % QUEUE_SIZE;\n\n return 0; // No errors\n}\n\nint QueueGet(int *old)\n{\n if(QueueIn == QueueOut)\n {\n return -1; /* Queue Empty - nothing to get*/\n }\n\n *old = Queue[QueueOut];\n\n QueueOut = (QueueOut + 1) % QUEUE_SIZE;\n\n return 0; // No errors\n}\n"
},
{
"answer_id": 19704777,
"author": "arapEST",
"author_id": 1268966,
"author_profile": "https://Stackoverflow.com/users/1268966",
"pm_score": 1,
"selected": false,
"text": "fifo_t* createFifoToHeap(size_t size)\n{\n byte_t* buffer = (byte_t*)malloc(size);\n\n if (buffer == NULL)\n return NULL;\n\n fifo_t* fifo = (fifo_t*)malloc(sizeof(fifo_t));\n\n if (fifo == NULL)\n {\n free(buffer);\n return NULL;\n }\n\n fifo->buffer = buffer;\n fifo->head = 0;\n fifo->tail = 0;\n fifo->size = size;\n\n return fifo;\n}\n\n#define CHECK_FIFO_NULL(fifo) MAC_FUNC(if (fifo == NULL) return 0;)\n\nsize_t fifoPushByte(fifo_t* fifo, byte_t byte)\n{\n CHECK_FIFO_NULL(fifo);\n\n if (fifoIsFull(fifo) == true)\n return 0;\n\n fifo->buffer[fifo->head] = byte;\n\n fifo->head++;\n if (fifo->head == fifo->size)\n fifo->head = 0;\n\n return 1;\n}\n\nsize_t fifoPushBytes(fifo_t* fifo, byte_t* bytes, size_t count)\n{\n CHECK_FIFO_NULL(fifo);\n\n for (uint32_t i = 0; i < count; i++)\n {\n if (fifoPushByte(fifo, bytes[i]) == 0)\n return i;\n }\n\n return count;\n}\n\nsize_t fifoPopByte(fifo_t* fifo, byte_t* byte)\n{\n CHECK_FIFO_NULL(fifo);\n\n if (fifoIsEmpty(fifo) == true)\n return 0;\n\n *byte = fifo->buffer[fifo->tail];\n\n fifo->tail++;\n if (fifo->tail == fifo->size)\n fifo->tail = 0;\n\n return 1;\n}\n\nsize_t fifoPopBytes(fifo_t* fifo, byte_t* bytes, size_t count)\n{\n CHECK_FIFO_NULL(fifo);\n\n for (uint32_t i = 0; i < count; i++)\n {\n if (fifoPopByte(fifo, bytes + i) == 0)\n return i;\n }\n\n return count;\n}\n\nbool fifoIsFull(fifo_t* fifo)\n{\n if ((fifo->head == (fifo->size - 1) && fifo->tail == 0) || (fifo->head == (fifo->tail - 1)))\n return true;\n else\n return false;\n}\n\nbool fifoIsEmpty(fifo_t* fifo)\n{\n if (fifo->head == fifo->tail)\n return true;\n else\n return false;\n}\n\nsize_t fifoBytesFilled(fifo_t* fifo)\n{\n if (fifo->head == fifo->tail)\n return 0;\n else if ((fifo->head == (fifo->size - 1) && fifo->tail == 0) || (fifo->head == (fifo->tail - 1)))\n return fifo->size;\n else if (fifo->head < fifo->tail)\n return (fifo->head) + (fifo->size - fifo->tail);\n else\n return fifo->head - fifo->tail; \n}\n"
},
{
"answer_id": 34624090,
"author": "Prateek Joshi",
"author_id": 4281711,
"author_profile": "https://Stackoverflow.com/users/4281711",
"pm_score": -1,
"selected": false,
"text": " public class CircularQueueDemo {\n public static void main(String[] args) throws Exception {\n\n CircularQueue queue = new CircularQueue(2);\n /* dynamically increasing/decreasing circular queue */\n System.out.println(\"--dynamic circular queue--\");\n queue.enQueue(1);\n queue.display();\n queue.enQueue(2);\n queue.display();\n queue.enQueue(3);\n queue.display();\n queue.enQueue(4);\n queue.display();\n queue.deQueue();\n queue.deQueue();\n queue.enQueue(5);\n queue.deQueue(); \n queue.display();\n\n }\n}\n\nclass CircularQueue {\n private int[] queue;\n public int front;\n public int rear;\n private int capacity;\n\n public CircularQueue(int cap) {\n front = -1;\n rear = -1;\n capacity = cap;\n queue = new int[capacity];\n }\n\n public boolean isEmpty() {\n return (rear == -1);\n }\n\n public boolean isFull() {\n if ((front == 0 && rear == capacity - 1) || (front == rear + 1))\n return true;\n else\n return false;\n }\n\n public void enQueue(int data) { \n if (isFull()) { //if queue is full then expand it dynamically \n reSize(); \n enQueue(data);\n } else { //else add the data to the queue\n if (rear == -1) //if queue is empty\n rear = front = 0;\n else if (rear == capacity) //else if rear reached the end of array then place rear to start (circular array)\n rear = 0;\n else\n rear++; //else just incement the rear \n queue[rear] = data; //add the data to rear position\n }\n }\n\n public void reSize() {\n int new_capacity = 2 * capacity; //create new array of double the prev size\n int[] new_array = new int[new_capacity]; \n\n int prev_size = getSize(); //get prev no of elements present\n int i = 0; //place index to starting of new array\n\n while (prev_size >= 0) { //while elements are present in prev queue\n if (i == 0) { //if i==0 place the first element to the array\n new_array[i] = queue[front++];\n } else if (front == capacity) { //else if front reached the end of array then place rear to start (circular array) \n front = 0;\n new_array[i] = queue[front++];\n } else //else just increment the array\n new_array[i] = queue[front++];\n prev_size--; //keep decreasing no of element as you add the elements to the new array\n i++; //increase the index of new array\n }\n front = 0; //assign front to 0\n rear = i-1; //assign rear to the last index of added element\n capacity=new_capacity; //assign the new capacity\n queue=new_array; //now queue will point to new array (bigger circular array)\n }\n\n public int getSize() {\n return (capacity - front + rear) % capacity; //formula to get no of elements present in circular queue\n }\n\n public int deQueue() throws Exception {\n if (isEmpty()) //if queue is empty\n throw new Exception(\"Queue is empty\");\n else {\n int item = queue[front]; //get item from front\n if (front == rear) //if only one element\n front = rear = -1;\n else if (front == capacity) //front reached the end of array then place rear to start (circular array)\n front = 0;\n else\n front++; //increment front by one\n decreaseSize(); //check if size of the queue can be reduced to half\n return item; //return item from front\n }\n\n }\n\n public void decreaseSize(){ //function to decrement size of circular array dynamically\n int prev_size = getSize();\n if(prev_size<capacity/2){ //if size is less than half of the capacity\n int[] new_array=new int[capacity/2]; //create new array of half of its size\n int index=front; //get front index\n int i=0; //place an index to starting of new array (half the size)\n while(prev_size>=0){ //while no of elements are present in the queue\n if(i==0) //if index==0 place the first element\n new_array[i]=queue[front++];\n else if(front==capacity){ //front reached the end of array then place rear to start (circular array) \n front=0;\n new_array[i]=queue[front++];\n }\n else\n new_array[i]=queue[front++]; //else just add the element present in index of front\n prev_size--; //decrease the no of elements after putting to new array \n i++; //increase the index of i\n }\n front=0; //assign front to 0\n rear=i-1; //assign rear to index of last element present in new array(queue)\n capacity=capacity/2; //assign new capacity (half the size of prev)\n queue=new_array; //now queue will point to new array (or new queue)\n }\n }\n\n public void display() { //function to display queue\n int size = getSize();\n int index = front;\n\n while (size >= 0) {\n if (isEmpty())\n System.out.println(\"Empty queue\");\n else if (index == capacity)\n index = 0;\n System.out.print(queue[index++] + \"=>\");\n size--;\n }\n System.out.println(\" Capacity: \"+capacity);\n\n }\n\n}\n"
},
{
"answer_id": 63006567,
"author": "EvLa",
"author_id": 13966848,
"author_profile": "https://Stackoverflow.com/users/13966848",
"pm_score": 0,
"selected": false,
"text": "#include <iostream>\n#include <string>\n\nusing namespace std;\n\nclass E: public std::exception {\n\n const char *_msg;\n E(){}; //no default constructor\n\npublic:\n\n explicit E(const char *msg) throw(): _msg(msg) {};\n const char * what() const throw() {return(_msg);};\n\n};\n\nconst int min_size = 2;\nconst int max_size = 1000;\n\ntemplate<typename T>\nclass Fifo{\n\n int _head;\n int _tail;\n int _size;\n\n T* _storage;\n\npublic:\n\n explicit Fifo(int size = min_size);\n ~Fifo(){ delete [] _storage;};\n\n bool is_full() const{\n return(((_head+1)%_size) == _tail);\n };\n bool is_empty() const{\n return(_head == _tail);\n };\n\n void add_item(const T& item);\n const T& get_item();\n\n};\n\ntemplate<typename T>\nFifo<T>::Fifo(int size): _size(size){\n \n if (size < min_size) throw E(\"Cannot create Fifo less than 2\\n\");\n\n _head = _tail = 0;\n\n try{\n\n _storage = new T[_size];\n }\n catch (std::bad_alloc &ba)\n {\n char e_string[500];\n sprintf(e_string, \"Cannot allocate memory (%s)\\n\", ba.what());\n throw E(e_string);\n }\n\n printf(\"Constructing Fifo of size %d\\n\", _size);\n\n}\n\ntemplate <typename T>\nvoid Fifo<T>::add_item(const T& item)\n{\n if (this->is_full()) throw E(\"Fifo is full.\\n\");\n\n _storage[_head] = item;\n\n _head = (_head + 1)%_size;\n}\n\ntemplate <typename T>\nconst T& Fifo<T>::get_item()\n{\n if (this->is_empty()) throw E(\"Fifo is empty.\\n\");\n\n int temp = _tail; //save the current tail\n\n _tail = (_tail+1)%_size; //update tail\n\n return(_storage[temp]);\n}\n\nint main()\n{\n Fifo<int> my_fifo(3);\n\n for (int i = 1, item; i < 50; i++)\n {\n my_fifo.add_item(i);\n my_fifo.add_item(i*10);\n item = my_fifo.get_item();\n printf(\"Item: %d\\n\", item);\n item = my_fifo.get_item();\n printf(\"Item: %d\\n\", item);\n }\n\n\n return 0;\n}\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22992/"
] |
215,581
|
<p>What is the purpose of the colon before a block in Python?</p>
<p>Example:</p>
<pre><code>if n == 0:
print "The end"
</code></pre>
|
[
{
"answer_id": 215676,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 7,
"selected": true,
"text": "if a == b \n print a\n if a == b: \n print a\n"
},
{
"answer_id": 1464645,
"author": "Yoo",
"author_id": 37664,
"author_profile": "https://Stackoverflow.com/users/37664",
"pm_score": 5,
"selected": false,
"text": "pewkah\nlalala\n chunkykachoo\n pewpewpew\nskunkybacon\n pewkah\nlalala: (<-- see this colon)\n chunkykachoo\n pewpewpew\nskunkybacon\n"
},
{
"answer_id": 3075389,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 3,
"selected": false,
"text": "if expression: action()\ncode_continues()\n if expression: action()\n\ncode_continues()\n if"
},
{
"answer_id": 52451080,
"author": "Serge",
"author_id": 5874981,
"author_profile": "https://Stackoverflow.com/users/5874981",
"pm_score": 2,
"selected": false,
"text": "x = (23 + \n 24 + \n 33)\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14732/"
] |
215,584
|
<p>I am currently a student and trying to design a Visual C++ application to allow me to visually insert an oriented graph in order to create a text file with the graph's matrix. At this point I have created an onClick event to create nodes and have used the form's Paint event to draw the nodes. I have also inserted the conditions to avoid nodes from overlapping.</p>
<p>I am currently working on creating the links between nodes. The problem that I have encountered is that the line that unites two nodes crosses another node. I consider that writing an algorithm to detect overlapping and calculate how much the line needs to arch in order to avoid that is too tedious in this situation.</p>
<p>Therefore I thought about creating a line that can be arched by the user by clicking and dragging it to the left or right, however I have had problems finding any tutorials on how to do this. So if anyone has ever had to introduce this kind of arching line in a project or has any idea where I could find some information about this I would deeply appreciate it.</p>
<p>Mentions:</p>
<ol>
<li>please do not recommend any fancy graphics libraries for doing this, as I am not interested in installing 3rd party stuff for this program. The function I want to insert the code into is named something like form1_onPaint, so I would like to keep it strictly to the C++ standard libraries.</li>
<li>I know I said I am interested in arching a line through click and drag, however if someone could suggest another viable solution to this, such as a function that detects overlapping in onPaint events or anything else that could be of use to solve this it would be of great help.</li>
</ol>
|
[
{
"answer_id": 215676,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 7,
"selected": true,
"text": "if a == b \n print a\n if a == b: \n print a\n"
},
{
"answer_id": 1464645,
"author": "Yoo",
"author_id": 37664,
"author_profile": "https://Stackoverflow.com/users/37664",
"pm_score": 5,
"selected": false,
"text": "pewkah\nlalala\n chunkykachoo\n pewpewpew\nskunkybacon\n pewkah\nlalala: (<-- see this colon)\n chunkykachoo\n pewpewpew\nskunkybacon\n"
},
{
"answer_id": 3075389,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 3,
"selected": false,
"text": "if expression: action()\ncode_continues()\n if expression: action()\n\ncode_continues()\n if"
},
{
"answer_id": 52451080,
"author": "Serge",
"author_id": 5874981,
"author_profile": "https://Stackoverflow.com/users/5874981",
"pm_score": 2,
"selected": false,
"text": "x = (23 + \n 24 + \n 33)\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29293/"
] |
215,615
|
<p>Erlang support to partition its nodes into groups using the <a href="http://erlang.org/doc/man/global_group.html" rel="nofollow noreferrer">global_group</a> module.
Further, Erlang supports adding nodes on the fly to the node-network. Are these two features usable with each other?<br>
As far as I understand, you have to name every node on startup to use the global groups.</p>
|
[
{
"answer_id": 2736872,
"author": "TBBle",
"author_id": 166389,
"author_profile": "https://Stackoverflow.com/users/166389",
"pm_score": 2,
"selected": true,
"text": "application:set_env( kernel, global_groups, [GroupTuple|GroupTuples] ),\nkernel:config_change( [ { global_groups, [GroupTuple|GroupTuples] } ], [], [] )\n application:set_env( kernel, global_groups, [GroupTuple|GroupTuples] ),\nkernel:config_change( [], [{ global_groups, [GroupTuple|GroupTuples] }], [] )\n global_group:sync()\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23760/"
] |
215,620
|
<p>How do I load MS Word document (.doc and .docx) to memory (variable) without doing this?:</p>
<p><em>wordApp.Documents.Open</em> </p>
<p>I don't want to open MS Word, I just want that text inside. </p>
<p>You gave me answer for DOCX, but what about DOC? I want free and high performance solution - not to open 12.000 instances of Word to process all of them. :( Aspose is commercial product, and 900$ is a way too much for what I do.</p>
|
[
{
"answer_id": 25975734,
"author": "edi9999",
"author_id": 1993501,
"author_profile": "https://Stackoverflow.com/users/1993501",
"pm_score": 0,
"selected": false,
"text": "DocxTemplater=require('docxtemplater');\ndoc=new DocxTemplater().loadFromFile(\"input.docx\");\nresult=doc.getFullText();\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21209/"
] |
215,624
|
<p>I am trying to use some pinvoke code to call a C function. The function fills a buffer with data.</p>
<p>The structure is set up as a DWORD for the length, followed by a string. How do I extract the string from the IntPtr?</p>
<pre><code> IntPtr buffer = Marshal.AllocHGlobal(nRequiredSize);
PInvokedFunction(buffer, nRequiredSize);
string s = Marshal.PtrToStringAuto(buffer + 4); //this is an error.
Marshal.FreeHGlobal(buffer);
</code></pre>
|
[
{
"answer_id": 215627,
"author": "Adam Tegen",
"author_id": 4066,
"author_profile": "https://Stackoverflow.com/users/4066",
"pm_score": 0,
"selected": false,
"text": " IntPtr buffer = Marshal.AllocHGlobal((int)nRequiredSize);\n PInvokedFunction(buffer, nRequiredSize);\n UnmanagedMemoryStream memStream = new UnmanagedMemoryStream(buffer.ToPointer(), nRequiredSize);\n memStream.Seek(4, SeekOrigin.Begin);\n IntPtr ptr = new IntPtr(memStream.PositionPointer);\n string s = Marshal.PtrToStringAuto(ptr);\n Marshal.FreeHGlobal(buffer);\n"
},
{
"answer_id": 215660,
"author": "Matt Ellis",
"author_id": 29306,
"author_profile": "https://Stackoverflow.com/users/29306",
"pm_score": 3,
"selected": true,
"text": "IntPtr sBuffer = new IntPtr( buffer.ToInt64() + 4 );\nstring s = Marshal.PtrToStringAuto( sBuffer );\n"
},
{
"answer_id": 215698,
"author": "Adam Tegen",
"author_id": 4066,
"author_profile": "https://Stackoverflow.com/users/4066",
"pm_score": 0,
"selected": false,
"text": " //allocate the buffer in .Net\n byte[] buffer = new byte[nRequiredSize];\n\n //call the WIN32 function, passing it the allocated buffer\n PInvokedFunction(buffer);\n\n //get the string from the 5th byte\n string s = Marshal.PtrToStringAuto(Marshal.UnsafeAddrOfPinnedArrayElement(buffer, 4));\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4066/"
] |
215,636
|
<p>I'm having some trouble with Visual Studio 2008 on my Windows XP SP2 laptop.</p>
<p>What happens is that when I start a program with a few textboxes and stuff like that, the boxes are see-through. I can litteraly see through them and see what's on the underlaying screen. Like if I only have this Form showing and behind that my wallpaper, I can see my wallpaper through the Textbox, ComboBox, even through the small cracks between various elements.</p>
<p>i've searched the web but haven't encountered info on this yet. Does anybody know what might be causing this and how to solve it? I'm in the process of trying to see how the text in my TextBoxes is parsed, but I can't since I can't even enter anything. I click on the textbox and I'm focused on the desktop...</p>
|
[
{
"answer_id": 215646,
"author": "Cameron",
"author_id": 21475,
"author_profile": "https://Stackoverflow.com/users/21475",
"pm_score": 3,
"selected": true,
"text": "Reset"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11795/"
] |
215,638
|
<p>I'm trying to access the message in a jthrowable while handing an exception generated when I fail to find a class. However, I am unable to access the message ID of getMessage() on the jthrowable object, and I don't know why. I've tried changing the signature of getMessage to "()Ljava/lang/String" (without the semicolon at the end, but that's necessary, right?) with no joy. I'm confused as hell about this. I even tried replacing getMessage with toString, and <em>that</em> didn't work. Obviously I'm doing something trivially wrong here.</p>
<p>Here's the code I'm using:</p>
<pre><code>jthrowable java_exception;
jclass java_class;
jmethodID method;
java_exception = (*jEnv)->ExceptionOccurred(jEnv);
assert (java_exception != NULL);
java_class = (*jEnv)->GetObjectClass (jEnv, java_exception);
assert (java_class != NULL);
method = (*jEnv)->GetMethodID (jEnv, java_class, "getMessage", "()Ljava/lang/String;");
if (method == NULL) {
printf ("Seriously, how do I get here?!\n");
(*jEnv)->ExceptionDescribe (jEnv);
return;
}
</code></pre>
<p>The output of this code (amongst other things) looks like this:</p>
<blockquote>
<p>Seriously, how do I get here?!<br>
Exception in thread "main" java.lang.NoClassDefFoundError: com/planet/core360/docgen/Processor</p>
</blockquote>
<p><code>javap -p -s java.lang.Throwable</code> gives me this:</p>
<blockquote>
<p>Compiled from "Throwable.java"<br>
public class java.lang.Throwable extends java.lang.Object implements java.io.Serializable{<br>
...<br>
public java.lang.String getMessage();<br>
Signature: ()Ljava/lang/String;<br>
... </p>
</blockquote>
|
[
{
"answer_id": 215662,
"author": "Chris R",
"author_id": 23309,
"author_profile": "https://Stackoverflow.com/users/23309",
"pm_score": 4,
"selected": true,
"text": "GetObjectClass java_class = (*jEnv)->FindClass (jEnv, \"java/lang/Throwable\");\nmethod = (*jEnv)->GetMethodID (jEnv, java_class, \"getMessage\", \"()Ljava/lang/String;\");\n"
},
{
"answer_id": 215681,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 2,
"selected": false,
"text": "#include <cstdio>\n#include <jni.h>\n\nint\nmain(int argc, char** argv)\n{\n if (argc != 3) {\n std::fprintf(stderr, \"usage: %s class message\\n\", argv[0]);\n return 1;\n }\n\n JavaVM* jvm;\n void* penv;\n JavaVMInitArgs args = {JNI_VERSION_1_6};\n\n if (jint res = JNI_CreateJavaVM(&jvm, &penv, &args)) {\n std::fprintf(stderr, \"Can's create JVM: %d\\n\", res);\n return -res;\n }\n\n JNIEnv* env(static_cast<JNIEnv*>(penv));\n jint vers(env->GetVersion());\n std::printf(\"JNI version %d.%d\\n\", vers >> 16, vers & 0xffff);\n\n env->ThrowNew(env->FindClass(argv[1]), argv[2]);\n jthrowable exc(env->ExceptionOccurred());\n std::printf(\"Exception: %p\\n\", exc);\n if (exc) {\n jclass exccls(env->GetObjectClass(exc));\n jclass clscls(env->FindClass(\"java/lang/Class\"));\n\n jmethodID getName(env->GetMethodID(clscls, \"getName\", \"()Ljava/lang/String;\"));\n jstring name(static_cast<jstring>(env->CallObjectMethod(exccls, getName)));\n char const* utfName(env->GetStringUTFChars(name, 0));\n\n jmethodID getMessage(env->GetMethodID(exccls, \"getMessage\", \"()Ljava/lang/String;\"));\n jstring message(static_cast<jstring>(env->CallObjectMethod(exc, getMessage)));\n char const* utfMessage(env->GetStringUTFChars(message, 0));\n\n std::printf(\"Exception: %s: %s\\n\", utfName, utfMessage);\n env->ReleaseStringUTFChars(message, utfMessage);\n env->ReleaseStringUTFChars(name, utfName);\n }\n return -jvm->DestroyJavaVM();\n}\n jnitest java/lang/InternalError 'Hello, world!'"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23309/"
] |
215,667
|
<p>I am trying to develop a script to pull some data from a large number of html tables. One problem is that the number of rows that contain the information to create the column headings is indeterminate. I have discovered that the last row of the set of header rows has the attribute border-bottom for each cell with a value. Thus I decided to find those cells with the attribute border-bottom. As you can see I initialized a list. I intended to find the parent of each of the cells that end up in the borderCells list. However, when I run this code only one cell, that is the first cell in allCells with the attribute border-bottom is added to the list borderCells. For your information allCells has 193 cells, 9 of them have the attr border-bottom. Thus I was expecting nine members in the borderCells list. Any help is appreciated.</p>
<pre><code>borderCells=[]
for each in allCells:
if each.find(attrs={"style": re.compile("border-bottom")}):
borderCells.append(each)
</code></pre>
|
[
{
"answer_id": 215720,
"author": "pantsgolem",
"author_id": 9261,
"author_profile": "https://Stackoverflow.com/users/9261",
"pm_score": 2,
"selected": false,
"text": "borderCells = soup.findAll(\"td\", style=re.compile(\"border-bottom\")})"
},
{
"answer_id": 215727,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<TD nowrap align=\"left\" valign=\"bottom\">\n<DIV style=\"border-bottom: 1px solid #000000; width: 1%; padding-bottom: 1px\">\n<B>Name</B>\n</DIV>\n</TD>\n <TD colspan=\"2\" nowrap align=\"center\" valign=\"bottom\" style=\"border-bottom: 1px solid 00000\">\n<B>Location</B>\n</TD>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
215,672
|
<p>Does anyone have experience with a query language for the web?</p>
<p>I am looking for project, commercial or not, that does a good job at making a webpage queryable and that even follows links on it to aggregate information from a bunch of pages.</p>
<p>I would prefere a sql or linq like syntax. I could of course download a webpage and start doing some XPATH on it but Im looking for a solution that has a nice abstraction.</p>
<p>I found websql </p>
<p><a href="http://www.cs.utoronto.ca/~websql/" rel="nofollow noreferrer">http://www.cs.utoronto.ca/~websql/</a></p>
<p>Which looks good but I'm not into Java</p>
<pre><code>SELECT a.label
FROM Anchor a SUCH THAT base = "http://www.SomeDoc.html"
WHERE a.href CONTAINS ".ps.Z";
</code></pre>
<p>Are there others out there? </p>
<p>Is there a library that can be used in a .NET language?</p>
|
[
{
"answer_id": 215788,
"author": "Pistos",
"author_id": 28558,
"author_profile": "https://Stackoverflow.com/users/28558",
"pm_score": 2,
"selected": false,
"text": "# load the RedHanded home page\ndoc = Hpricot(open(\"http://redhanded.hobix.com/index.html\"))\n# change the CSS class on links\n(doc/\"span.entryPermalink\").set(\"class\", \"newLinks\")\n# remove the sidebar\n(doc/\"#sidebar\").remove\n# print the altered HTML\nputs doc\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25145/"
] |
215,684
|
<p>I have a std::multimap where key is a custom class. Something like this:</p>
<pre><code>Class X {
public:
std::string s;
int x;
operator <(const X& other) const { return s < other.s; }
};
std::multimap<X, int> mymap;
</code></pre>
<p>Now, I'd like to use upper_bound and lower_bound to iterate over all elements with the same value of "s". Do I need to implement some other operator for X (for example: ==). Or it will work properly just like this?</p>
<p>Also, what should I supply as argument for <em>upper_bound</em> and <em>lower_bound</em>? I assume I should create a dummy object with desired value of "s"?</p>
|
[
{
"answer_id": 215692,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 4,
"selected": true,
"text": "class X upper_bound() lower_bound() class X std::string X::s upper_bound() lower_bound() less<> operator <() class X"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14690/"
] |
215,685
|
<p>I often find myself trying to come up with good names for complementary pairs of variables; where two variables denote opposing concepts, two participants in some sort of duologue, and so on.</p>
<p>This might be better explained by a counter-example - I maintain an app that prints two graphics as part of a print advertisement. They're stored in the database as <code>TopLogo</code> and <code>LowerLogo</code>, which I have to stop and double-check every time I use them because I'm expecting <code>top</code> to complement <code>bottom</code>, and <code>lower</code> should complement <code>upper</code>. </p>
<p>There's some obvious examples that I think work well:</p>
<p><code>client / server</code><br>
<code>source / target</code> for copying/moving data or files from one variable to another<br>
<code>minimum / maximum</code> </p>
<p>but there's some concepts that just don't lend themselves to such neat naming schemes. For example, when paging through records, does 'last' mean 'final' or 'previous' ? I recently saw some code that used <code>firstPage</code>, <code>previousPage</code>, <code>nextPage</code> and <code>finalPage</code> to avoid the ambiuous <code>lastPage</code> completely, which I thought was very beat, hence this question.</p>
<p>Do you have any particularly neat variable name pairs you'd care to share with us? (Bonus points if they're the same length, which makes the code so much neater in monospaced fonts.)</p>
|
[
{
"answer_id": 215724,
"author": "Dan Rosenstark",
"author_id": 8047,
"author_profile": "https://Stackoverflow.com/users/8047",
"pm_score": 1,
"selected": false,
"text": "Connection setDestination destination Server target aimHere placeToSendTheData whatever source comingFromHere placeToGetTheDataFrom placeWeWantTheDataToGo Conexion Connection"
},
{
"answer_id": 218553,
"author": "onedaywhen",
"author_id": 15354,
"author_profile": "https://Stackoverflow.com/users/15354",
"pm_score": 1,
"selected": false,
"text": "start_date end_date employee_start_date employee_hire_date person_birth_date person_start_date"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5017/"
] |
215,689
|
<p>I still haven't got my head around decorators in Python.</p>
<p>I've already started using a lot of closures to do things like customize functions and classes in my coding.</p>
<p>Eg.</p>
<pre><code>class Node :
def __init__(self,val,children) :
self.val = val
self.children = children
def makeRunner(f) :
def run(node) :
f(node)
for x in node.children :
run(x)
return run
tree=Node(1,[Node(2,[]),Node(3,[Node(4,[]),Node(5,[])])])
def pp(n) : print "%s," % n.val
printTree = makeRunner(pp)
printTree(tree)
</code></pre>
<p>As far as I can see, decorators are just a different syntax for doing something similar. </p>
<p>Instead of </p>
<pre><code>def pp(n) : print "%s," % n.val
printTree = makeRunner(pp)
</code></pre>
<p>I would write :</p>
<pre><code>@makeRunner
def printTree(n) : print "%s," % n.val
</code></pre>
<p>Is this all there is to decorators? Or is there a fundamental difference that I've missed? </p>
|
[
{
"answer_id": 215782,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 3,
"selected": false,
"text": "def run(rootnode, func):\n def _run(node): # recursive internal function\n func(node)\n for x in node.children:\n _run(x) # recurse\n _run(rootnode) # initial run\n def pp(n): print \"%s,\" % n.val\nrun(tree, pp)\n class Node :\n def __init__(self,val,children) :\n self.val = val\n self.children = children\n\n def __iter__(self): # recursive\n yield self\n for child in self.children:\n for item in child: # recurse\n yield item\n\ndef run(rootnode, func):\n for node in rootnode:\n func(node)\n def pp(n): print \"%s,\" % n.val\nrun(tree, pp)\n __iter__ for node in rootnode: __iter__ walker run for node in rootnode.walker(): run class Node run(tree, func) printTree functools.partial printTree= functools.partial(run, func=pp)\n printTree(tree)\n"
},
{
"answer_id": 26626194,
"author": "kako-nawao",
"author_id": 844972,
"author_profile": "https://Stackoverflow.com/users/844972",
"pm_score": 2,
"selected": false,
"text": "class tracked_with(object):\n \"\"\"\n Method decorator used to track the results of celery tasks.\n \"\"\"\n def __init__(self, model, unique=False, id_attr='results_id',\n log_error=False, raise_error=False):\n self.model = model\n self.unique = unique\n self.id_attr = id_attr\n self.log_error = log_error\n self.raise_error = raise_error\n\n def __call__(self, fn):\n\n def wrapped(*args, **kwargs):\n # Unique passed by parameter has priority above the decorator def\n unique = kwargs.get('unique', None)\n if unique is not None:\n self.unique = unique\n\n if self.unique:\n caller = args[0]\n pending = self.model.objects.filter(\n state=self.model.Running,\n task_type=caller.__class__.__name__\n )\n if pending.exists():\n raise AssertionError('Another {} task is already running'\n ''.format(caller.__class__.__name__))\n\n results_id = kwargs.get(self.id_attr)\n try:\n result = fn(*args, **kwargs)\n\n except Retry:\n # Retry must always be raised to retry a task\n raise\n\n except Exception as e:\n # Error, update stats, log/raise/return depending on values\n if results_id:\n self.model.update_stats(results_id, error=e)\n if self.log_error:\n logger.error(e)\n if self.raise_error:\n raise\n else:\n return e\n\n else:\n # No error, save results in refresh object and return\n if results_id:\n self.model.update_stats(results_id, **result)\n return result\n\n return wrapped\n run class SomeTask(Task):\n\n @tracked_with(RefreshResults, unique=True, log_error=False)\n def run(self, *args, **kwargs)...\n"
},
{
"answer_id": 45866054,
"author": "Chen A.",
"author_id": 840582,
"author_profile": "https://Stackoverflow.com/users/840582",
"pm_score": 3,
"selected": false,
"text": "def increment(x):\n return x + 1\n\ndef double_increment(func):\n def wrapper(x):\n print 'decorator executed'\n r = func(x) # --> func is saved in __closure__\n y = r * 2\n return r, y\n return wrapper\n\n@double_increment\ndef increment(x):\n return x + 1\n\n>>> increment(2)\ndecorator executed\n(3, 6)\n\n>>> increment.__closure__\n(<cell at 0x02C7DC50: function object at 0x02C85DB0>,)\n\n>>> increment.__closure__[0].cell_contents \n<function increment at 0x02C85DB0>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8482/"
] |
215,718
|
<p>How do I revert a modified file to its previous revision at a specific commit hash (which I determined via <a href="https://git-scm.com/docs/git-log" rel="noreferrer"><code>git log</code></a> and <a href="https://git-scm.com/docs/git-diff" rel="noreferrer"><code>git diff</code></a>)?</p>
|
[
{
"answer_id": 35288,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 8,
"selected": false,
"text": "git checkout -- foo\n foo git checkout HEAD^ foo\n"
},
{
"answer_id": 35335,
"author": "Aaron Maenpaa",
"author_id": 2603,
"author_profile": "https://Stackoverflow.com/users/2603",
"pm_score": 5,
"selected": false,
"text": "git checkout foo foo git checkout HEAD foo git checkout ./foo $ pwd\n/Users/aaron/Documents/work/foo\n$ git checkout foo\nD foo\nAlready on \"foo\"\n$ git checkout ./foo\n$ git checkout HEAD foo\n"
},
{
"answer_id": 36801,
"author": "Damien Diederen",
"author_id": 3844,
"author_profile": "https://Stackoverflow.com/users/3844",
"pm_score": 4,
"selected": false,
"text": "git checkout ./foo git checkout HEAD ./foo $ echo A > foo\n$ git add foo\n$ git commit -m 'A' foo\nCreated commit a1f085f: A\n1 files changed, 1 insertions(+), 0 deletions(-)\ncreate mode 100644 foo\n$ echo B >> foo\n$ git add foo\n$ echo C >> foo\n$ cat foo\nA\nB\nC\n$ git checkout ./foo\n$ cat foo\nA\nB\n$ git checkout HEAD ./foo\n$ cat foo\nA\n add Git checkout ./foo ./foo HEAD HEAD"
},
{
"answer_id": 215731,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 14,
"selected": true,
"text": "c5f567 git checkout c5f567 -- file1/to/restore file2/to/restore\n c5f567 ~1 git checkout c5f567~1 -- file1/to/restore file2/to/restore\n git restore"
},
{
"answer_id": 215768,
"author": "Aristotle Pagaltzis",
"author_id": 9410,
"author_profile": "https://Stackoverflow.com/users/9410",
"pm_score": 5,
"selected": false,
"text": "git revert eg revert foo/bar foo/baz"
},
{
"answer_id": 373834,
"author": "jdee",
"author_id": 39655,
"author_profile": "https://Stackoverflow.com/users/39655",
"pm_score": 6,
"selected": false,
"text": "$ git log $ git reset --hard SHA1_HASH"
},
{
"answer_id": 373848,
"author": "Chris Lloyd",
"author_id": 42413,
"author_profile": "https://Stackoverflow.com/users/42413",
"pm_score": 10,
"selected": false,
"text": "git diff <commit hash> <filename>\n git reset <commit hash> <filename>\n --hard git checkout <commit hash>\ngit checkout -b <new branch name>\n git checkout <my branch>\ngit rebase master\ngit checkout master\ngit merge <my branch>\n"
},
{
"answer_id": 375626,
"author": "Otto",
"author_id": 9594,
"author_profile": "https://Stackoverflow.com/users/9594",
"pm_score": 3,
"selected": false,
"text": "git revert <hash>\n git revert"
},
{
"answer_id": 432564,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "$ git checkout $A file\n $ git revert $B\n"
},
{
"answer_id": 581113,
"author": "cmcginty",
"author_id": 64313,
"author_profile": "https://Stackoverflow.com/users/64313",
"pm_score": 5,
"selected": false,
"text": "rebase git checkout <my branch>\ngit rebase master\ngit checkout master\ngit merge <my branch>\n ---o----o----o----o master\n \\---A----B <my branch>\n master rebase <my branch> master master <my branch> master master git rebase master <my branch>\n ---o----o----o----o master\n \\----A'----B' <my branch>\n git checkout master\ngit merge <my branch>\n <my branch> master master ---o----o----o----o----A'----B' master, <my branch>\n master <my branch> B' <my branch> git branch -d <my branch>\n"
},
{
"answer_id": 725893,
"author": "Ron DeVera",
"author_id": 63428,
"author_profile": "https://Stackoverflow.com/users/63428",
"pm_score": 7,
"selected": false,
"text": "git checkout master~5 image.png\n master"
},
{
"answer_id": 727725,
"author": "foxxtrot",
"author_id": 10369,
"author_profile": "https://Stackoverflow.com/users/10369",
"pm_score": 9,
"selected": false,
"text": "git checkout [commit-ref] -- [filename]"
},
{
"answer_id": 917126,
"author": "bbrown",
"author_id": 20595,
"author_profile": "https://Stackoverflow.com/users/20595",
"pm_score": 7,
"selected": false,
"text": "commit-ref git checkout [commit-ref] [filename]\n"
},
{
"answer_id": 7197855,
"author": "v2k",
"author_id": 146550,
"author_profile": "https://Stackoverflow.com/users/146550",
"pm_score": 6,
"selected": false,
"text": "git checkout <commit hash> file\n git commit -a\n"
},
{
"answer_id": 8391189,
"author": "mustafakyr",
"author_id": 1082254,
"author_profile": "https://Stackoverflow.com/users/1082254",
"pm_score": 3,
"selected": false,
"text": "git log git checkout <hashkey>"
},
{
"answer_id": 8529292,
"author": "Ian Davis",
"author_id": 1101152,
"author_profile": "https://Stackoverflow.com/users/1101152",
"pm_score": 3,
"selected": false,
"text": "cd <working copy>\ngit revert master\n"
},
{
"answer_id": 8860548,
"author": "CDR",
"author_id": 50542,
"author_profile": "https://Stackoverflow.com/users/50542",
"pm_score": 7,
"selected": false,
"text": "git checkout HEAD file/to/restore\n"
},
{
"answer_id": 19034316,
"author": "Amos Folarin",
"author_id": 771372,
"author_profile": "https://Stackoverflow.com/users/771372",
"pm_score": 4,
"selected": false,
"text": "git checkout HEAD~5 -- foo.bar\nor \ngit checkout 048ee28 -- foo.bar\n"
},
{
"answer_id": 21056953,
"author": "ModernIncantations",
"author_id": 1998744,
"author_profile": "https://Stackoverflow.com/users/1998744",
"pm_score": 5,
"selected": false,
"text": "git checkout HEAD^1 path/to/file\n git checkout HEAD~1 path/to/file\n"
},
{
"answer_id": 22016441,
"author": "shah1988",
"author_id": 2189927,
"author_profile": "https://Stackoverflow.com/users/2189927",
"pm_score": 4,
"selected": false,
"text": "git checkout eb917a1 YourFileName\n git reset HEAD YourFileName\ngit checkout YourFileName\n"
},
{
"answer_id": 29980518,
"author": "TheCodeArtist",
"author_id": 319204,
"author_profile": "https://Stackoverflow.com/users/319204",
"pm_score": 5,
"selected": false,
"text": "git prevision <N> <filename>\n <N> <filename> x/y/z.c git prevision -1 x/y/z.c\n gitconfig [alias]\n prevision = \"!f() { git checkout `git log --oneline $2 | awk -v commit=\"$1\" 'FNR == -commit+1 {print $1}'` $2;} ;f\"\n git log git checkout"
},
{
"answer_id": 34666232,
"author": "Peter V. Mørch",
"author_id": 345716,
"author_profile": "https://Stackoverflow.com/users/345716",
"pm_score": 5,
"selected": false,
"text": "git checkout $revision -- $file git show $revision:$file > $file\n git show $revision:$file\n git show $revision:$file | vim -R -\n $file ./ git show $revision:$file git archive $revision $file | tar -x0 > $file\n"
},
{
"answer_id": 41020368,
"author": "Vince",
"author_id": 1624598,
"author_profile": "https://Stackoverflow.com/users/1624598",
"pm_score": 4,
"selected": false,
"text": "git reset ... <file> git checkout ... <file> <file> git revert git diff git apply <sha> git diff <sha>^ <sha> path/to/file.ext | git apply -R\n <sha1> HEAD"
},
{
"answer_id": 42758961,
"author": "Francis Bacon",
"author_id": 5097539,
"author_profile": "https://Stackoverflow.com/users/5097539",
"pm_score": 2,
"selected": false,
"text": "git checkout commit_id file_path"
},
{
"answer_id": 42963059,
"author": "desmond13",
"author_id": 2761849,
"author_profile": "https://Stackoverflow.com/users/2761849",
"pm_score": 4,
"selected": false,
"text": "abc1 file.txt file.txt abc1 git checkout file.txt git checkout abc1 file.txt git commit -m \"Restored file.txt to version abc1\" git push git status file.txt git add"
},
{
"answer_id": 43204559,
"author": "Gulshan Maurya",
"author_id": 4035691,
"author_profile": "https://Stackoverflow.com/users/4035691",
"pm_score": 5,
"selected": false,
"text": "git reset HEAD path_to_file\n git checkout -- path_to_file\n"
},
{
"answer_id": 50231389,
"author": "Nir M.",
"author_id": 1518020,
"author_profile": "https://Stackoverflow.com/users/1518020",
"pm_score": 3,
"selected": false,
"text": "git revert <commit_hash> git reset HEAD~1 git add <file_i_want_to_revert> git commit -m 'reverting file' git checkout ."
},
{
"answer_id": 54352201,
"author": "Abhishek Dwivedi",
"author_id": 6146338,
"author_profile": "https://Stackoverflow.com/users/6146338",
"pm_score": 4,
"selected": false,
"text": "# git checkout <previous commit_id> <file_name>\n# git commit --amend\n"
},
{
"answer_id": 54550311,
"author": "ireshika piyumalie",
"author_id": 5567429,
"author_profile": "https://Stackoverflow.com/users/5567429",
"pm_score": 5,
"selected": false,
"text": "git checkout Last_Stable_commit_Number -- fileName\n git checkout branchName_Which_Has_stable_Commit fileName\n"
},
{
"answer_id": 57676529,
"author": "mjarosie",
"author_id": 3088888,
"author_profile": "https://Stackoverflow.com/users/3088888",
"pm_score": 7,
"selected": false,
"text": "git checkout git checkout source c5f567 git restore --source=c5f567 file1/to/restore file2/to/restore\n git restore --source=c5f567~1 file1/to/restore file2/to/restore\n"
},
{
"answer_id": 67104511,
"author": "Dev-lop-er",
"author_id": 9792530,
"author_profile": "https://Stackoverflow.com/users/9792530",
"pm_score": -1,
"selected": false,
"text": "git reset --soft HEAD^1\n git status\n git remote prune origin\n\n"
},
{
"answer_id": 69237447,
"author": "user1034533",
"author_id": 1034533,
"author_profile": "https://Stackoverflow.com/users/1034533",
"pm_score": -1,
"selected": false,
"text": "git revert -n <commit> git revert -n HEAD git reset git add a.txt b.txt c.txt git commit -m 'Undo <commit> for a.txt, b.txt, c.txt' git reset --hard"
},
{
"answer_id": 71530153,
"author": "Valeriy K.",
"author_id": 7804595,
"author_profile": "https://Stackoverflow.com/users/7804595",
"pm_score": 3,
"selected": false,
"text": "git log --oneline // you see commits, find commit hash to which you want reset\ngit diff y0urhash src/main/.../../YourFile.java // to see difference\ngit reset y0urhash src/main/.../../YourFile.java // revert to y0urhash commit\ngit status // check files to commit\ngit commit -m \"your commit message\"\ngit push origin\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3410/"
] |
215,719
|
<p>I'm following the <a href="http://www.asp.net/learn/mvc-videos/video-395.aspx" rel="nofollow noreferrer">ASP.Net MVC "TaskList" example video</a> and on clicking Run in Visual Studio (~14:00 min into the video) I'm getting the following error message in the browser:</p>
<pre><code>Server Error in '/' Application.
Bad IL format.
Description: An unhandled exception occurred during the execution of the
current webrequest. Please review the stack trace for more information
about the error andwhere it originated in the code.
Exception Details: System.BadImageFormatException: Bad IL format.
Source Error:
Line 12: ' (2) URL with parameters
Line 13: ' (3) Parameter defaults
Line 14: routes.MapRoute( _
Line 15: "Default", _
Line 16: "{controller}/{action}/{id}", _
Source File: C:\Users\...\TaskList\TaskList\Global.asax.vb Line: 14
Stack Trace:
[BadImageFormatException: Bad IL format.]
VB$AnonymousType_0`3..ctor(T0 controller, T1 action, T2 id) +0
TaskList.MvcApplication.RegisterRoutes(RouteCollection routes) in
C:\Users\...\TaskList\TaskList\Global.asax.vb:14
TaskList.MvcApplication.Application_Start() in
C:\Users\...\TaskList\TaskList\Global.asax.vb:23
Version Information:
Microsoft .NET Framework Version:2.0.50727.1434;
ASP.NET Version:2.0.50727.1434
</code></pre>
<p>I've double-checked the code I've typed in, what am I missing?</p>
<p>Thank you!</p>
<p>Versions:</p>
<ul>
<li>ASP.Net MVC Beta (16th October 2008)</li>
<li>Visual Studion 2008 (9.0.21022.8 RTM)</li>
<li>Vista Ultimate SP1</li>
<li>IIS 7.0.6000.16386</li>
</ul>
|
[
{
"answer_id": 216512,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 0,
"selected": false,
"text": "routes.MapRoute( _\n \"Default\", _\n \"{controller}/{action}/{id}\", _\n New With { .controller = \"Home\", .action = \"Index\" }\n)\n"
},
{
"answer_id": 219769,
"author": "Andrew",
"author_id": 5662,
"author_profile": "https://Stackoverflow.com/users/5662",
"pm_score": 3,
"selected": true,
"text": "HomeController.vb Public Class HomeController\n Inherits System.Web.Mvc.Controller\n\n ' Display a list of tasks\n Function Index()\n Return View()\n End Function\n\n ' Dislpay a form for creating a new task\n Function Create() As ActionResult\n Return View()\n End Function\n\n ' Adding a new task to the database\n Function CreateNew(ByVal task As String) As ActionResult\n ' add the new task to the database\n Return RedirectToAction(\"Index\")\n End Function\n\n ' Mark a task as complete\n Function Complete()\n ' database logic\n Return RedirectToAction(\"Index\")\n End Function\n\nEnd Class\n Function Complete() ' Mark a task as complete\n Function Complete() As ActionResult\n ' database logic\n Return RedirectToAction(\"Index\")\n End Function\n Global.asax.vb"
},
{
"answer_id": 40182162,
"author": "Tayyebi",
"author_id": 3847552,
"author_profile": "https://Stackoverflow.com/users/3847552",
"pm_score": 0,
"selected": false,
"text": "app.UseMvc(); Startup.cs app.UseMvc(routes =>\n {\n routes.MapRoute(\n name: \"default\",\n template: \"{controller=Home}/{action=Index}/{id?}\");\n });\n app.UseMvc();\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5662/"
] |
215,729
|
<p>What is the state of native SVG support in the most popular browsers in their latest releases?</p>
<ul>
<li>Internet explorer</li>
<li>Firefox</li>
<li>Opera</li>
<li>Safari</li>
<li>Chrome</li>
<li>Konqueror</li>
<li>Camino</li>
</ul>
|
[
{
"answer_id": 19298539,
"author": "iconoclast",
"author_id": 241142,
"author_profile": "https://Stackoverflow.com/users/241142",
"pm_score": 2,
"selected": false,
"text": "Time.now"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3153/"
] |
215,735
|
<p>I am trying to draw a domain model or class diagram in UML for car dealership. I am stuck with how to present test drive in the model. One way is to have appointment class and then test-drive as sub class. A dealer also offers after-sale vehicle service so i could have appointment/booking class as super class and then vehicle service and test-drive as two sub classes.</p>
<p>Another way is to have the customer class have a direct relationship with test drive class and vehicle service class under appointment class.</p>
<p>A dealer also sells new and used cars and their parts.</p>
<p>A dealer also offers finance for car sale.</p>
<p>Would testdrive class have relationship with vehicle class or there is separate class for display and testdrive class?</p>
<p>Another question is how do I show potential customers and their inquiries about sale and service in the model. A dealer wants to save details of potential customers if they allow for marketing purposes. Shall I have two classes: one for customers and one for potential customers or it can be achieved just by using an attribute in customer class?</p>
|
[
{
"answer_id": 6307687,
"author": "Novalis",
"author_id": 778894,
"author_profile": "https://Stackoverflow.com/users/778894",
"pm_score": 0,
"selected": false,
"text": "-- What kind of entities you have in yor domain?\n-- If they are important for your system under desing, \n what kind of properties they have, how they behave?\n-- What kind of business rules they obey?\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29312/"
] |
215,741
|
<p>MTOM is the W3C Message Transmission Optimization Mechanism, a method of efficiently sending binary data to and from web services.</p>
<p>How does it work in general?</p>
|
[
{
"answer_id": 15572342,
"author": "Jops",
"author_id": 1551022,
"author_profile": "https://Stackoverflow.com/users/1551022",
"pm_score": 7,
"selected": false,
"text": "<soap:Envelope>\n <soap:Body>\n <tns:data>\n <xop:include href=\"SomeUniqueID-ThatLeadsToTheImage\"/>\n </tns:data>\n </soap:Body>\n</soap:Envelope>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3153/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.