qid int64 4 19.1M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
369,007 | <p>I've been using NetBeans as the XDebug interactive debugging client. But seems like it only supports attaching debuggers to scripts that are invoked via Firefox. I want to step through the request parse script when it's invoked via cURL.</p>
| [
{
"answer_id": 369185,
"author": "lewen7er9",
"author_id": 46413,
"author_profile": "https://Stackoverflow.com/users/46413",
"pm_score": 2,
"selected": false,
"text": ">curl \"http://localhost/wordpress/wp-app.php/posts\" -X POST -H \"Content-type: application/atom+xml\" -v -L -k -u admin:password --data @post_atom_entry_bad.xml -o post_bad_response.txt -b XDEBUG_SESSION=netbeans-xdebug\n* About to connect() to localhost port 80 (#0)\n* Trying 127.0.0.1... connected\n* Connected to localhost (127.0.0.1) port 80 (#0)\n* Server auth using Basic with user 'admin'\n> POST /wordpress/wp-app.php/posts HTTP/1.1\n> Authorization: Basic YWRtaW46d2Fuc3Vp\n> User-Agent: curl/7.19.1 (i586-pc-mingw32msvc) libcurl/7.19.1 OpenSSL/0.9.8i zlib/1.2.3\n> Host: localhost\n> Accept: */*\n> Cookie: XDEBUG_SESSION=netbeans-xdebug\n> Content-type: application/atom+xml\n> Content-Length: 302\n>\n} [data not shown]\n % Total % Received % Xferd Average Speed Time Time Time Current\n Dload Upload Total Spent Left Speed\n100 302 0 0 0 302 0 74 --:--:-- 0:00:04 --:--:-- 0\n % Total % Received % Xferd Average Speed Time Time Time Current\n Dload Upload Total Spent Left Speed\n100 302 0 0 0 302 0 2 --:--:-- 0:02:17 --:--:-- 0< HTTP/1.1 400 Bad Request\n< Date: Mon, 15 Dec 2008 17:47:06 GMT\n< Server: Apache/2.2.9 (Win32) DAV/2 mod_ssl/2.2.9 OpenSSL/0.9.8i mod_autoindex_color PHP/5.2.6\n< X-Powered-By: PHP/5.2.6\n< Content-Length: 0\n< Connection: close\n< Content-Type: text/plain\n<\n100 302 0 0 0 302 0 2 --:--:-- 0:02:18 --:--:-- 0* Closing connection #0\n\n\n>\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46413/"
] |
369,011 | <p>Is it possible to avoid the automatic collapse of a Silverlight ComboBox after LostFocus?</p>
| [
{
"answer_id": 371033,
"author": "Sorskoot",
"author_id": 31722,
"author_profile": "https://Stackoverflow.com/users/31722",
"pm_score": 2,
"selected": true,
"text": "private void FocusChanged(bool hasFocus)\n{\n this.UpdateSelectionBoxHighlighted();\n base.SetValueInternal(IsSelectionActiveProperty, hasFocus, true);\n if (!hasFocus)\n {\n this.IsDropDownOpen = false;\n }\n} \n"
},
{
"answer_id": 2176649,
"author": "R4cOOn",
"author_id": 124930,
"author_profile": "https://Stackoverflow.com/users/124930",
"pm_score": 2,
"selected": false,
"text": "\n protected override void OnLostFocus(RoutedEventArgs e)\n {\n base.OnLostFocus(e);\n this.FocusChanged(this.HasFocus());\n }\n ComboBox Popup public class ComboBoxWithMultiSelect : ComboBox\n{\n protected override void OnKeyDown(KeyEventArgs e)\n {\n if (base.IsDropDownOpen &&\n (e.Key == Key.Enter ||\n e.Key == Key.Space))\n {\n e.Handled = true;\n }\n else\n {\n base.OnKeyDown(e);\n }\n }\n\n protected override DependencyObject GetContainerForItemOverride()\n {\n return new ComboBoxItemWithMultiSelect();\n }\n}\n\n\npublic class ComboBoxItemWithMultiSelect : ComboBoxItem\n{\n protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)\n {\n if (e == null)\n {\n throw new ArgumentNullException(\"e\");\n }\n if (!e.Handled)\n {\n e.Handled = true;\n }\n }\n}\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3714/"
] |
369,023 | <p>I have a directory on a linux box that I want to make publicly readable using Tomcat (5.5). I think this is easy to set up but can't find the appropriate documentation. Is there a simple way to accomplish this?</p>
| [
{
"answer_id": 369033,
"author": "Joachim Sauer",
"author_id": 40342,
"author_profile": "https://Stackoverflow.com/users/40342",
"pm_score": 2,
"selected": false,
"text": "$TOMCAT_HOME/webapps $TOMCAT_HOME/conf/server.xml .xml $TOMCAT_HOME/conf/Catalina/localhost"
},
{
"answer_id": 369038,
"author": "Yoni Roit",
"author_id": 34161,
"author_profile": "https://Stackoverflow.com/users/34161",
"pm_score": 2,
"selected": false,
"text": "ln -s /path-to-real-folder /path-to-tomcat/webapps/publicfoldername\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8207/"
] |
369,024 | <p>How do I achieve the equivalent of the LVIS_CUT style for a listview item? It looks like it's not exposed by the framework? Should I P/Invoke?</p>
<p>Edit: LVIS_CUT is a Win32 style that affects the look of the item: It grays the item image. You can see it in action in Windows Explorer: Select a file and type Ctrl+X.</p>
<p>TIA.</p>
| [
{
"answer_id": 533611,
"author": "Daniel LeCheminant",
"author_id": 62055,
"author_profile": "https://Stackoverflow.com/users/62055",
"pm_score": 1,
"selected": false,
"text": "private void MakeCutList(ImageList sourceList, Color background)\n{\n Brush overlay = new SolidBrush(Color.FromArgb(128, BackColor));\n Rectangle rect = new Rectangle(new Point(0, 0), sourceList.ImageSize);\n\n foreach (Image img in sourceList.Images)\n {\n Bitmap cutBmp = new Bitmap(img.Width, img.Height);\n\n using (Graphics g = Graphics.FromImage(cutBmp))\n {\n g.DrawImage(img, 0, 0);\n g.FillRectangle(overlay, rect);\n }\n\n sourceList.Images.Add(cutBmp); \n }\n}\n public Form1()\n{\n InitializeComponent();\n MakeCutList(listView1.LargeImageList, listView1.BackColor);\n}\n private void SetCutState(ListViewItem lvi, Boolean isItemCut)\n{\n int originalListSize = lvi.ImageList.Images.Count / 2;\n int baseIndex = lvi.ImageIndex % originalListSize;\n int cutImagesOffset = originalListSize;\n\n if (isItemCut)\n {\n lvi.ImageIndex = cutImagesOffset + baseIndex;\n lvi.ForeColor = SystemColors.GrayText;\n }\n else\n {\n lvi.ImageIndex = baseIndex;\n lvi.ForeColor = SystemColors.WindowText;\n }\n}\n"
},
{
"answer_id": 9098766,
"author": "Murhaf Sousli",
"author_id": 1015648,
"author_profile": "https://Stackoverflow.com/users/1015648",
"pm_score": 0,
"selected": false,
"text": " private void MakeCutItem()\n {\n foreach (ListViewItem item in listView1.SelectedItems)\n {\n Image img = item.ImageList.Images[item.ImageIndex];\n Brush overlay = new SolidBrush(Color.FromArgb(128, BackColor));\n Rectangle rect = new Rectangle(new Point(0, 0), item.ImageList.ImageSize);\n using (Graphics g = Graphics.FromImage(img))\n {\n g.FillRectangle(overlay, rect);\n }\n item.ImageIndex = item.ImageList.Images.Add(img,Color.Empty);\n }\n }\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12379/"
] |
369,026 | <p>I have a page with a <code>document.onkeydown</code> event handler, and I'm loading it inside an iframe in another page. I have to click inside the iframe to get the content page to start "listening". </p>
<p>Is there some way I can use JavaScript in the outer page to set the focus to the inner page so I don't have to click inside the iframe?</p>
<p>EDIT: response to comment: </p>
<p>The context is the main window is a light-box-like system, except instead of pictures, it shows iframes, and each iframe is an interactive page with keydown/mousemove handlers. these handlers don't fire until I click in the iframe after showing the light-box-thing.</p>
<p>I'm not actually looking to "setFocus" in the traditional sense as much as "enable event handlers on the iframe contentDocument"</p>
| [
{
"answer_id": 369034,
"author": "Jaime Febres",
"author_id": 33205,
"author_profile": "https://Stackoverflow.com/users/33205",
"pm_score": 4,
"selected": false,
"text": "document.getElementsByName(\"iframe_name\")[0].contentWindow.document.body.focus();\n"
},
{
"answer_id": 376580,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 0,
"selected": false,
"text": "var iframe = ...\nvar doc = iframe.contentDocument;\n\nvar i = doc.createElement('input');\ni.style.display = 'none'; \ndoc.body.appendChild(i);\ni.focus();\ndoc.body.removeChild(i);\n"
},
{
"answer_id": 2070472,
"author": "cheeming",
"author_id": 28836,
"author_profile": "https://Stackoverflow.com/users/28836",
"pm_score": 7,
"selected": true,
"text": "function setFocusThickboxIframe() {\n var iframe = $(\"#TB_iframeContent\")[0];\n iframe.contentWindow.focus();\n}\n\n$(document).ready(function(){\n $(\"#id_cmd_open\").click(function(){\n /*\n run thickbox code here to open lightbox,\n like tb_show(\"google this!\", \"http://www.google.com\");\n */\n setTimeout(setFocusThickboxIframe, 100);\n return false;\n });\n});\n"
},
{
"answer_id": 3264166,
"author": "danza",
"author_id": 393758,
"author_profile": "https://Stackoverflow.com/users/393758",
"pm_score": 5,
"selected": false,
"text": "onload=\"this.contentWindow.focus()\""
},
{
"answer_id": 13462026,
"author": "nate_weldon",
"author_id": 1209369,
"author_profile": "https://Stackoverflow.com/users/1209369",
"pm_score": 2,
"selected": false,
"text": " var iframeID = document.getElementById(\"modalIFrame\"); \n//focus the IFRAME element \n$(iframeID).focus(); \n//use JQuery to find the control in the IFRAME and set focus \n$(iframeID).contents().find(\"#emailTxt\").focus(); \n"
},
{
"answer_id": 29612835,
"author": "Stephen Ostermiller",
"author_id": 1145388,
"author_profile": "https://Stackoverflow.com/users/1145388",
"pm_score": 2,
"selected": false,
"text": "var jqueryIframe = $('<iframe>', {\n src: \"http://example.com\"\n}),\nfocusWhenReady = function(){\n var iframe = jqueryIframe[0],\n doc = iframe.contentDocument || iframe.contentWindow.document;\n if (doc.readyState == \"complete\") {\n iframe.contentWindow.focus();\n } else {\n setTimeout(focusWhenReady, 100)\n }\n}\n$(document).append(jqueryIframe);\nsetTimeout(focusWhenReady, 10);\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4435/"
] |
369,042 | <p>I have a table with doctor offices and doctors in those offices that I'm populating to a repeater control. The data coming back is not aggregated. So, if there are 2 doctors in 1 office, there are 2 rows, same office, different doctor. </p>
<p>Is there a way to aggregate the data so the repeater shows 1 office with all of the doctors from that office so I can avoid the duplication?</p>
| [
{
"answer_id": 369118,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": true,
"text": "<table><tr><th>Office</th><th>Doctors</th></tr>\n<asp:repeater id=\"Repeater\" runat=\"server\" OnItemDataBound=\"NextItem\" ... >\n <ItemTemplate><asp:Literal id=\"RepeaterRow\" runat=\"server\" />\n </ItemTemplate>\n</asp:repeater>\n<asp:Literal id=\"LastRow\" runat=\"server\" />\n</table>\n public class Office\n{\n public string OfficeName {get;set;};\n List<string> _doctors = new List<string>();\n public List<string> Doctors {get{ return _doctors; } };\n\n void Clear()\n {\n OfficeName = \"\";\n _doctors.Clear();\n }\n\n public override string ToString()\n {\n StringBuilder result = new StringBuilder(\"<tr>\");\n\n result.AppendFormat(\"<td>{0}</td>\", OfficeName);\n\n string delimiter = \"\";\n result.Append(\"<td>\");\n foreach(string doctor in Doctors)\n {\n result.Append(doctor).Append(delimiter);\n delimiter = \"<br/>\";\n }\n\n result.Append(\"</td></tr>\");\n\n return result.ToString();\n }\n}\n private string CurOffice = \"\";\nprivate Office CurRecord = new Office();\n\nvoid NextItem(object sender, RepeaterItemEventArgs e)\n{\n if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem) return;\n\n Literal repeaterRow = e.Item.FindControl(\"RepeaterRow\") as Literal;\n if (repeaterRow == null) return;\n\n DataRow row = ((DataRowView)e.Item.DataItem).Row;\n\n if ( CurOffice != (string)row[\"Office\"] )\n {\n repeaterRow.Text = CurRecord.ToString();\n repeaterRow.Visible = true;\n\n CurRecord.Clear();\n CurOffice = row[\"Office\"];\n CurRecord.Office = CurOffice;\n }\n else\n e.Item.Visible = false;\n\n CurRecord.Doctors.Add((string)row[\"doctor\"]);\n}\n\nvoid Page_PreRender(object sender, EventArgs e)\n{\n LastRow.Text = CurRecord.ToString();\n}\n"
},
{
"answer_id": 388947,
"author": "Bill Martin",
"author_id": 46064,
"author_profile": "https://Stackoverflow.com/users/46064",
"pm_score": 0,
"selected": false,
"text": "DECLARE @EmployeeList varchar(100)\n\nSELECT @EmployeeList = COALESCE(@EmployeeList + ', ', '') + \n CAST(Emp_UniqueID AS varchar(5))\nFROM SalesCallsEmployees\nWHERE SalCal_UniqueID = 1\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45043/"
] |
369,046 | <p>I want to debug my project in Zend Framework in Eclipse. Zend Debugger is already running bud now I have problem with Debug tool in Eclipse. It give an extra GET parametrs and the project in Zend don't like it.</p>
<p>I tried to google it and found <a href="http://framework.zend.com/wiki/display/ZFDEV/Configuring+Your+URL+Rewriter" rel="nofollow noreferrer">this</a></p>
<p>I modifed the <em>.htaccess</em> file but not make it working.</p>
<pre><code>RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.*)?(start_debug=1.*)$ index.php?$2 [L]
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]
</code></pre>
<p>Don't know if its completely right because the Rewrite rules on the <a href="http://framework.zend.com/wiki/display/ZFDEV/Configuring+Your+URL+Rewriter" rel="nofollow noreferrer">page</a> has some for me uknown flags which my Apache do not work with.</p>
<p>the link which is Eclipse making is </p>
<blockquote>
<p><a href="http://localhost/?debug_start_url=http://localhost/&debug_session_id=1007&start_debug=1&debug_host=127.0.0.1&debug_no_cache=1229359621130&debug_port=10000&send_sess_end=1&original_url=http://localhost/&debug_stop=1" rel="nofollow noreferrer">http://localhost/?debug_start_url=http://localhost/&debug_session_id=1007&start_debug=1&debug_host=127.0.0.1&debug_no_cache=1229359621130&debug_port=10000&send_sess_end=1&original_url=http://localhost/&debug_stop=1</a></p>
</blockquote>
| [
{
"answer_id": 371713,
"author": "Akeem",
"author_id": 35505,
"author_profile": "https://Stackoverflow.com/users/35505",
"pm_score": 1,
"selected": false,
"text": "<IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteRule ^(.*)$ index.php [QSA,L]\n RewriteCond %{REQUEST_FILENAME} (logs|library|application|config)\n RewriteRule ^(.*)$ index.php\n</IfModule>\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45846/"
] |
369,065 | <p>I'm about to start a project where programmers will be contributing from their homes (much like stackoverflow was built)</p>
<p>I want to use some centralized source control, but I don't want it to require the programmers to be online, and the server may come offline from time to time (as at first it'll probably be my desktop machine)</p>
<p>I think I remember Jeff talking about this in some podcast, but I don't remember which one.</p>
<p>Is there a source control tool that works perhaps asynchronically by e-mail?
Programmers could connect to download the latest version, and the checkin process would be sending files to an email account for example</p>
<p>Does such a thing exist?</p>
<p>EDIT: Sorry, I forgot to say that I'll be working with .NET (Visual Studio 2008)</p>
<p>It'd be great if it could be integrated into this environment... does GIT (suggested below) support that?</p>
| [
{
"answer_id": 369075,
"author": "Joachim Sauer",
"author_id": 40342,
"author_profile": "https://Stackoverflow.com/users/40342",
"pm_score": 4,
"selected": false,
"text": "git"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369065",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1782/"
] |
369,090 | <p>When I drag a link that is inside a draggable div over an iframe in IE7, I get very strange results. Try the code below and let me know if you have any suggestions about how to fix this.</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<!--<script type="text/javascript" src="/js/prototype.js"></script>-->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.3/prototype.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/scriptaculous/1.8.2/scriptaculous.js?load=effects,dragdrop,controls"></script>
<!--<script type="text/javascript" src="/js/scriptaculous.js?load=effects,dragdrop,controls"></script>-->
</head>
<body>
<div id="test" style="background-color: #aaaaaa; width: 200px; height: 50px;">
<a href="blah" onclick="blah(); return false;">blah</a>
</div>
<iframe>
</iframe>
</body>
<script>
function blah(){
//blackbird.debug("blah");
}
var dummy = new Draggable("test", {scroll:window,scrollSensitivity: 20,scrollSpeed: 25, revert: true, onStart: onDragStart, onEnd: onDragEnd });
var temp;
function onDragStart(drgObj,mouseEvent){
temp = mouseEvent.target.onclick;
mouseEvent.target.onclick = function(e){
mouseEvent.target.onclick = temp;
return false;
}
}
function onDragEnd(drgObj,mouseEvent){
}
</script>
</html>
</code></pre>
| [
{
"answer_id": 369238,
"author": "Tony",
"author_id": 45849,
"author_profile": "https://Stackoverflow.com/users/45849",
"pm_score": 0,
"selected": false,
"text": "<div style=\"filter:alpha(opacity=1); opacity: 0.01; -moz-opacity:0.01;\">\n <iframe> \n </iframe>\n</div>\n"
},
{
"answer_id": 598511,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<div id=\"main_container\">\n <div>\n <iframe></iframe>\n </div>\n <div id=\"youredragelelement\"><img /></div>\n</div>\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45849/"
] |
369,102 | <p>Does anyone know how I could go about doing something like :</p>
<p>Html.ActionLink(c => c.SomeAction(new MessageObject { Id = 1 } ))</p>
<p>This should output a link with the url of "/Controller/SomeAction/1", pointing at an ActionMethod along the lines of:</p>
<pre><code>public Controller : Controller
{
public ActionResult SomeMethod(MessageObject message)
{
// do something with the message
return View();
}
}
</code></pre>
<p>I've written something similar for generating forms, but that doens't need to include the Id value on the end of the Url. Basically I want to do some sort of reverse lookup in my routes but I can't find any doco on how I might go about doing that. I have a ModelBinder setup that is able to build a MessageObject from GET and POST parameters, but I'm not sure how I can reverse the process.</p>
<p>Thanks,
Matt</p>
| [
{
"answer_id": 370375,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 0,
"selected": false,
"text": "public ActionResult SomeMethod()\n{\n int messageObjectID;\n if (RouteData.Values.TryGetValue(\"id\",out messageObjectID))\n {\n ... get the object with the correct id and process it...\n }\n else\n {\n ... error processing because the id was not available...\n }\n return View();\n}\n"
},
{
"answer_id": 374283,
"author": "mattcole",
"author_id": 12459,
"author_profile": "https://Stackoverflow.com/users/12459",
"pm_score": 1,
"selected": false,
"text": " public static RouteValueDictionary GetRouteValuesFromExpression<TController>(Expression<Action<TController>> action)\n where TController : Controller\n {\n Guard.Against<ArgumentNullException>(action == null, @\"Action passed to GetRouteValuesFromExpression cannot be null.\");\n MethodCallExpression methodCall = action.Body as MethodCallExpression;\n Guard.Against<InvalidOperationException>(methodCall == null, @\"Action passed to GetRouteValuesFromExpression must be method call\");\n string controllerName = typeof(TController).Name;\n Guard.Against<InvalidOperationException>(!controllerName.EndsWith(\"Controller\"), @\"Controller passed to GetRouteValuesFromExpression is incorrect\");\n\n RouteValueDictionary rvd = new RouteValueDictionary();\n rvd.Add(\"Controller\", controllerName.Substring(0, controllerName.Length - \"Controller\".Length));\n rvd.Add(\"Action\", methodCall.Method.Name);\n\n AddParameterValuesFromExpressionToDictionary(rvd, methodCall);\n return rvd;\n }\n\n /// <summary>\n /// Adds a route value for each parameter in the passed in expression. If the parameter is primitive it just uses its name and value\n /// if not, it creates a route value for each property on the object with the property's name and value.\n /// </summary>\n /// <param name=\"routeValues\"></param>\n /// <param name=\"methodCall\"></param>\n private static void AddParameterValuesFromExpressionToDictionary(RouteValueDictionary routeValues, MethodCallExpression methodCall)\n {\n ParameterInfo[] parameters = methodCall.Method.GetParameters();\n methodCall.Arguments.Each(argument =>\n {\n int index = methodCall.Arguments.IndexOf(argument);\n\n ConstantExpression constExpression = argument as ConstantExpression;\n if (constExpression != null)\n {\n object value = constExpression.Value;\n routeValues.Add(parameters[index].Name, value);\n }\n else\n {\n object actualArgument = argument;\n MemberInitExpression expression = argument as MemberInitExpression;\n if (expression != null)\n {\n actualArgument = Expression.Lambda(argument).Compile().DynamicInvoke();\n }\n\n // create a route value for each property on the object\n foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(actualArgument))\n {\n object obj2 = descriptor.GetValue(actualArgument);\n routeValues.Add(descriptor.Name, obj2);\n }\n }\n });\n }\n"
},
{
"answer_id": 2224056,
"author": "Ian Mercer",
"author_id": 224370,
"author_profile": "https://Stackoverflow.com/users/224370",
"pm_score": 0,
"selected": false,
"text": "// This const is only needed if the route isn't already mapped \n// by some more general purpose route (e.g. {controller}/{action}/{message}\npublic const string SomeMethodUrl = \"/Home/SomeMethod/{message}\";\n\n// This method generates route values that match the SomeMethod method signature\n// You can add default values here too\npublic static object SomeMethodRouteValues(MessageObject messageObject)\n{\n return new { controller = \"Home\", action = \"SomeMethod\", \n message = messageObject };\n} \n Routes.MapRoute (\"SomeMethod\", \n HomeController.SomeMethodUrl,\n HomeController.SomeMethodRouteValues(null));\n <%=Url.RouteUrl(HomeController.SomeMethodValues(new MessageObject())) %>\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12459/"
] |
369,104 | <p>I'm looking to automate the backup of a Windows XP file structure (a wiki) into CVS.<br>
Through repeated calls to <em>cvs commit</em> and <em>cvs add</em> I can identify and commit changed files and newly added files, but I can't see a cvs command that would let me know a local file has been deleted. </p>
<p>One possibility would be to update a parallel file structure with the latest files from the repository and then remove those files that only appear in second structure, but I was hoping there was a more efficient solution? </p>
| [
{
"answer_id": 369131,
"author": "David Norman",
"author_id": 34502,
"author_profile": "https://Stackoverflow.com/users/34502",
"pm_score": 2,
"selected": false,
"text": "cvs -nq update\n cvs update: warning: SourceControlledFile.xml was lost\n"
},
{
"answer_id": 4959315,
"author": "Adam Nofsinger",
"author_id": 18524,
"author_profile": "https://Stackoverflow.com/users/18524",
"pm_score": 0,
"selected": false,
"text": "cvs remove -R\n -f cvs -nq update | findstr /C:\"U \"\n cvs remove -R\n cvs -nq update | findstr /C:\"U \"\n U file1.cs\nU file2_23.cs\nU directory_1/Reports/test.rpt\n cvs remove"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43168/"
] |
369,116 | <p>When I hit /// in Visual Studio, is it possible to change the resulting snippet from this:</p>
<pre><code>/// <summary>
///
/// </summary>
</code></pre>
<p>to this?:</p>
<pre><code>/// <summary></summary>
</code></pre>
| [
{
"answer_id": 5574557,
"author": "Valamas",
"author_id": 511438,
"author_profile": "https://Stackoverflow.com/users/511438",
"pm_score": 5,
"selected": true,
"text": "/// <summary> </summary>\n <CodeSnippets xmlns=\"http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet\">\n\n <CodeSnippet Format=\"1.0.0\">\n <Header>\n <Title>Summary - inline</Title>\n <Description>Created inline summary comment tag</Description>\n <Author>Mike Vanderkley</Author>\n <Shortcut>summ</Shortcut>\n <SnippetTypes>\n <SnippetType>Expansion</SnippetType>\n </SnippetTypes>\n </Header>\n <Snippet>\n <Code Language=\"csharp\">\n <![CDATA[/// <summary> $end$ </summary>]]>\n </Code>\n </Snippet>\n </CodeSnippet>\n\n</CodeSnippets>\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2596/"
] |
369,120 | <p>Every now and then I get an error when I set up states in an MXML file. The error I get says that mx:states could not be resolved to a component implementation.</p>
<p>I read, at the following url, that this issue is caused by extending components - that somehow throws off the compiler's ability to resolve mx:states. I don't see why this should be the case, but I don't have any answer of my own. I also can't necessarily make this approach work with all of my extended components.</p>
<p><a href="http://life.neophi.com/danielr/2007/01/could_not_resolve_to_a_compone.html" rel="nofollow noreferrer">http://life.neophi.com/danielr/2007/01/could_not_resolve_to_a_compone.html</a></p>
<p>The workaround I've come up with is to not use any namespace.
So, my code then looks like this:</p>
<pre><code><states>...</states>
</code></pre>
<p>rather than:</p>
<pre><code><mx:states>...</mx:states>
</code></pre>
<p>Making this stranger (at least, to me) is the fact that the children of the tag - - does not have this issue. mx:states can not be resolved, but its child mx:State can. And mx:SetProperty - a child of mx:State - is also resolved.</p>
<p>Can anyone explain this, and/or offer a better solution to the problem than what I've come up with?</p>
<p>Incidentally, I see the same issue with mx:transitions.</p>
| [
{
"answer_id": 369605,
"author": "Josh Tynjala",
"author_id": 10768,
"author_profile": "https://Stackoverflow.com/users/10768",
"pm_score": 5,
"selected": true,
"text": "<example:MyComponent xmlns:mx=\"http://www.adobe.com/2006/mxml\"\n xmlns:example=\"com.example.*\">\n</example:MyComponent>\n <example:MyComponent xmlns:mx=\"http://www.adobe.com/2006/mxml\"\n xmlns:example=\"com.example.*\">\n\n <example:states>\n <mx:State name=\"CustomState\">\n </mx:State>\n </example:states>\n\n</example:MyComponent>\n <zzz:VBox xmlns:zzz=\"http://www.adobe.com/2006/mxml\">\n <zzz:states>\n </zzz:states>\n</zzz:VBox>\n"
},
{
"answer_id": 372684,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<mx:VBox xmlns:mx=\"http://www.adobe.com/2006/mxml\"\n width=\"100%\" \n height=\"100%\"\n backgroundColor=\"#f7f7f7\" \n xmlns:common=\"com.americanexpress.voice.view.component.common.*\">\n <mx:states name=\"edit\">\n <mx:"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37446/"
] |
369,122 | <p>I have the following Clojure code and I'm not sure why it's not working:</p>
<pre><code>(defn match (x y &optional binds)
(cond
((eql x y) (values binds t))
((assoc x binds) (match (binding x binds) y binds))
((assoc y binds) (match x (binding y binds) binds))
((var? x) (values (cons (cons x y) binds) t))
((var? y) (values (cons (cons y x) binds) t))
(t
(when (and (consp x) (consp y))
(multiple-value-bind (b2 yes)
(match (car x) (car y) binds)
(and yes (match (cdr x) (cdr y) b2)))))))
</code></pre>
<p>(The code is translated from Paul Graham's <em>ANSI Common Lisp</em> book.)</p>
<p>When I run it, I get the following error:</p>
<pre><code>java.lang.IllegalArgumentException: Don't know how to create ISeq from: Symbol
clojure.lang.Compiler$CompilerException: NO_SOURCE_FILE:2: java.lang.RuntimeException: java.lang.IllegalArgumentException: Don't know how to create ISeq from: Symbol
at clojure.lang.Compiler.analyze(Compiler.java:3713)
at clojure.lang.Compiler.analyzeSeq(Compiler.java:3848)
at clojure.lang.Compiler.analyze(Compiler.java:3698)
at clojure.lang.Compiler.access$200(Compiler.java:37)
at clojure.lang.Compiler$DefExpr$Parser.parse(Compiler.java:343)
at clojure.lang.Compiler.analyzeSeq(Compiler.java:3858)
at clojure.lang.Compiler.analyze(Compiler.java:3698)
at clojure.lang.Compiler.analyzeSeq(Compiler.java:3848)
at clojure.lang.Compiler.analyze(Compiler.java:3698)
at clojure.lang.Compiler.analyze(Compiler.java:3671)
at clojure.lang.Compiler.eval(Compiler.java:3895)
at clojure.lang.Repl.main(Repl.java:75)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at jline.ConsoleRunner.main(ConsoleRunner.java:69)
Caused by: java.lang.RuntimeException: java.lang.RuntimeException: java.lang.IllegalArgumentException: Don't know how to create ISeq from: Symbol
at clojure.lang.LazyCons.rest(LazyCons.java:64)
at clojure.lang.ASeq.count(ASeq.java:85)
at clojure.lang.RT.count(RT.java:486)
at clojure.lang.Cons.count(Cons.java:41)
at clojure.lang.Compiler.analyze(Compiler.java:3695)
... 16 more
Caused by: java.lang.RuntimeException: java.lang.IllegalArgumentException: Don't know how to create ISeq from: Symbol
at clojure.lang.LazyCons.first(LazyCons.java:44)
at clojure.lang.LazyCons.rest(LazyCons.java:59)
... 20 more
Caused by: java.lang.IllegalArgumentException: Don't know how to create ISeq from: Symbol
at clojure.lang.RT.seqFrom(RT.java:465)
at clojure.lang.RT.seq(RT.java:448)
at clojure.seq__28.invoke(boot.clj:92)
at clojure.every_QMARK___596.invoke(boot.clj:1180)
at clojure.fn__1147$psig__1149.invoke(boot.clj:2155)
at clojure.map__602$fn__605.invoke(boot.clj:1214)
at clojure.lang.LazyCons.first(LazyCons.java:40)
... 21 more
</code></pre>
<p>What am I doing wrong here?</p>
| [
{
"answer_id": 369332,
"author": "Paul Reiners",
"author_id": 7648,
"author_profile": "https://Stackoverflow.com/users/7648",
"pm_score": 6,
"selected": true,
"text": "(defn match [x y &optional binds]\n"
},
{
"answer_id": 370027,
"author": "drewr",
"author_id": 3227,
"author_profile": "https://Stackoverflow.com/users/3227",
"pm_score": 4,
"selected": false,
"text": "(cond\n test1 eval1\n test2 eval2\n :else eval3)\n"
},
{
"answer_id": 4679009,
"author": "starblue",
"author_id": 49246,
"author_profile": "https://Stackoverflow.com/users/49246",
"pm_score": 2,
"selected": false,
"text": ". \"bla bla\". \"bla bla.\""
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7648/"
] |
369,128 | <p>I have a simple iPhone app that has a tab bar and 3 tabs. Each tab loads as a separate nib with a corresponding controller. Each nib contains a tableview with some other controls for searching/filtering etc.</p>
<p>What I would like (and cant seem to find an example of) is adding a navigation controller to the app so each nib (i.e. each tab) can drill down to further detail pages.</p>
<p>Should I be adding a navigation controller to the main window and creating an <code>IBOutlet</code> for it or should the NC be added to the nibs.</p>
| [
{
"answer_id": 9290046,
"author": "Max B.",
"author_id": 578852,
"author_profile": "https://Stackoverflow.com/users/578852",
"pm_score": 5,
"selected": false,
"text": " UIViewController *viewController1, *viewController2;\n\n viewController1 = [[[UIViewController alloc] initWithNibName:@\"FirstViewController_iPhone\" bundle:nil] autorelease];\n UINavigationController *navigationcontroller = [[[UINavigationController alloc] initWithRootViewController:viewController1] autorelease];\n\n viewController2 = [[[UIViewController alloc] initWithNibName:@\"SecondViewController_iPhone\" bundle:nil] autorelease];\n\n self.tabBarController = [[[UITabBarController alloc] init] autorelease];\n self.tabBarController.viewControllers = [NSArray arrayWithObjects:navigationcontroller, viewController2, nil];\n self.navigationController didSelectRowAtIndexPath - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath\n{\n DetailViewController *detailViewController = [[DetailViewController alloc] initWithNibName:@\"DetailViewController\" bundle:nil];\n [self.navigationController pushViewController:detailViewController animated:YES];\n [detailViewController release];\n}\n detailViewController UIBarButtonItem detailViewController -(void) GoBack\n{ \n [self.navigationController popViewControllerAnimated:YES];\n}\n"
},
{
"answer_id": 10218840,
"author": "john.k.doe",
"author_id": 774691,
"author_profile": "https://Stackoverflow.com/users/774691",
"pm_score": 3,
"selected": false,
"text": "Editor Embed In > Tab Bar Controller"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
369,132 | <p>I have two services and am sending pretty chunky messages between them (~100kb). Though the previously mentioned value is typical of the size of the message, it is possible for it to fluctuate greatly (in both positive and negative directions).</p>
<p>Thus, to deal with such situations where i have to transport a swollen message I have cranked up all the max message size, max string size etc attributes in the app.config on both client and server end (with the relevant endpoint correctly referencing the binding which states the sizes).</p>
<p>The bound I have put in completely exceeds any possible message size for safety's sake. However, where the inter-service communication has proved reliable at the lower end of the message size scale, at the higher end this is not so - messages do not seem to be delivered at all.</p>
<p>The strangest thing is that <em>if</em> the message had exceeded max size then an exception would be thrown (I have encountered enough of these to know this! lol), but nothing gets thrown - it all passes by completely silently. I have experimented with various sizes of messages and it definitely only begins to happen as the message size grows. I can prove are not being received by the destination service as, upon reception, the service makes a log in a DB - but with big messages, no log is made.</p>
<p>As I said, I am almost certain I have increased the size of all applicable attributes in the app.config, and so am completely and utterly baffled by this behaviour!</p>
<p>Any suggestions on what could be causing such mystifying behaviour?</p>
| [
{
"answer_id": 374169,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<services>\n <service name=\"DataFeederService.FeederService\" behaviorConfiguration=\"DataFeederService.FeederServiceBehavior\">\n <host>\n <baseAddresses>\n <add baseAddress=\"http://localhost:8010/Feeder\"/>\n <add baseAddress=\"net.pipe://localhost/FeederPipe\"/>\n </baseAddresses>\n </host>\n <!-- Service Endpoints -->\n <!-- Unless fully qualified, address is relative to base address supplied above -->\n <endpoint name=\"namedPipeEndpoint\" \n address=\"\" \n bindingConfiguration=\"IPCWindowsSecurity\" \n binding=\"netNamedPipeBinding\" \n contract=\"DataFeederService.IFeederService\">\n <identity>\n <dns value=\"localhost\" />\n </identity>\n </endpoint>\n\n <endpoint name=\"httpEndpoint\" \n address=\"FeederService\" \n binding=\"wsHttpBinding\" \n bindingConfiguration=\"httpBinding\" \n contract=\"DataFeederService.IWebFeederService\"/>\n\n <!-- Metadata Endpoints -->\n <!-- The Metadata Exchange endpoint is used by the service to describe itself to clients. -->\n <!-- This endpoint does not use a secure binding and should be secured or removed before deployment -->\n <endpoint address=\"mex\" binding=\"mexHttpBinding\" contract=\"IMetadataExchange\"/>\n </service>\n</services>\n\n<bindings>\n <netNamedPipeBinding>\n <binding name=\"IPCWindowsSecurity\" \n maxBufferPoolSize=\"965536\" \n maxBufferSize=\"965536\" \n maxReceivedMessageSize=\"965536\">\n <readerQuotas maxStringContentLength=\"965536\" />\n <security mode=\"Transport\">\n <transport protectionLevel=\"EncryptAndSign\" />\n </security>\n </binding>\n </netNamedPipeBinding>\n <wsHttpBinding>\n <binding name=\"httpBinding\" \n maxBufferPoolSize=\"965536\"\n maxReceivedMessageSize=\"965536\">\n <readerQuotas maxStringContentLength=\"965536\" />\n </binding>\n </wsHttpBinding>\n</bindings>\n\n<behaviors>\n <serviceBehaviors>\n <behavior name=\"DataFeederService.FeederServiceBehavior\">\n <!-- To avoid disclosing metadata information, \n set the value below to false and remove the metadata endpoint above before deployment -->\n <serviceMetadata httpGetEnabled=\"True\" policyVersion=\"Policy15\"/>\n <!-- To receive exception details in faults for debugging purposes, \n set the value below to true. Set to false before deployment \n to avoid disclosing exception information -->\n <serviceDebug includeExceptionDetailInFaults=\"True\" httpHelpPageEnabled=\"true\" />\n </behavior>\n </serviceBehaviors>\n</behaviors>\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
369,145 | <p>When the following two lines of code are executed in a bash script, "ls" complains that the files don't exist:</p>
<pre><code>dirs=/content/{dev01,dev02}
ls -l $dirs
</code></pre>
<p>When I run the script with the -x option, it appears to be passing the variable within single quotes (which would prevent globbing):</p>
<pre><code>+ dirs=/content/{dev01,dev01}
+ ls -l '/content/{dev01,dev01}'
ls: /content/{dev01,dev01}: No such file or directory
</code></pre>
<p>If I execute the "ls" command from my interactive shell (sans quotes), it returns the two directories.</p>
<p>I've been reading through the Bash Reference Manual (v 3.2) and can't see any reason for filename globbing to not take place (I'm not passing -f to the shell), or anything that I can set to ensure that globbing happens.</p>
| [
{
"answer_id": 369165,
"author": "Zsolt Botykai",
"author_id": 11621,
"author_profile": "https://Stackoverflow.com/users/11621",
"pm_score": -1,
"selected": false,
"text": "ls `echo $dirs` \n"
},
{
"answer_id": 369181,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 6,
"selected": true,
"text": "brace\n expansion variable pathname expansion eval ls $dirs\n f{m,k}t*; some_command eval /content/dev01 /content/dev02 * dirs=/content/{dev01,dev02}*\n"
},
{
"answer_id": 369199,
"author": "feoh",
"author_id": 32514,
"author_profile": "https://Stackoverflow.com/users/32514",
"pm_score": 5,
"selected": false,
"text": "dirs=(/content/{dev01,dev01})\n"
},
{
"answer_id": 369227,
"author": "Yoni Roit",
"author_id": 34161,
"author_profile": "https://Stackoverflow.com/users/34161",
"pm_score": 3,
"selected": false,
"text": "#!/bin/sh\ndirs=`echo ./{dev01,dev02}`\nls $dirs\n"
},
{
"answer_id": 35867580,
"author": "Peter",
"author_id": 6034275,
"author_profile": "https://Stackoverflow.com/users/6034275",
"pm_score": 2,
"selected": false,
"text": "dirs=( /\"content with spaces\"/{dev01,dev02} )\n\ndirs=( /content/{dev01,dev02} )\nls -l \"${dirs[@]}\"\n /content/{dev01,dev02}\n \"/content/dev01\" \"/content/dev02\"\n dirs=/content/{dev01,dev02}\n \"/content/dev01\"\n \"/content/dev01 /content/dev02\"\n \"/content/dev01\" \"/content/dev02\"\n \"/content/{dev01,dev02}\"\n"
},
{
"answer_id": 35868472,
"author": "gniourf_gniourf",
"author_id": 1815797,
"author_profile": "https://Stackoverflow.com/users/1815797",
"pm_score": 2,
"selected": false,
"text": "shopt -s extglob # likely already set in interactive shells\n\ndirs=/content/@(dev01|dev02)\nls $dirs\n"
},
{
"answer_id": 37416061,
"author": "cxw",
"author_id": 2877364,
"author_profile": "https://Stackoverflow.com/users/2877364",
"pm_score": 4,
"selected": false,
"text": "list_of_results=(pattern)\n pattern list_of_results list_of_results \"${list_of_results[<index>]}\" <index> \"${list_of_results[@]}\""
},
{
"answer_id": 53188148,
"author": "Sam Liddicott",
"author_id": 2332068,
"author_profile": "https://Stackoverflow.com/users/2332068",
"pm_score": 0,
"selected": false,
"text": "dirs=/content/{dev01,dev02}\n echo /content/{dev01,dev02}\n dirs"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42126/"
] |
369,147 | <p>I have a paragraph of text in a javascript variable called 'input_content' and that text contains multiple anchor tags/links. I would like to match all of the anchor tags and extract anchor text and URL, and put it into an array like (or similar to) this:</p>
<pre>Array
(
[0] => Array
(
[0] => <a href="http://yahoo.com">Yahoo</a>
[1] => http://yahoo.com
[2] => Yahoo
)
[1] => Array
(
[0] => <a href="http://google.com">Google</a>
[1] => http://google.com
[2] => Google
)
)</pre>
<p>I've taken a crack at it (<a href="http://pastie.org/339755" rel="noreferrer"><a href="http://pastie.org/339755" rel="noreferrer">http://pastie.org/339755</a></a>), but I am stumped beyond this point. Thanks for the help!</p>
| [
{
"answer_id": 369174,
"author": "Ates Goral",
"author_id": 23501,
"author_profile": "https://Stackoverflow.com/users/23501",
"pm_score": 7,
"selected": true,
"text": "var matches = [];\n\ninput_content.replace(/[^<]*(<a href=\"([^\"]+)\">([^<]+)<\\/a>)/g, function () {\n matches.push(Array.prototype.slice.call(arguments, 1, 4))\n});\n <a href=\"...\">...</a> target matches arguments split Array.prototype.slice.call(arguments, 1, 4)\n arguments var input_content = \"blah \\\n <a href=\\\"http://yahoo.com\\\">Yahoo</a> \\\n blah \\\n <a href=\\\"http://google.com\\\">Google</a> \\\n blah\";\n\nvar matches = [];\n\ninput_content.replace(/[^<]*(<a href=\"([^\"]+)\">([^<]+)<\\/a>)/g, function () {\n matches.push(Array.prototype.slice.call(arguments, 1, 4));\n});\n\nalert(matches.join(\"\\n\"));\n"
},
{
"answer_id": 369190,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 3,
"selected": false,
"text": ".getElementsByTagName() .getElementsByTagName()"
},
{
"answer_id": 369216,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<script type=\"text/javascript\">\n // From http://brandonaaron.net Thanks!\n jQuery.fn.outerHTML = function() {\n return $('<div>').append( this.eq(0).clone() ).html();\n }; \n\n var items = new Array();\n var i = 0;\n\n $(document).ready(function(){\n $(\"a\").each(function(){\n items[i] = {el:$(this).outerHTML(),href:this.href,text:this.text};\n i++; \n });\n });\n\n function showItems(){\n alert(items);\n }\n\n</script>\n"
},
{
"answer_id": 369231,
"author": "Ben Blank",
"author_id": 46387,
"author_profile": "https://Stackoverflow.com/users/46387",
"pm_score": 3,
"selected": false,
"text": "function getLinks(html) {\n var container = document.createElement(\"p\");\n container.innerHTML = html;\n\n var anchors = container.getElementsByTagName(\"a\");\n var list = [];\n\n for (var i = 0; i < anchors.length; i++) {\n var href = anchors[i].href;\n var text = anchors[i].textContent;\n\n if (text === undefined) text = anchors[i].innerText;\n\n list.push(['<a href=\"' + href + '\">' + text + '</a>', href, text];\n }\n\n return list;\n}\n"
},
{
"answer_id": 38372053,
"author": "JsAndDotNet",
"author_id": 852806,
"author_profile": "https://Stackoverflow.com/users/852806",
"pm_score": 2,
"selected": false,
"text": "var text = 'This is my <a target=\"_blank\" href=\"www.google.co.uk\">link</a> Text';\nvar urlPattern = /([^+>]*)[^<]*(<a [^>]*(href=\"([^>^\\\"]*)\")[^>]*>)([^<]+)(<\\/a>)/gi;\nvar output = text.replace(urlPattern, \"$1___$2___$3___$4___$5___$6\");\nalert(output);\n var returnText = text.replace(urlPattern, function(fullText, beforeLink, anchorContent, href, lnkUrl, linkText, endAnchor){\n return \"The bits you want e.g. linkText\";\n });\n"
},
{
"answer_id": 39430872,
"author": "JohnP2",
"author_id": 1691651,
"author_profile": "https://Stackoverflow.com/users/1691651",
"pm_score": 2,
"selected": false,
"text": "//var string = '<a id=\"btn\" target=\"_blank\" class=\"button\" href=\"https://yourdomainame.com:4089?param=751&2ndparam=2345\">Buy Now</a>;'\n//uncomment the above as an example of link.outerHTML\n\nvar string = link.outerHTML\nvar pattern = /.*href=\"(.*)\".*/;\nvar href = string.replace(pattern,'$1');\nalert(href)\n link.innerHtml"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/74552/"
] |
369,150 | <p>I know with python and a couple other languages there is a way to safely make install a newer generational version of a language onto a machine, but after digging through PHP5's configure & makefile the only thing I've seen is the prefix dir option and the ini scan path.</p>
<p>Ideally I'd like php5 to have its own lib/bin subdirectories in /usr/local and then I can just put php5 after php4 in the path or make a symbolic link from the php5 binaries to php5-cli, php5-cgi, etc. </p>
<p>Also, am I missing anything dramatically bad here, the server in question is a legacy application server that's still somewhat busy and is due to be deprecated by June of 2009 but in the meantime the plan is to start updating parts with php5 code.</p>
<p>Machine states:
CENTOS 5
PHP 4 was built from a source RPM outside of yum's control</p>
<p>Most of php4 is in ambiguous directories:
/usr/{include,lib}/php </p>
| [
{
"answer_id": 369310,
"author": "Bob Fanger",
"author_id": 19165,
"author_profile": "https://Stackoverflow.com/users/19165",
"pm_score": 1,
"selected": false,
"text": "configure --prefix=/usr/local/php5\nmake install-cli \n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9908/"
] |
369,151 | <p>Everytime i retrieve data from a mysql stored procedure with a concat function an error will occur after binding the datagridview to the datatable that holds the returned rows.</p>
| [
{
"answer_id": 369239,
"author": "maxnk",
"author_id": 45862,
"author_profile": "https://Stackoverflow.com/users/45862",
"pm_score": 1,
"selected": true,
"text": "select concat(column1, column2) as concatenated from table1\n"
},
{
"answer_id": 5732075,
"author": "CARLOS",
"author_id": 717343,
"author_profile": "https://Stackoverflow.com/users/717343",
"pm_score": 1,
"selected": false,
"text": "select CAST(concat(column1, column2)AS CHAR)"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26087/"
] |
369,177 | <p>When I try to connect to WMI from Powershell, ConfigMgr, or WMI explorer, I can talk to the majority of my computers, but some (maybe 30%?) return an 0x800706ba (RPC server is unavailable).</p>
<p>If I turn the firewall off on the remote machine, the queries start working. I have tried a bunch of different configurations of firewall settings, though, and I can't seem to figure out what the right combination of exceptions is.</p>
<p>Here's the relevant bits of my firewall config on the remote machine. The crazy part is that there are <strong>no drops</strong> listed in pfirewall.log when it doesn't work - but again, if I turn off the firewall on the remote computer, everything starts to behave.</p>
<p>I will babysit this thread since I know you'll probably need more details to diagnose this.</p>
<pre><code>Domain profile configuration (current):
-------------------------------------------------------------------
Operational mode = Enable
Exception mode = Enable
Multicast/broadcast response mode = Enable
Notification mode = Enable
Service configuration for Domain profile:
Mode Customized Name
-------------------------------------------------------------------
Enable No Remote Desktop
Allowed programs configuration for Domain profile:
Mode Name / Program
-------------------------------------------------------------------
Enable Remote Assistance / C:\WINDOWS\system32\sessmgr.exe
Enable Network Diagnostics for Windows XP / C:\WINDOWS\Network Diagnostic\xpnetdiag.exe
Port configuration for Domain profile:
Port Protocol Mode Name
-------------------------------------------------------------------
3389 TCP Enable Remote Desktop
Standard profile configuration:
-------------------------------------------------------------------
Operational mode = Enable
Exception mode = Enable
Multicast/broadcast response mode = Enable
Notification mode = Enable
Service configuration for Standard profile:
Mode Customized Name
-------------------------------------------------------------------
Enable No Remote Desktop
Allowed programs configuration for Standard profile:
Mode Name / Program
-------------------------------------------------------------------
Enable Remote Assistance / C:\WINDOWS\system32\sessmgr.exe
Enable McAfee Framework Service / C:\Program Files\McAfee\Common Framework\FrameworkService.exe
Enable Network Diagnostics for Windows XP / C:\WINDOWS\Network Diagnostic\xpnetdiag.exe
Port configuration for Standard profile:
Port Protocol Mode Name
-------------------------------------------------------------------
3389 TCP Enable Remote Desktop
Log configuration:
-------------------------------------------------------------------
File location = C:\WINDOWS\pfirewall.log
Max file size = 4096 KB
Dropped packets = Disable
Connections = Disable
Bluetooth Network Connection firewall configuration:
-------------------------------------------------------------------
Operational mode = Enable
Local Area Connection firewall configuration:
-------------------------------------------------------------------
Operational mode = Enable
Wireless Network Connection firewall configuration:
-------------------------------------------------------------------
Operational mode = Enable
1394 Connection firewall configuration:
-------------------------------------------------------------------
Operational mode = Enable
</code></pre>
| [
{
"answer_id": 369239,
"author": "maxnk",
"author_id": 45862,
"author_profile": "https://Stackoverflow.com/users/45862",
"pm_score": 1,
"selected": true,
"text": "select concat(column1, column2) as concatenated from table1\n"
},
{
"answer_id": 5732075,
"author": "CARLOS",
"author_id": 717343,
"author_profile": "https://Stackoverflow.com/users/717343",
"pm_score": 1,
"selected": false,
"text": "select CAST(concat(column1, column2)AS CHAR)"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44831/"
] |
369,187 | <p><strong>Please note the Edit below for a lot more information, and a possible solution</strong></p>
<p>We recently modified a large Delphi application to use ADO connections and queries instead of BDE connections and queries. Since that change, performance has become terrible.</p>
<p>I've profiled the application and the bottleneck seems to be at the actual call to <code>TADOQuery.Open</code>. In other words, there isn't much I can do from a code standpoint to improve this, other than restructuring the application to actually use the database less.</p>
<p>Does anyone have suggestions about how to improve the performance of an ADO-connected Delphi application? I've tried both of the <a href="http://dn.codegear.com/print/27790" rel="noreferrer">suggestions given here</a>, with virtually no impact.</p>
<p>To give an idea of the performance difference, I benchmarked the same large operation:</p>
<ul>
<li><p>Under BDE: 11 seconds</p></li>
<li><p>Under ADO: 73 seconds</p></li>
<li><p>Under ADO after the changes referenced by that article: 72 seconds</p></li>
</ul>
<p>We are using an Oracle back-end in a client-server environment. Local machines each maintain a separate connection to the database.</p>
<p>For the record, the connection string looks like this:</p>
<pre><code>const
c_ADOConnString = 'Provider=OraOLEDB.Oracle.1;Persist Security Info=True;' +
'Extended Properties="plsqlrset=1";' +
'Data Source=DATABASE.DOMAIN.COM;OPTION=35;' +
'User ID=******;Password=*******';
</code></pre>
<p>To answer the questions posed by zendar:</p>
<p>I'm using Delphi 2007 on Windows Vista and XP.</p>
<p>The back end is an Oracle 10g database.</p>
<p>As indicated by the connection string, we are using the OraOLEDB driver.</p>
<p>The MDAC version on my benchmark machine is 6.0.</p>
<p><strong>Edit:</strong></p>
<p>Under the BDE, we had a lot of code that looked like this:</p>
<pre><code>procedure MyBDEProc;
var
qry: TQuery;
begin
//fast under BDE, but slow under ADO!!
qry := TQuery.Create(Self);
try
with qry do begin
Database := g_Database;
Sql.Clear;
Sql.Add('SELECT');
Sql.Add(' FIELD1');
Sql.Add(' ,FIELD2');
Sql.Add(' ,FIELD3');
Sql.Add('FROM');
Sql.Add(' TABLE1');
Sql.Add('WHERE SOME_FIELD = SOME_CONDITION');
Open;
//do something
Close;
end; //with
finally
FreeAndNil(qry);
end; //try-finally
end; //proc
</code></pre>
<p>But we found that the call to <code>Sql.Add</code> is actually very expensive under ADO, because the <code>QueryChanged</code> event is fired every time you change the <code>CommandText</code>. So replacing the above with this was MUCH faster:</p>
<pre><code>procedure MyADOProc;
var
qry: TADOQuery;
begin
//fast(er) under ADO
qry := TADOQuery.Create(Self);
try
with qry do begin
Connection := g_Connection;
Sql.Text := ' SELECT ';
+ ' FIELD1 '
+ ' ,FIELD2 '
+ ' ,FIELD3 '
+ ' FROM '
+ ' TABLE1 '
+ ' WHERE SOME_FIELD = SOME_CONDITION ';
Open;
//do something
Close;
end; //with
finally
FreeAndNil(qry);
end; //try-finally
end; //proc
</code></pre>
<p>Better yet, you can copy <code>TADOQuery</code> out of ADODB.pas, rename it under a new name, and rip out the <code>QueryChanged</code> event, which as far as I can tell, is not doing anything useful at all. Then use your new, modified version of TADOQuery, instead of the native one.</p>
<pre><code>type
TADOQueryTurbo = class(TCustomADODataSet)
private
//
protected
procedure QueryChanged(Sender: TObject);
public
FSQL: TWideStrings;
FRowsAffected: Integer;
function GetSQL: TWideStrings;
procedure SetSQL(const Value: TWideStrings);
procedure Open;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function ExecSQL: Integer; {for TQuery compatibility}
property RowsAffected: Integer read FRowsAffected;
published
property CommandTimeout;
property DataSource;
property EnableBCD;
property ParamCheck;
property Parameters;
property Prepared;
property SQL: TWideStrings read FSQL write SetSQL;
end;
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
constructor TADOQueryTurbo.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FSQL := TWideStringList.Create;
TWideStringList(FSQL).OnChange := QueryChanged;
Command.CommandText := 'SQL'; { Do not localize }
end;
destructor TADOQueryTurbo.Destroy;
begin
inherited;
inherited Destroy;
FreeAndNil(FSQL);
end;
function TADOQueryTurbo.ExecSQL: Integer;
begin
CommandText := FSQL.Text;
inherited;
end;
function TADOQueryTurbo.GetSQL: TWideStrings;
begin
Result := FSQL;
end;
procedure TADOQueryTurbo.Open;
begin
CommandText := FSQL.Text;
inherited Open;
end;
procedure TADOQueryTurbo.QueryChanged(Sender: TObject);
begin
// if not (csLoading in ComponentState) then
// Close;
// CommandText := FSQL.Text;
end;
procedure TADOQueryTurbo.SetSQL(const Value: TWideStrings);
begin
FSQL.Assign(Value);
CommandText := FSQL.Text;
end;
</code></pre>
| [
{
"answer_id": 6646406,
"author": "Arnaud Bouchez",
"author_id": 458259,
"author_profile": "https://Stackoverflow.com/users/458259",
"pm_score": 0,
"selected": false,
"text": " Q := TQuery.Create(aSQLDBConnection);\n try\n Q.SQL.Clear; // optional\n Q.SQL.Add('select * from DOMAIN.TABLE');\n Q.SQL.Add(' WHERE ID_DETAIL=:detail;');\n Q.ParamByName('DETAIL').AsString := '123420020100000430015';\n Q.Open;\n Q.First; // optional\n while not Q.Eof do begin\n assert(Q.FieldByName('id_detail').AsString='123420020100000430015');\n Q.Next;\n end;\n Q.Close; // optional\n finally\n Q.Free;\n end;\n procedure Test(Props: TOleDBConnectionProperties; const aName: RawUTF8);\nvar I: ISQLDBRows;\n Customer: Variant;\nbegin\n I := Props.Execute('select * from Domain.Customers where Name=?',[aName],@Customer);\n while I.Step do\n writeln(Customer.Name,' ',Customer.FirstName,' ',Customer.Address);\nend;\n\nvar Props: TOleDBConnectionProperties;\nbegin\n Props := TSQLDBOracleConnectionProperties.Create(\n 'TnsName','UserName','Password',CODEPAGE_US);\n try\n Test(Props,'Smith');\n finally\n Props.Free;\n end;\nend;\n"
},
{
"answer_id": 6718130,
"author": "Ian Boyd",
"author_id": 12597,
"author_profile": "https://Stackoverflow.com/users/12597",
"pm_score": 3,
"selected": false,
"text": ".DisableControls TADOQuery Open Query.DisableControls .Next Query.Recordset.Fields.Items['columnName'].Value Query.FieldByName('columnName') TADODataSet TADOQuery Loop Results Get Values \nADOExpress: 28.0s 46.6s \nADOExpress w/DisableControls: 0.5s 17.0s \nADO (direct use of interfaces): 0.2s 4.7s \n var\n qry: TADOQuery;\nbegin\n qry := TADOQuery.Create(nil);\n try\n qry.SQL.Add(CommandText);\n qry.Open;\n while not qry.EOF do\n begin\n ...\n qry.Next;\n end;\n var\n qry: TADOQuery;\nbegin\n qry := TADOQuery.Create(nil);\n try \n qry.DisableControls;\n qry.SQL.Add(CommandText);\n qry.Open;\n while not qry.EOF do\n begin\n ...\n qry.Next;\n end;\n var\n qry: TADOQuery;\nbegin\n qry := TADOQuery.Create(nil);\n try \n qry.DisableControls;\n qry.SQL.Add(CommandText);\n qry.Open;\n while not qry.EOF do\n begin\n value1 := VarAsString(qry.Recordset.Fields['FieldOne'].Value);\n value2 := VarAsInt(qry.Recordset.Fields['FieldTwo'].Value);\n value3 := VarAsInt64(qry.Recordset.Fields['FieldTwo'].Value);\n value4 := VarAsFloat(qry.Recordset.Fields['FieldThree'].Value);\n value5 := VarAsWideString(qry.Recordset.Fields['FieldFour'].Value);\n ...\n value56 := VarAsMoney(qry.Recordset.Fields['FieldFive'].Value);\n qry.Next;\n end;\n class function TADOHelper.Execute(const Connection: TADOConnection; \n const CommandText: WideString): TADOQuery;\nvar\n rs: _Recordset;\n query: TADOQuery;\n nRecords: OleVariant;\nbegin\n Query := TADOQuery.Create(nil);\n Query.DisableControls; //speeds up Query.Next by a magnitude\n Query.Connection := Connection;\n Query.SQL.Text := CommandText;\n try\n Query.Open();\n except\n on E:Exception do\n begin\n Query.Free;\n raise;\n end;\n end;\n Result := Query;\nend;\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/672/"
] |
369,198 | <p>I have the following problem. If I query values with a keyfigure which is a function I can't specify multiple values of the same dimension restriction, but if it is not a function it works.</p>
<p>So this works:</p>
<pre><code>SELECT {[Measures].[Netto]} on columns FROM TDC where
({NonEmpty([Time].[Month].[Month].&[2008-03-01T00:00:00]),
NonEmpty([Time].[Month].[Month].&[2008-04-01T00:00:00])})
</code></pre>
<p>But this doesn't:</p>
<pre><code>SELECT {[Measures].[CalculatedFunction]} on columns FROM TDC where
({NonEmpty([Time].[Month].[Month].&[2008-03-01T00:00:00]),
NonEmpty([Time].[Month].[Month].&[2008-04-01T00:00:00])})
</code></pre>
<p>And this also works:</p>
<pre><code>SELECT {[Measures].[CalculatedFunction]} on columns FROM TDC where
({NonEmpty([Time].[Month].[Month].&[2008-03-01T00:00:00])})
</code></pre>
<p>I guess the solution is something like adding the where clause to the header but I really like this solution because it's so simple.</p>
<p>The Calucated function is:</p>
<pre><code>CREATE MEMBER CURRENTCUBE.[MEASURES].Ultimo
AS (iif ((not [Time].[Year - Month - Date].currentmember is [Time].[Year - Month - Date].defaultmember),
IIF(NOT ([Measures].[LagerStk] = 0),
Sum([Time].[Year - Month - Date].[Date].members(0):
ClosingPeriod([Time].[Year - Month - Date].[Date]),
[Measures].[LagerStk]), NULL)
,
IIF(NOT ([Measures].[LagerStk] = 0),
Sum([Time].[Year - Week - Date].[Date].members(0):
ClosingPeriod([Time].[Year - Week - Date].[Date]),
[Measures].[LagerStk]), NULL))),
VISIBLE = 1;
</code></pre>
<p>The code is inspired from this and modified for two hierarchies in the time dimension: <a href="http://www.sqlserveranalysisservices.com/OLAPPapers/InventoryManagement%20in%20AS2005v2.htm" rel="nofollow noreferrer">http://www.sqlserveranalysisservices.com/OLAPPapers/InventoryManagement%20in%20AS2005v2.htm</a></p>
<p>This is on SQL server 2005 Enterprise edition.</p>
| [
{
"answer_id": 371866,
"author": "Anders Rune Jensen",
"author_id": 13995,
"author_profile": "https://Stackoverflow.com/users/13995",
"pm_score": 2,
"selected": true,
"text": "WITH MEMBER [Time].[Month].a AGGREGATE \n({[Time].[Month].[Month].&[2008-03-01T00:00:00], \n [Time].[Month].[Month].&[2008-04-01T00:00:00]})\nSELECT {[Measures].[CalculatedFunction]} on columns FROM TDC where a\n"
},
{
"answer_id": 510006,
"author": "Darren Gosbell",
"author_id": 11860,
"author_profile": "https://Stackoverflow.com/users/11860",
"pm_score": 0,
"selected": false,
"text": "CREATE \n MEMBER CURRENTCUBE.[MEASURES].Ultimo AS NULL;\n\nSCOPE ([MEASURES].Ultimo);\n SCOPE ([Time].[Year - Month - Date].[All]);\n this = IIF\n (\n (NOT \n [Measures].[LagerStk] = 0)\n ,Sum\n (\n NULL:Tail(Existing [Time].[Year - Week - Date].[Date],1).item(0).item(0)\n ,[Measures].[LagerStk]\n )\n ,NULL\n );\n END SCOPE;\n\n SCOPE ([Time].[Year - Week - Date].[All]);\n this = IIF\n (\n (NOT \n [Measures].[LagerStk] = 0)\n ,Sum\n (\n NULL:Tail(Existing [Time].[Year - Month - Date].[Date],1).Item(0).Item(0)\n ,[Measures].[LagerStk]\n )\n ,NULL\n )\n ); \n END SCOPE;\nEND SCOPE;\n SCOPE ([Time].[Year - Week - Date].[All]);\n this = Sum\n (\n NULL:Tail(Existing [Time].[Year - Month - Date].[Date],1).Item(0).Item(0)\n ,[Measures].[LagerStk]\n ); \n END SCOPE;\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13995/"
] |
369,209 | <p>I'm writing a programmer's text editor (yes another one) in Perl called <a href="http://kephra.sourceforge.net/" rel="nofollow noreferrer">Kephra</a>, which is also a CPAN module of course and bundled with <a href="http://cpanratings.perl.org/dist/Module-Install" rel="nofollow noreferrer">Module::Install</a>. Recently I saw that <a href="http://cpanratings.perl.org/dist/Module-Build" rel="nofollow noreferrer">Module::Build</a> has gone into core, so if I switch I could reduce dependencies. Is there any other reason to switch?</p>
| [
{
"answer_id": 369229,
"author": "mat",
"author_id": 42083,
"author_profile": "https://Stackoverflow.com/users/42083",
"pm_score": 3,
"selected": false,
"text": "Module::Build ExtUtils::MakeMaker Module::Install Module::Build Module::Install"
},
{
"answer_id": 561392,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 3,
"selected": false,
"text": "make perl Makemaker.PL; make; make install Build.PL"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29269/"
] |
369,211 | <p>I've got a node struct</p>
<pre><code>struct Node{CString text, int id;};
</code></pre>
<p>in a sorted vector. </p>
<p>I'm wondering if there's a function in algorithm that will do a binary search of the vector and find an element. </p>
| [
{
"answer_id": 369276,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 5,
"selected": true,
"text": "std::binary_search() std::lower_bound()/std::upper_bound() operator<"
},
{
"answer_id": 20390430,
"author": "razeh",
"author_id": 139781,
"author_profile": "https://Stackoverflow.com/users/139781",
"pm_score": 0,
"selected": false,
"text": "std::equal_range std::equal_range std::pair struct Node #include <iostream>\n#include <algorithm>\n#include <vector>\n#include <string>\n\nint main(int argc, const char * argv[])\n{\n std::vector<int> sorted = { 1, 2, 2, 5, 10 };\n\n auto range = std::equal_range(sorted.begin(), sorted.end(), 20);\n // Outputs \"5 5\"\n std::cout << std::distance(sorted.begin(), range.first) << ' '\n << std::distance(sorted.begin(), range.second) << '\\n';\n\n range = std::equal_range(sorted.begin(), sorted.end(), 5);\n // Outputs \"3 4\"\n std::cout << std::distance(sorted.begin(), range.first) << ' '\n << std::distance(sorted.begin(), range.second) << '\\n';\n\n range = std::equal_range(sorted.begin(), sorted.end(), -1);\n // Outputs \"0 0\"\n std::cout << std::distance(sorted.begin(), range.first) << ' '\n << std::distance(sorted.begin(), range.second) << '\\n';\n\n return 0;\n}\n struct Node operator < struct Node std::equal_range std::equal_range std::vector<Node> nodes = { Node{\"hello\", 5}, Node{\"goodbye\", 6} };\nNode searchForMe { \"goodbye\", 6 };\nauto range = std::equal_range(nodes.begin(), nodes.end(), searchForMe,\n [](Node lhs, Node rhs) { return lhs.id < rhs.id; });\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31325/"
] |
369,213 | <p>I am writing a addressbook module for my software right now. I have the database set up so far that it supports a very flexible address-book configuration.</p>
<p>I can create n-entries for every type I want. Type means here data like 'email', 'address', 'telephone' etc.</p>
<p>I have a table named 'contact_profiles'.</p>
<p>This only has two columns:</p>
<pre><code>id Primary key
date_created DATETIME
</code></pre>
<p>And then there is a table called contact_attributes. This one is a little more complex:</p>
<pre><code>id PK
#profile (Foreign key to contact_profiles.id)
type VARCHAR describing the type of the entry (name, email, phone, fax, website, ...) I should probably change this to a SET later.
value Text (containing the value for the attribute).
</code></pre>
<p>I can now link to these profiles, for example from my user's table. But from here I run into problems.</p>
<p>At the moment I would have to create a JOIN for each value that I want to retrieve.
Is there a possibility to somehow create a View, that gives me a result with the type's as columns?</p>
<p>So right now I would get something like</p>
<pre><code>#profile type value
1 email name@domain.tld
1 name Sebastian Hoitz
1 website domain.tld
</code></pre>
<p>But it would be nice to get a result like this:</p>
<pre><code>#profile email name website
1 name@domain.tld Sebastian Hoitz domain.tld
</code></pre>
<p>The reason I do not want to create the table layout like this initially is, that there might always be things to add and I want to be able to have multiple attributes of the same type.</p>
<p>So do you know if there is any possibility to convert this dynamically?</p>
<p>If you need a better description please let me know.</p>
| [
{
"answer_id": 369253,
"author": "Michael Haren",
"author_id": 29,
"author_profile": "https://Stackoverflow.com/users/29",
"pm_score": 1,
"selected": false,
"text": "SELECT cp.ID profile\n ,cp.Name\n ,(SELECT value FROM contact_attributes WHERE type = 'email' and profile = cp.id) email\n ,(SELECT value FROM contact_attributes WHERE type = 'website' and profile = cp.id) website\n ,(SELECT value FROM contact_attributes WHERE type = 'phone' and profile = cp.id) phone\nFROM contact_profiles cp\n contact_attribute_types contact_attribute_types.id contact_attributes"
},
{
"answer_id": 369262,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 0,
"selected": false,
"text": "select #profile,\n max(case when type='email' then value end) as email,\n max(case when type='name' then value end) as name,\n max(case when type='website' then value end) as website\nfrom mytable\ngroup by #profile\n"
},
{
"answer_id": 369267,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 3,
"selected": true,
"text": "SELECT c.id, c.date_created,\n c1.value AS name,\n c2.value AS email,\n c3.value AS phone,\n c4.value AS fax,\n c5.value AS website\nFROM contact_profiles c\n LEFT OUTER JOIN contact_attributes c1\n ON (c.id = c1.profile AND c1.type = 'name')\n LEFT OUTER JOIN contact_attributes c1\n ON (c.id = c1.profile AND c1.type = 'email')\n LEFT OUTER JOIN contact_attributes c1\n ON (c.id = c1.profile AND c1.type = 'phone')\n LEFT OUTER JOIN contact_attributes c1\n ON (c.id = c1.profile AND c1.type = 'fax')\n LEFT OUTER JOIN contact_attributes c1\n ON (c.id = c1.profile AND c1.type = 'website');\n LEFT OUTER JOIN LEFT OUTER JOIN INNER JOIN NOT NULL n SELECT * FROM contact_profiles c\n LEFT OUTER JOIN contact_attributes ca ON (c.id = ca.profile);\n TEXT"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9535/"
] |
369,220 | <p>I entered this statement in JSLint:</p>
<pre><code>var number = new Number(3);
</code></pre>
<p>And received the following message:</p>
<blockquote>
<p>Do not use Number as a constructor.</p>
</blockquote>
<p>Why is that? The statement is creating a number object, not a primitive value, so I don't see why using <code>new</code> is a problem.</p>
<p><strong>EDIT:</strong> Thanks for all the responses. They've got me thinking further, so I posted a follow-up question <a href="https://stackoverflow.com/questions/369424/question-about-objectmethod-in-javascript">here</a>.</p>
| [
{
"answer_id": 369257,
"author": "Ates Goral",
"author_id": 23501,
"author_profile": "https://Stackoverflow.com/users/23501",
"pm_score": 4,
"selected": false,
"text": "var number = new Number(3);\nalert(typeof number); // gives \"object\"\n number Object var number = Number(3);\nalert(typeof number); // gives \"number\"\n"
},
{
"answer_id": 369258,
"author": "Ben Blank",
"author_id": 46387,
"author_profile": "https://Stackoverflow.com/users/46387",
"pm_score": 3,
"selected": false,
"text": "assert(typeof 3 === \"number\");\nassert(typeof new Number(3) === \"object\");\n if (typeof foo === \"number\" || foo instanceof Number) { … }\n assert(typeof [] === \"object\");\nassert(typeof new Array() === \"object\");\nassert(typeof {} === \"object\");\nassert(typeof new Object() === \"object\");\n assert(3 !== new Number(3));\n"
},
{
"answer_id": 369275,
"author": "Steven Huwig",
"author_id": 28604,
"author_profile": "https://Stackoverflow.com/users/28604",
"pm_score": 3,
"selected": false,
"text": ">>> 3 == 1 + 2\ntrue\n>>> 3 === 1 + 2\ntrue\n>>> new Number(3) == 1 + 2\ntrue\n>>> new Number(3) === 1 + 2\nfalse\n"
},
{
"answer_id": 369450,
"author": "Matthew Crumley",
"author_id": 2214,
"author_profile": "https://Stackoverflow.com/users/2214",
"pm_score": 5,
"selected": false,
"text": "var n1 = 0;\nvar n2 = new Number(0);\n\nn1 == n2 // true\nn1 === n2 // false\nif (n1) {\n // Doesn't execute\n}\nif (n2) {\n // Does execute, because n2 is an object that is not null\n}\n var n1 = new Number(3);\nvar n2 = new Number(3);\n\nalert(n1 == n2); // false\nalert(n1 === n2); // false\n"
},
{
"answer_id": 369484,
"author": "pottedmeat",
"author_id": 2120,
"author_profile": "https://Stackoverflow.com/users/2120",
"pm_score": 3,
"selected": false,
"text": "3 Number"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369220",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
369,230 | <p>I am using Django and the Google Web Toolkit (GWT) for my current project. I would like to pass a ModelForm instance to GWT via an Http response so that I can "chop" it up and render it as I please. My goal is to keep the form in sync with changes to my models.py file, yet increase control I have over the look of the form. However, the django classes for serialization, serializers and simplejson, cannot serialize a ModelForm. Neither can cPickle. What are my alternatives? </p>
| [
{
"answer_id": 372985,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "{% for field in form.fields %}\n <div class=\"form-field\">{{ field }}</div>\n{% endfor %}\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44440/"
] |
369,242 | <p>In my code segment, when I script the file name, it gives me a permission denied
on the following line: </p>
<pre><code>Set objTextFile = objFSO.OpenTextFile(strDirectory & strFile, ForAppending, True)
</code></pre>
<p>Here is the script </p>
<pre><code>'output log info
Function OutputToLog (strToAdd)
Dim strDirectory,strFile,strText, objFile,objFolder,objTextFile,objFSO
strDirectory = "c:\eNet"
strFile = "\weeklydel.bat"
'strText = "Book Another Holiday"
strText = strToAdd
' Create the File System Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
' Check that the strDirectory folder exists
If objFSO.FolderExists(strDirectory) Then
Set objFolder = objFSO.GetFolder(strDirectory)
Else
Set objFolder = objFSO.CreateFolder(strDirectory)
'WScript.Echo "Just created " & strDirectory
End If
If objFSO.FileExists(strDirectory & strFile) Then
Set objFolder = objFSO.GetFolder(strDirectory)
Else
Set objFile = objFSO.CreateTextFile(strDirectory & strFile)
'Wscript.Echo "Just created " & strDirectory & strFile
End If
set objFile = nothing
set objFolder = nothing
' OpenTextFile Method needs a Const value
' ForAppending = 8 ForReading = 1, ForWriting = 2
Const ForAppending = 2
Set objTextFile = objFSO.OpenTextFile(strDirectory & strFile, ForAppending, True)
' Writes strText every time you run this VBScript
objTextFile.WriteLine(strText)
objTextFile.Close
End Function
</code></pre>
<p>I have assigned the vbscript domain administrator permissions. Any ideas? </p>
<p>thanks in advance</p>
| [
{
"answer_id": 369287,
"author": "BenAlabaster",
"author_id": 40650,
"author_profile": "https://Stackoverflow.com/users/40650",
"pm_score": 5,
"selected": true,
"text": "Set objFile = objFSO.CreateTextFile(strDirectory & strFile)\n ...\n'Missing objFile.Close here\nSet objFile = nothing\nSet objFolder = nothing\n...\n"
},
{
"answer_id": 1826162,
"author": "Chris",
"author_id": 209576,
"author_profile": "https://Stackoverflow.com/users/209576",
"pm_score": 2,
"selected": false,
"text": "Set LogFile = LogFSO.OpenTextFile(LogFileName, ForWriting, True)\n WshShell.AppActivate(ScreensToRemove(i))\nWshShell.SendKeys (\"~\")\nWScript.Sleep(1000)\n If WshShell.AppActivate(ScreensToRemove(i)) = True Then\n WshShell.SendKeys (\"~\")\n WScript.Sleep(1000)\nEnd if\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18853/"
] |
369,246 | <p><strong>Background</strong></p>
<p>I have made a Web Service in Visual Studio, and I'm trying to consume it using the automatically generated proxy class. The Web Service returns a class that I have implemented, containing a List.</p>
<p><strong>Question</strong></p>
<p>The proxy class has automatically generated methods to send the SOAP to the web service. It uses the Invoke() method to execute the call, and then casts the result as a DataSet. How can I get this object back into the class I know it is?</p>
<p>I know that I can hand-edit the auto-generated file, but that's not very maintainable, so I don't want to go down that route (any time the Web Service is rebuilt, the changes would have to be made again).</p>
<p>Is there a way to tell the generated class to be more specific, and actually use the correct data type? Or do I have to write a clunky set of deserialisers to get my data back into the correct shape?</p>
<p><strong>Example</strong></p>
<p>One method in my Web Service class:</p>
<pre><code>[WebMethod]
public UpdateList RetrieveUpdates(long sessionID, string configurationVersion, string coreVersion, string researcherDBVersion)
{ ... }
</code></pre>
<p>Adding the class as a Web Reference generates the following proxy method:</p>
<pre><code>public DataSet RetrieveUpdates(long sessionID, string configurationVersion, string coreVersion, string researcherDBVersion) {
object[] results = this.Invoke("RetrieveUpdates", new object[] {
sessionID,
configurationVersion,
coreVersion,
researcherDBVersion});
return ((DataSet)(results[0]));
}
</code></pre>
<p>The DataSet I receive from this method is always empty (because you can't cast from my class to a DataSet).</p>
<p>Thanks in advance</p>
| [
{
"answer_id": 369308,
"author": "Andrew Hare",
"author_id": 34211,
"author_profile": "https://Stackoverflow.com/users/34211",
"pm_score": 0,
"selected": false,
"text": "UpdateList"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369246",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37481/"
] |
369,248 | <p>I have been reading the proper article in MSDN, <em><a href="http://msdn.microsoft.com/en-us/library/wd40t7ad.aspx" rel="noreferrer">Strong-Named Assemblies</a></em> and a related Stack Overflow question, <em><a href="https://stackoverflow.com/questions/308756">Checking an assembly for a strong name</a></em>.</p>
<ol>
<li>To which extent can a strong-named assembly be verified to avoid tampering?</li>
<li>Is it possible to use strong-naming to verify an assembly author?</li>
</ol>
<p>The first question arises after reading the CSharp411 article <em><a href="http://www.csharp411.com/net-assembly-faq-part-3-strong-names-and-signing/" rel="noreferrer">.NET Assembly FAQ – Part 3 – Strong Names and Signing</a></em>, which mentions this, among other problems of using strong names:</p>
<blockquote>
<p>"<strong><em>Cannot Stop Full Replacement.</strong> Strong names cannot prevent a hacker from removing the strong name signature, maliciously modifying your assembly, re-signing it with his own key, and then passing off his assembly as yours.</em>"</p>
</blockquote>
<p>The second question intends to find the differences between strong naming and other signing schemes like, say, <a href="http://www.iss.net/security_center/advice/Countermeasures/Authentication/Authenticode/default.htm" rel="noreferrer">Authenticode</a>. The same MSDN article mentioned early states:</p>
<blockquote>
<p>"<em>Note, however, that strong names in and of themselves do not imply a level of trust like that provided, for example, by a digital signature and supporting certificate.</em>"</p>
</blockquote>
<p>Am I trying to use strong-naming for much more than it was created for? Was strong-naming created just to avoid name clashes or a new kind of "GAC DLL Hell"?</p>
| [
{
"answer_id": 369477,
"author": "HTTP 410",
"author_id": 13118,
"author_profile": "https://Stackoverflow.com/users/13118",
"pm_score": 6,
"selected": true,
"text": "// Check that public key token matches what's expected.\nprivate static bool IsPublicTokenOkay_Check(byte [] tokenExpected)\n{\n // Retrieve token from current assembly\n byte [] tokenCurrent = Assembly.GetExecutingAssembly().GetName().GetPublicKeyToken();\n\n // Check that lengths match\n if (tokenExpected.Length == tokenCurrent.Length)\n {\n // Check that token contents match\n for (int i = 0; i < tokenCurrent.Length; i++)\n if (tokenExpected[i] != tokenCurrent[i]) \n return false;\n }\n else\n {\n return false;\n }\n return true;\n}\n // Check that this assembly has a strong name.\nprivate bool IsStrongNameValid_Check()\n{\n byte wasVerified = Convert.ToByte(false); \n byte forceVerification = Convert.ToByte(true);\n string assemblyName = AppDomain.CurrentDomain.BaseDirectory + \n AppDomain.CurrentDomain.FriendlyName; \n return NativeMethods.CheckSignature(assemblyName, \n forceVerification, \n ref wasVerified);\n}\n // P/Invoke to check various security settings\n// Using byte for arguments rather than bool, \n// because bool won't work on 64-bit Windows!\n[DllImport(\"mscoree.dll\", CharSet=CharSet.Unicode)]\nprivate static extern bool StrongNameSignatureVerificationEx(string wszFilePath, \n byte fForceVerification, \n ref byte pfWasVerified);\n\n// Private constructor because this type has no non-static members\nprivate NativeMethods()\n{\n}\n\npublic static bool CheckSignature(string assemblyName, \n byte forceVerification, \n ref byte wasVerified)\n{\n return StrongNameSignatureVerificationEx(assemblyName, \n forceVerification, \n ref wasVerified );\n}\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18552/"
] |
369,277 | <p>We've got a page in our asp.net web system that uses response.redirect to redirect the user directly to an excel file so it will download "automatically" without the user having to to a right click / save as.</p>
<p>This works great - except for files over about 100k in IE7. Other browsers just download the large file fine, and IE works fine under that threshold, but at somewhere about 200k, IE just starts handing out "page cannot be displayed" errors.</p>
<p>Obviously, we'd like the user to be able to download in IE as well - any ideas? Is there some kind of download size threshold thing I can override?</p>
| [
{
"answer_id": 369324,
"author": "EndangeredMassa",
"author_id": 106,
"author_profile": "https://Stackoverflow.com/users/106",
"pm_score": 2,
"selected": true,
"text": "Public Shared Sub SendFileToBrowser(ByRef response As HttpResponse, ByVal filepath As String, Optional ByVal filename As String = \"\", Optional ByVal contentType As String = \"\", Optional ByVal disposition As String = \"\", Optional ByVal contentLength As String = \"\")\n Dim ext As String = filepath.Substring(filepath.Length - 3, 3)\n\n If String.IsNullOrEmpty(contentType) Then\n If ext = \"pdf\" Then\n contentType = \"application/pdf\"\n Else\n contentType = \"application/file\"\n End If\n End If\n\n If String.IsNullOrEmpty(disposition) Then\n disposition = \"attachment\"\n End If\n\n If String.IsNullOrEmpty(filename) Then\n ''//Test for relative url path\n Dim fileparts As String() = filepath.Split(\"/\")\n If fileparts.Length > 1 Then\n filename = fileparts(fileparts.Length - 1)\n Else\n ''//Test for absolute file path\n Dim fileparts2 As String() = filepath.Split(\"\\\") ''//\" SO: Fix syntax highlighting\n If fileparts2.Length > 1 Then\n filename = fileparts2(fileparts2.Length - 1)\n Else\n ''//Just give it a temp name\n filename = \"temp.\" & ext\n End If\n End If\n End If\n\n response.Clear()\n\n response.AddHeader(\"content-disposition\", disposition & \";filename=\" & filename)\n If Not String.IsNullOrEmpty(contentLength) Then\n response.AddHeader(\"Content-Length\", contentLength)\n End If\n\n response.ContentType = contentType\n\n response.Cache.SetCacheability(HttpCacheability.Public) \n\n response.TransmitFile(filepath)\n response.End()\nEnd Sub\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19074/"
] |
369,288 | <p>I'm using interface builder's tag feature to access some UILabels I'm instantiating in a xib file. Since this a UITextViewCell I want to avoid superfluous method calls, but I want to do it right too. Thus when I do:</p>
<pre><code>UILabel *label = (UILabel *)[cell viewWithTag:1];
</code></pre>
<p>I'm wondering if I should wrap it up like so:</p>
<pre><code>if([[cell viewWithTag:1] isKindOfClass [UITableViewCell class]]) {
UILabel *label = (UILabel *)[cell viewWithTag:1];
}
</code></pre>
<p>Any discussion on this would be appreciated.</p>
<p>Thanks</p>
| [
{
"answer_id": 369988,
"author": "Ashley Clark",
"author_id": 4556,
"author_profile": "https://Stackoverflow.com/users/4556",
"pm_score": 3,
"selected": false,
"text": "enum viewWithTag:"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46436/"
] |
369,289 | <p>Why would IE 7 display HTTP Error "Bad request" 400 on the same page that Firefox loads without complaining?</p>
| [
{
"answer_id": 393424,
"author": "Piskvor left the building",
"author_id": 19746,
"author_profile": "https://Stackoverflow.com/users/19746",
"pm_score": 0,
"selected": false,
"text": "\\ /"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46440/"
] |
369,291 | <p>In a multi-server environment, users will be able to use a page to put, update or delete files on the servers. I was considering using a webservice (on each server) called by the IIS thread to do that work (with an aspx management page).</p>
<p>However, for obvious reasons, I don't really want anyone to be able to call that webservice (by POSTing a well-formed request from their machines).</p>
<p>I am wondering what would be the most effective (in terms of complexity, scalability) way to ensure that the access to the webservice is restricted to my page (token? Sending the current user's Principal? I don't have access to their password so sending the login/password couple is out of the question)</p>
| [
{
"answer_id": 369490,
"author": "Rex Morgan",
"author_id": 46429,
"author_profile": "https://Stackoverflow.com/users/46429",
"pm_score": 1,
"selected": true,
"text": "IPrinciple _currentUser = HttpContext.Current.User;\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5789/"
] |
369,297 | <p><strong><em>Skunk Works Project</em></strong>: A project carried out by one part of a company without the knowledge of the remainder of the company.</p>
<p>Looking for stories about any skunk works projects you've worked on or initiated:</p>
<ul>
<li>Was it successful? </li>
<li>Were you found out? </li>
<li>Were you punished or rewarded? </li>
<li>How did you fund it? </li>
<li>How did you staff it? </li>
<li>How long did it take to finish, compared to above-ground projects? </li>
<li>What was the cost, compared to above-ground projects? </li>
<li>Was it formally adopted?</li>
</ul>
| [
{
"answer_id": 369503,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "git svn clone svn st git status"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7903/"
] |
369,301 | <p>Anticipating the day when multi-touch interfaces become more pervasive, are there libraries in Java that can be used for developing touch applications? I'm looking for interfaces similar to MouseListener / MouseMotionListener / MouseWheelListener.</p>
| [
{
"answer_id": 369387,
"author": "James Van Huis",
"author_id": 31828,
"author_profile": "https://Stackoverflow.com/users/31828",
"pm_score": 3,
"selected": false,
"text": "sparshui.client.Client processEvent public void processEvent(int groupID, Event event) {\n\n if(event instanceof TouchEvent) {\n TouchEvent e = (TouchEvent)event;\n if(e.getState() == TouchState.BIRTH) {\n //do initial touch stuff\n } else if(e.getState() == TouchState.MOVE) {\n //do dragging stuff\n }\n }\n else if(event instanceof DragEvent) {\n DragEvent e = (DragEvent)event;\n //do DragEvent specific stuff\n } else if(event instanceof RotateEvent) {\n RotateEvent e = (RotateEvent)event;\n //do RotateEvent specific stuff\n } else if(event instanceof ZoomEvent) {\n ZoomEvent e = (ZoomEvent)event;\n //do ZoomEvent specific stuff\n }\n //several other gesture types....\n}\n new ServerConnection(\"localhost\", objectImplementingClientInterface);\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2197/"
] |
369,312 | <p>I'm currently working on desktop application which calls third party API. After authorizing against their "web service", a kind of user token is returned which should be stored locally (even if user closes application). </p>
<p>So I'm looking for solution to encrypt this token with user specific key. Does Windows (and .NET) provide some standard way for doing this? All I want is protect token from other users of same computer.</p>
<p>P.S. I can't store hash, as I need to decrypt this token at startup.</p>
| [
{
"answer_id": 369330,
"author": "mmx",
"author_id": 33708,
"author_profile": "https://Stackoverflow.com/users/33708",
"pm_score": 4,
"selected": true,
"text": "System.Security.Cryptography.ProtectedData"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25718/"
] |
369,334 | <p>Is is possible to have a local variable in an anonymous c# methods, i.e. in the following code I would like to perform the count only once.</p>
<pre><code>IQueryable<Enquiry> linq = db.Enquiries;
if(...) linq = linq.Where(...);
if(...) linq = linq.Where(e =>
(x <= (from p in db.Orders where p.EnquiryId == e.Id select p).Count() &&
(from p in db.Orders where p.EnquiryId == e.Id select p).Count() <= y));
if(...) linq = linq.Where(...);
var result = (from e in linq select e);
</code></pre>
<p>Is there a "let" for anonymous functions?</p>
<p>Update:
Note that I'm adding several Where clauses after this statement so I can't close with a select.</p>
<p>/Niels</p>
| [
{
"answer_id": 369341,
"author": "mmx",
"author_id": 33708,
"author_profile": "https://Stackoverflow.com/users/33708",
"pm_score": 5,
"selected": false,
"text": " x => { int y = x + 1; return x + y; }\n delegate(int x) {\n int y = x + 1;\n return x + y;\n }\n ... = linq.Where(e => {\n var count = (from p in db.Orders where p.EnquiryId == e.Id select p).Count();\n return x <= count && count <= y;\n });\n"
},
{
"answer_id": 369388,
"author": "Daniel Earwicker",
"author_id": 27423,
"author_profile": "https://Stackoverflow.com/users/27423",
"pm_score": 3,
"selected": false,
"text": "let ... = from e in linq \n let count = (from p in db.Orders where p.EnquiryId == e.Id select p).Count()\n where (x <= count) && (count <= y)\n select e;\n count where (x <= count) && /* <= */ (count <= y);\n"
},
{
"answer_id": 370706,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 0,
"selected": false,
"text": "(count => x <= count && count <= y)\n ((from p in db.Orders \n where p.EnquiryId == e.Id \n select p).Count())\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40939/"
] |
369,348 | <p>I have a number of icons used throughout an application - let's take ok/cancel icons as an example. At the moment they might be a tick and a cross (tick.png, cross.png) but I may want to replace them in future. Also, I would like to keep the resource path in one place.</p>
<p>Is this ok:</p>
<pre><code>public class Icons {
public static Icon OK = new ImageIcon(Icons.class.getResource("/icons/tick.png");
public static Icon CANCEL = new ImageIcon(Icons.class.getResource("/icons/cross.png");
}
</code></pre>
<p>Or should I be doing this a different way? I don't mind relying on the existence of the image files at runtime since they're in the .jar</p>
<p><strong>Solution</strong></p>
<p>I've used Bent's idea for initialisation, and I've made the constants final:</p>
<pre><code>public final class Icons {
private static final Logger logger = Logger.getLogger(Icons.class);
public static final Icon OK = icon("/icons/add.png");
public static final Icon CANCEL = icon("/icons/cancel.png");
private static Icon icon(String path) {
URL resource = Icons.class.getResource(path);
if(resource==null) {
logger.error("Resource "+path+" does not exist");
return new ImageIcon();
}
return new ImageIcon(resource);
}
}
</code></pre>
| [
{
"answer_id": 369378,
"author": "Bent André Solheim",
"author_id": 44380,
"author_profile": "https://Stackoverflow.com/users/44380",
"pm_score": 2,
"selected": true,
"text": "public static final Icon ok = icon(\"ok.png\");\n\n\nprivate static Icon icon(String path) {\n\n URL resource = Icons.class.getResource(\"/icons/\" + path);\n if (resource == null) {\n // Log something...\n return null;\n }\n return new ImageIcon(resource);\n}\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26334/"
] |
369,356 | <p>WinXP Pro
Oracle 10g Instant Client 10.2.0.1
MS Access 2003</p>
<p>When I link a table in MS Access, the pick list that appears shows me every table and view in the system I have access to. This list is quite large. Normally, I really only want to look at the tables that I own. Is there a way to filter the items displayed based on owner, or any other criteria?</p>
| [
{
"answer_id": 369378,
"author": "Bent André Solheim",
"author_id": 44380,
"author_profile": "https://Stackoverflow.com/users/44380",
"pm_score": 2,
"selected": true,
"text": "public static final Icon ok = icon(\"ok.png\");\n\n\nprivate static Icon icon(String path) {\n\n URL resource = Icons.class.getResource(\"/icons/\" + path);\n if (resource == null) {\n // Log something...\n return null;\n }\n return new ImageIcon(resource);\n}\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8670/"
] |
369,362 | <p>I have a table named categories, which contains ID(long), Name(varchar(50)), parentID(long), and shownByDefault(boolean) columns. </p>
<p>This table contains 554 records. All the shownByDefaultValues are 'false'.<br>
When I execute 'select id, name from categories', pg returns me all the categories,
orderer by its id.<br>
Then I update some of the rows of the table('update categories set shownByDefault where parentId = 1'), update OK.<br>
Then, when I try to execute the first query, which returns all the categories, they are
returner with a very weird order.<br>
I do not have problem to add 'order by', but since I am using JPA to get this values, anyone knows what the problem is or if there is a way to fix this?</p>
| [
{
"answer_id": 369371,
"author": "Joachim Sauer",
"author_id": 40342,
"author_profile": "https://Stackoverflow.com/users/40342",
"pm_score": 5,
"selected": true,
"text": "ORDER BY ORDER BY"
},
{
"answer_id": 369410,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "CLUSTER ORDER BY"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/314728/"
] |
369,364 | <p>I'd like to know if it's possible to compile an .swf file at runtime via C# (would be called via a Flex Application). I've read some articles about using fsch.exe, but nothing that gave any concrete examples.</p>
<p>I'm fairly certain this is possible, so a secondary question is whether it's feasible on a medium scale. I'd like to allow users to configure an swf, and then compile those settings directly into the swf for delivery rather than relying on external data storage for holding configuration details.</p>
<p>Thanks in advance for any assistance you can offer - </p>
<p>Bill</p>
| [
{
"answer_id": 369371,
"author": "Joachim Sauer",
"author_id": 40342,
"author_profile": "https://Stackoverflow.com/users/40342",
"pm_score": 5,
"selected": true,
"text": "ORDER BY ORDER BY"
},
{
"answer_id": 369410,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "CLUSTER ORDER BY"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369364",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46445/"
] |
369,367 | <p>I thought this was pretty straight forward but I don't get the same results as the tutorials I read. I have a button on an html page that calls a function in script tags. I also have a reference to the prototype.js file which I haven't even begun to implement yet. If I leave that reference in the page, my function call does not work from the button's onclick event. Below is what is called from the button onclick event.</p>
<p> </p>
<p></p>
<pre><code>callIt = function(){
alert('It worked!');
}
</script>
</code></pre>
| [
{
"answer_id": 369401,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 3,
"selected": true,
"text": "<script type=\"text/javascript\" src=\"prototype.js\"></script>\n <script ... /> Event.observe(window, 'load', function() {\n Event.observe('button_id', 'click', callIt); \n});\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2636656/"
] |
369,383 | <p>I am thinking about something like this:</p>
<pre><code>public static <T extends Comparable<T>> T minOf(T...ts){
SortedSet<T> set = new TreeSet<T>(Arrays.asList(ts));
return set.first();
}
public static <T extends Comparable<T>> T maxOf(T...ts){
SortedSet<T> set = new TreeSet<T>(Arrays.asList(ts));
return set.last();
}
</code></pre>
<p>But is not null safe, which is something I want too.</p>
<p>Do you know a better way to solve this problem?</p>
<p>EDIT:</p>
<p>After the comments I have also tried min():</p>
<pre><code>public static <T extends Comparable<T>> T minOf(T...ts){
return Collections.min(Arrays.asList(ts), new Comparator<T>(){
public int compare(T o1, T o2) {
if(o1!=null && o2!=null){
return o1.compareTo(o2);
}else if(o1!=null){
return 1;
}else{
return -1;
}
}});
}
</code></pre>
<p>What do you think of that?</p>
| [
{
"answer_id": 369413,
"author": "Marc Novakowski",
"author_id": 27020,
"author_profile": "https://Stackoverflow.com/users/27020",
"pm_score": 3,
"selected": false,
"text": "public static <T extends Comparable<T>> T minOf(T...ts){\n T min = null;\n for (T t : ts) {\n if (t != null && (min == null || t.compareTo(min) < 0)) {\n min = t;\n }\n }\n return min;\n}\n\npublic static <T extends Comparable<T>> T maxOf(T...ts){\n T max = null;\n for (T t : ts) {\n if (t != null && (max == null || t.compareTo(max) > 0)) {\n max = t;\n }\n }\n return max;\n}\n"
},
{
"answer_id": 30596059,
"author": "Ciro Santilli OurBigBook.com",
"author_id": 895245,
"author_profile": "https://Stackoverflow.com/users/895245",
"pm_score": 1,
"selected": false,
"text": "Comparable ComparableNull"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1356709/"
] |
369,417 | <p>I'm puzzling over how to map a set of sequences to consecutive integers.</p>
<p>All the sequences follow this rule:</p>
<pre><code>A_0 = 1
A_n >= 1
A_n <= max(A_0 .. A_n-1) + 1
</code></pre>
<p>I'm looking for a solution that will be able to, given such a sequence, compute a integer for doing a lookup into a table and given an index into the table, generate the sequence.</p>
<p>Example: for length 3, there are 5 the valid sequences. A fast function for doing the following map (preferably in both direction) would be a good solution</p>
<pre><code>1,1,1 0
1,1,2 1
1,2,1 2
1,2,2 3
1,2,3 4
</code></pre>
<hr>
<ul>
<li>The point of the exercise is to get a packed table with a 1-1 mapping between valid sequences and cells.</li>
<li>The size of the set in bounded only by the number of unique sequences possible.</li>
<li>I don't know now what the length of the sequence will be but it will be a small, <12, constant known in advance.</li>
<li>I'll get to this sooner or later, but though I'd throw it out for the community to have "fun" with in the meantime.</li>
</ul>
<hr>
<p>these are different valid sequences</p>
<pre><code>1,1,2,3,2,1,4
1,1,2,3,1,2,4
1,2,3,4,5,6,7
1,1,1,1,2,3,2
</code></pre>
<p>these are not</p>
<pre><code>1,2,2,4
2,
1,1,2,3,5
</code></pre>
<hr>
<p>Related to <a href="https://stackoverflow.com/questions/346760/how-to-find-equivalent-texts">this</a></p>
| [
{
"answer_id": 369453,
"author": "Tzury Bar Yochay",
"author_id": 9296,
"author_profile": "https://Stackoverflow.com/users/9296",
"pm_score": 0,
"selected": false,
"text": "def valid_lines(lines):\n for line in lines:\n line = line.split(\",\")\n if line[0] == 1 and line[-1] and line[-1] <= max(line)+1:\n yield line\n\nlines = (line for line in open('/tmp/numbers.txt'))\nfor valid_line in valid_lines(lines):\n print valid_line\n"
},
{
"answer_id": 4377814,
"author": "Ante",
"author_id": 494076,
"author_profile": "https://Stackoverflow.com/users/494076",
"pm_score": 2,
"selected": true,
"text": "<Steps, Group> T(l,n) = n*T(l-1,n) + T(l-1,n+1)\nT(1,n) = n\n l + n <= sequence length + 1 sequence_length^2/2 T(7,1) + # for 1000000\n2^2 * T(4,2) + # for 001000\n2^2 * 3 * T(2,3) # for 010\n >O(1) Steps Groups Steps O(1)"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1343/"
] |
369,424 | <p>This is a follow-up question to <a href="https://stackoverflow.com/questions/369220/why-should-you-not-use-number-as-a-constructor">this one</a>.</p>
<p>Take a look at these two examples: </p>
<pre><code>var number1 = new Number(3.123);
number1 = number1.toFixed(2);
alert(number1);
var number2 = 3.123;
number2 = number2.toFixed(2);
alert(number2);
</code></pre>
<p>I realize they both end up with the same value, but is it correct thinking to refer to a method of a primitive value? (In other words, 3.123.method as opposed to object.method?)</p>
| [
{
"answer_id": 369479,
"author": "Matthew Crumley",
"author_id": 2214,
"author_profile": "https://Stackoverflow.com/users/2214",
"pm_score": 3,
"selected": false,
"text": "Number toFixed Object.prototype.type = function() { return typeof this; }\n\nvar string = \"a string\";\nvar number = 42;\n\nalert(typeof string); // string\nalert(string.type()); // object\n\nalert(typeof number); // number\nalert(number.type()); // object\n"
},
{
"answer_id": 369480,
"author": "Steven Huwig",
"author_id": 28604,
"author_profile": "https://Stackoverflow.com/users/28604",
"pm_score": 3,
"selected": true,
"text": ">>> (3.123).toString()\n\"3.123\"\n"
},
{
"answer_id": 369627,
"author": "Ates Goral",
"author_id": 23501,
"author_profile": "https://Stackoverflow.com/users/23501",
"pm_score": 2,
"selected": false,
"text": "Object.prototype.getPrototype = function() { return \"Object\"; };\nNumber.prototype.getPrototype = function() { return \"Number\"; };\n\nfunction test(v) {\n alert(\"proto: \" + v.getPrototype()\n + \", type: \" + typeof v\n + \", is a Number: \" + (v instanceof Number)\n + \", is an Object: \" + (v instanceof Object));\n}\n\n// proto: Number, type: number, is a Number: false, is an Object: false\ntest(42);\n\n// proto: Number, type: number, is a Number: false, is an Object: false\ntest(Number(42));\n\n// proto: Number, type: object, is a Number: true, is an Object: true\ntest(Object(42));\n\n// proto: Number, type: object, is a Number: true, is an Object: true\ntest(new Number(42));\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
369,438 | <p>I'm currently writing a program to generate really enormous (65536x65536 pixels and above) Mandelbrot images, and I'd like to devise a spectrum and coloring scheme that does them justice. The <a href="http://en.wikipedia.org/wiki/File:Mandel_zoom_00_mandelbrot_set.jpg" rel="noreferrer">wikipedia featured mandelbrot image</a> seems like an excellent example, especially how the palette remains varied at all zoom levels of the sequence. I'm not sure if it's rotating the palette or doing some other trick to achieve this, though.</p>
<p>I'm familiar with the <a href="http://en.wikipedia.org/wiki/Mandelbrot_set#Continuous_.28smooth.29_coloring" rel="noreferrer">smooth coloring algorithm</a> for the mandelbrot set, so I can avoid banding, but I still need a way to assign colors to output values from this algorithm.</p>
<p>The images I'm generating are pyramidal (eg, a series of images, each of which has half the dimensions of the previous one), so I can use a rotating palette of some sort, as long as the change in the palette between subsequent zoom levels isn't too obvious.</p>
| [
{
"answer_id": 369520,
"author": "Paul Brinkley",
"author_id": 18160,
"author_profile": "https://Stackoverflow.com/users/18160",
"pm_score": 2,
"selected": false,
"text": "(H2 - H1) * P + H1 = HP\n(S2 - S1) * P + S1 = SP\n(V2 - V1) * P + V1 = VP\n"
},
{
"answer_id": 1243788,
"author": "Per Alexandersson",
"author_id": 152109,
"author_profile": "https://Stackoverflow.com/users/152109",
"pm_score": 5,
"selected": false,
"text": "z0 n zn nsmooth := n + 1 - Math.log(Math.log(zn.abs()))/Math.log(2)\n Complex z = new Complex(x,y);\ndouble smoothcolor = Math.exp(-z.abs());\n\nfor(i=0;i<max_iter && z.abs() < 30;i++) {\n z = f(z);\n smoothcolor += Math.exp(-z.abs());\n}\n smoothcolor (0,max_iter) smoothcolor max_iter Color.HSBtoRGB(0.95f + 10 * smoothcolor ,0.6f,1.0f);\n"
},
{
"answer_id": 18678856,
"author": "Alex Russell",
"author_id": 2146829,
"author_profile": "https://Stackoverflow.com/users/2146829",
"pm_score": 3,
"selected": false,
"text": "for (ix = 0; ix < panelMain.Width; ix++)\n {\n cx = cxMin + (double )ix * pixelWidth;\n // init this go \n zx = 0.0;\n zy = 0.0;\n zx2 = 0.0;\n zy2 = 0.0;\n for (i = 0; i < iterationMax && ((zx2 + zy2) < er2); i++)\n {\n zy = zx * zy * 2.0 + cy;\n zx = zx2 - zy2 + cx;\n zx2 = zx * zx;\n zy2 = zy * zy;\n }\n if (i == iterationMax)\n {\n // interior, part of set, black\n // set colour to black\n g.FillRectangle(sbBlack, ix, iy, 1, 1);\n }\n else\n {\n // outside, set colour proportional to time/distance it took to converge\n // set colour not black\n SolidBrush sbNeato = new SolidBrush(MapColor(i, zx2, zy2));\n g.FillRectangle(sbNeato, ix, iy, 1, 1);\n }\n private Color MapColor(int i, double r, double c)\n {\n double di=(double )i;\n double zn;\n double hue;\n\n zn = Math.Sqrt(r + c);\n hue = di + 1.0 - Math.Log(Math.Log(Math.Abs(zn))) / Math.Log(2.0); // 2 is escape radius\n hue = 0.95 + 20.0 * hue; // adjust to make it prettier\n // the hsv function expects values from 0 to 360\n while (hue > 360.0)\n hue -= 360.0;\n while (hue < 0.0)\n hue += 360.0;\n\n return ColorFromHSV(hue, 0.8, 1.0);\n }\n"
},
{
"answer_id": 37941364,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "var rgbcol = [] ;\nvar rgbcol = MapColor ( Iteration , Zy2,Zx2 ) ;\npoint ( ctx , iX, iY ,rgbcol[0],rgbcol[1],rgbcol[2] ); \n /*\n * The Mandelbrot Set, in HTML5 canvas and javascript.\n * https://github.com/cslarsen/mandelbrot-js\n *\n * Copyright (C) 2012 Christian Stigen Larsen\n*/\n\n/*\n * Convert hue-saturation-value/luminosity to RGB.\n *\n * Input ranges:\n * H = [0, 360] (integer degrees)\n * S = [0.0, 1.0] (float)\n * V = [0.0, 1.0] (float)\n */\nfunction hsv_to_rgb(h, s, v)\n{\n if ( v > 1.0 ) v = 1.0;\n var hp = h/60.0;\n var c = v * s;\n var x = c*(1 - Math.abs((hp % 2) - 1));\n var rgb = [0,0,0];\n\n if ( 0<=hp && hp<1 ) rgb = [c, x, 0];\n if ( 1<=hp && hp<2 ) rgb = [x, c, 0];\n if ( 2<=hp && hp<3 ) rgb = [0, c, x];\n if ( 3<=hp && hp<4 ) rgb = [0, x, c];\n if ( 4<=hp && hp<5 ) rgb = [x, 0, c];\n if ( 5<=hp && hp<6 ) rgb = [c, 0, x];\n\n var m = v - c;\n rgb[0] += m;\n rgb[1] += m;\n rgb[2] += m;\n\n rgb[0] *= 255;\n rgb[1] *= 255;\n rgb[2] *= 255;\n\n rgb[0] = parseInt ( rgb[0] ); \n rgb[1] = parseInt ( rgb[1] );\n rgb[2] = parseInt ( rgb[2] ); \n\n return rgb;\n}\n\n// http://stackoverflow.com/questions/369438/smooth-spectrum-for-mandelbrot-set-rendering\n// alex russel : http://stackoverflow.com/users/2146829/alex-russell\n\nfunction MapColor(i,r,c)\n{\n var di= i;\n var zn;\n var hue;\n\n zn = Math.sqrt(r + c);\n hue = di + 1.0 - Math.log(Math.log(Math.abs(zn))) / Math.log(2.0); // 2 is escape radius\n hue = 0.95 + 20.0 * hue; // adjust to make it prettier\n // the hsv function expects values from 0 to 360\n while (hue > 360.0)\n hue -= 360.0;\n while (hue < 0.0)\n hue += 360.0;\n\n return hsv_to_rgb(hue, 0.8, 1.0);\n}\n"
},
{
"answer_id": 55522055,
"author": "Jason Hoffoss",
"author_id": 11307759,
"author_profile": "https://Stackoverflow.com/users/11307759",
"pm_score": 0,
"selected": false,
"text": " double value = Math.log(0.021 * (iteration + delta + 60)) + 0.72;\n value = value - Math.floor(value);\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12030/"
] |
369,448 | <p>I'm having this problem, same as ever, but never try to find the <em>right</em> solution</p>
<p>code:</p>
<pre><code> <div id="ListOfTextAndPhotos">
<div style="border-bottom: solid 1px silver;">
<img src="photo.jpg" style="float: left">
Some text about the photo
</div>
<div style="border-bottom: solid 1px silver;">
<img src="photo2.jpg" style="float: left">
Some text about the photo2
</div>
<div style="border-bottom: solid 1px silver;">
<img src="photo3.jpg" style="float: left">
Some text about the photo3
</div>
</div>
</code></pre>
<p>Question:
<strong>How do I to keep the photo inside the DIV?</strong> with the separator line under the photo</p>
| [
{
"answer_id": 369465,
"author": "cLFlaVA",
"author_id": 45109,
"author_profile": "https://Stackoverflow.com/users/45109",
"pm_score": 2,
"selected": false,
"text": " <div id=\"ListOfTextAndPhotos\">\n <div style=\"border-bottom: solid 1px silver;\">\n <img src=\"photo.jpg\" style=\"float: left\">\n <div style=\"clear:both;\">Some text about the photo</div>\n </div>\n <div style=\"border-bottom: solid 1px silver;\">\n <img src=\"photo2.jpg\" style=\"float: left\">\n <div style=\"clear:both;\">Some text about the photo2</div>\n </div>\n <div style=\"border-bottom: solid 1px silver;\">\n <img src=\"photo3.jpg\" style=\"float: left\">\n <div style=\"clear:both;\">Some text about the photo3</div>\n </div>\n </div>\n"
},
{
"answer_id": 369483,
"author": "davethegr8",
"author_id": 12930,
"author_profile": "https://Stackoverflow.com/users/12930",
"pm_score": 7,
"selected": true,
"text": "<div style=\"border-bottom: solid 1px silver; overflow: hidden;\">\n <img src=\"photo3.jpg\" style=\"float: left\">\n <div>Some text about the photo3</div>\n</div>\n"
},
{
"answer_id": 369869,
"author": "Steve Perks",
"author_id": 16124,
"author_profile": "https://Stackoverflow.com/users/16124",
"pm_score": 2,
"selected": false,
"text": "<div style=\"clear:both;\"></div> overflow: hidden; zoom: 1;"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2385/"
] |
369,452 | <p>I am being powerfully tempted to use an unchecked exception as a short-circuit control-flow construct in a Java program. I hope somebody here can advise me on a better, cleaner way to handle this problem.</p>
<p>The idea is that I want to cut short the recursive exploration of sub-trees by a visitor without having to check a "stop" flag in every method call. Specifically, I'm building a control-flow graph using a visitor over the abstract syntax tree. A <code>return</code> statement in the AST should stop exploration of the sub-tree and send the visitor back to the nearest enclosing if/then or loop block. </p>
<p>The <code>Visitor</code> superclass (from the <a href="http://cs.nyu.edu/rgrimm/xtc/" rel="noreferrer">XTC library</a>) defines</p>
<pre><code>Object dispatch(Node n)
</code></pre>
<p>which calls back via reflection methods of the form</p>
<pre><code>Object visitNodeSubtype(Node n)
</code></pre>
<p><code>dispatch</code> is not declared to throw any exceptions, so I declared a private class that extends <code>RuntimeException</code></p>
<pre><code>private static class ReturnException extends RuntimeException {
}
</code></pre>
<p>Now, the visitor method for a return statement looks like</p>
<pre><code>Object visitReturnStatement(Node n) {
// handle return value assignment...
// add flow edge to exit node...
throw new ReturnException();
}
</code></pre>
<p>and every compound statement needs to handle the <code>ReturnException</code></p>
<pre><code>Object visitIfElseStatement(Node n) {
Node test = n.getChild(0);
Node ifPart = n.getChild(1);
Node elsePart = n.getChild(2);
// add flow edges to if/else...
try{ dispatch(ifPart); } catch( ReturnException e ) { }
try{ dispatch(elsePart); } catch( ReturnException e ) { }
}
</code></pre>
<p>This all works fine, except:</p>
<ol>
<li>I may forget to catch a <code>ReturnException</code> somewhere and the compiler won't warn me.</li>
<li>I feel dirty.</li>
</ol>
<p>Is there a better way to do this? Is there a Java pattern I am unaware of to implement this kind of non-local flow-of-control?</p>
<p>[UPDATE] This specific example turns out to be somewhat invalid: the <code>Visitor</code> superclass catches and wraps exceptions (even <code>RuntimeException</code>s), so the exception throwing doesn't really help. I've implemented the suggestion to return an <code>enum</code> type from <code>visitReturnStatement</code>. Luckily, this only needs to be checked in a small number of places (e.g., <code>visitCompoundStatement</code>), so it's actually a bit less hassle than throwing exceptions. </p>
<p>In general, I think this is still a valid question. Though perhaps, if you are not tied to a third-party library, the entire problem can be avoided with sensible design.</p>
| [
{
"answer_id": 369494,
"author": "Paul Brinkley",
"author_id": 18160,
"author_profile": "https://Stackoverflow.com/users/18160",
"pm_score": 0,
"selected": false,
"text": "RuntimeException dispatch"
},
{
"answer_id": 369860,
"author": "Dan Vinton",
"author_id": 21849,
"author_profile": "https://Stackoverflow.com/users/21849",
"pm_score": 0,
"selected": false,
"text": "accept(visitor) visitXxx(node) accept(visitor) accept(visitor)"
},
{
"answer_id": 370544,
"author": "Apocalisp",
"author_id": 3434,
"author_profile": "https://Stackoverflow.com/users/3434",
"pm_score": 2,
"selected": false,
"text": "public Something visit(Node n) {\n if (n.someting())\n return new Something();\n else\n throw new Error(\"Remember to catch me!\");\n}\n public Callable<Something> visit(final Node n) {\n return new Callable<Something>() {\n public Something call() throws Exception {\n if (n.something())\n return new Something();\n else\n throw new Exception(\"Unforgettable!\");\n }\n };\n}\n Tuple<A, B> public Either<Fail, Something> visit(final Node n) {\n if (n.something())\n return Either.<Fail, Something>right(new Something());\n else\n return Either.<Fail, Something>left(Fail.DONE);\n}\n Either<Fail, Something> x = node.dispatch(visitor);\nfor (Something s : x.rightProjection()) {\n // Do something with Something\n}\nfor (Fail f : x.leftProjection()) {\n // Handle failure\n}\n public Option<Something> visit(final Node n) {\n if (n.something())\n return Option.some(new Something());\n else\n return Option.<Something>none();\n} \n Option<Something> s = node.dispatch(visitor));\nif (s.isSome()) {\n Something x = s.some();\n // Do something with x.\n}\nelse {\n // Handle None.\n}\n public Option<Something> visit(final Node n) {\n return dispatch(getIfPart(n).orElse(dispatch(getElsePart(n)));\n} \n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1412/"
] |
369,460 | <p>I am using Hibernate 3.x, MySQL 4.1.20 with Java 1.6. I am mapping a Hibernate Timestamp to a MySQL TIMESTAMP. So far so good. The problem is that MySQL stores the TIMESTAMP in seconds and discards the milliseconds and I now need millisecond precision. I figure I can use a BIGINT instead of TIMESTAMP in my table and convert the types in my Java code. I'm trying to figure out if there is a better way of doing this using hibernate, mysql, JDBC or some combination so I can still use date functions in my HSQL and/or SQL queries?</p>
| [
{
"answer_id": 371326,
"author": "bangroot",
"author_id": 45693,
"author_profile": "https://Stackoverflow.com/users/45693",
"pm_score": 3,
"selected": true,
"text": "public class CalendarBigIntType extends org.hibernate.type.CalendarType {\n public Object get(ResultSet rs, String name) {\n return cal = new GregorianCalendar(rs.getLong(name));\n }\n public void set(PreparedStatement stmt, Object value, int index) {\n stmt.setParameter(index, ((Calendar) value).getTime());\n }\n}\n @TypeDef (name=\"bigIntCalendar\", typeClass=CalendarBigIntType.class)\n@Entity\npublic class MyEntity {\n @Type(type=\"bigIntCalendar\")\n private Calendar myDate;\n}\n"
},
{
"answer_id": 3463572,
"author": "Alex",
"author_id": 275837,
"author_profile": "https://Stackoverflow.com/users/275837",
"pm_score": 0,
"selected": false,
"text": "public static Calendar bigDec2Cal(BigDecimal tsp) {\n Calendar cal = Calendar.getInstance();\n cal.setTimeInMillis(tsp.longValue());\n return cal;\n}\n\npublic static Date bigDec2Date(BigDecimal tsp) {\n Calendar cal = Calendar.getInstance();\n cal.setTimeInMillis(tsp.longValue());\n return cal.getTime();\n}\n\npublic static BigDecimal cal2BigDec(Calendar cal) {\n BigDecimal tsp = new BigDecimal(cal.getTimeInMillis());\n return tsp;\n}\n\npublic static BigDecimal date2BigDec(Date date) {\n Calendar cal = Calendar.getInstance();\n cal.setTime(date);\n BigDecimal tsp = new BigDecimal(cal.getTimeInMillis());\n return tsp;\n}\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4476/"
] |
369,495 | <p>Are C-style macro names subject to the same naming rules as identifiers? After a compiler upgrade, it is now emitting this warning for a legacy application:</p>
<pre><code>warning #3649-D: white space is required between the macro name "CHAR_" and its replacement text
#define CHAR_& 38
</code></pre>
<p>This line of code is defining an ASCII value constant for an ampersand.</p>
<pre><code>#define DOL_SN 36
#define PERCENT 37
#define CHAR_& 38
#define RT_SING 39
#define LF_PAR 40
</code></pre>
<p>I assume that this definition (not actually referenced by any code, as far as I can tell) is buggy and should be changed to something like "CHAR_AMPERSAND"?</p>
| [
{
"answer_id": 369524,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 6,
"selected": true,
"text": "'a-z' 'A-Z' '0-9' '_' '$' defined '\\u' '\\U' '\\u' '\\U' -fextended-identifiers '$' '$' '$' -$"
},
{
"answer_id": 369544,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 1,
"selected": false,
"text": "digits non-digits non-digits"
},
{
"answer_id": 34315237,
"author": "Alex Gray",
"author_id": 547214,
"author_profile": "https://Stackoverflow.com/users/547214",
"pm_score": 4,
"selected": false,
"text": "clang #define ?: /// WORKS FINE\n#define ■ @end /// WORKS FINE\n#define @interface /// WORKS FINE\n#define P @protocol /// WORKS FINE\n #define ☎ TEL /// ERROR: Macro name must be an identifier.\n#define ❌ NO /// ERROR: Macro name must be an identifier.\n#define ⇧ UP /// ERROR: Macro name must be an identifier.\n#define 〓 == /// ERROR: Macro name must be an identifier.\n#define APPLE /// ERROR: Macro name must be an identifier.\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17035/"
] |
369,498 | <p>Some websites have code to "break out" of <code>IFRAME</code> enclosures, meaning that if a page <code>A</code> is loaded as an <code>IFRAME</code> inside an parent page <code>P</code> some Javascript in <code>A</code> redirects the outer window to <code>A</code>.</p>
<p>Typically this Javascript looks something like this:</p>
<pre><code><script type="text/javascript">
if (top.location.href != self.location.href)
top.location.href = self.location.href;
</script>
</code></pre>
<p>My question is: As the author of the parent page <code>P</code> and not being the author of the inner page <code>A</code>, how can I prevent <code>A</code> from doing this break-out?</p>
<p>P.S. It seems to me like it ought to be a cross-site security violation, but it isn't.</p>
| [
{
"answer_id": 2139246,
"author": "radu",
"author_id": 259198,
"author_profile": "https://Stackoverflow.com/users/259198",
"pm_score": 2,
"selected": false,
"text": "<script type=\"text/javascript\">\n window.onbeforeunload = function () { \n return \"This will end your session\";\n }\n</script>\n"
},
{
"answer_id": 9880360,
"author": "Pankrat",
"author_id": 63392,
"author_profile": "https://Stackoverflow.com/users/63392",
"pm_score": 7,
"selected": false,
"text": "<iframe src=\"url\" sandbox=\"allow-forms allow-scripts\"></iframe>\n sandbox=\"allow-top-navigation\""
},
{
"answer_id": 11799307,
"author": "Luis Deleon",
"author_id": 1574627,
"author_profile": "https://Stackoverflow.com/users/1574627",
"pm_score": 2,
"selected": false,
"text": "<script type=\"text/javasript\">\nvar prevent_bust = false ;\n var from_loading_204 = false;\n var frame_loading = false;\n var prevent_bust_timer = 0;\n var primer = true;\n window.onbeforeunload = function(event) {\n prevent_bust = !from_loading_204 && frame_loading;\n if(from_loading_204)from_loading_204 = false;\n if(prevent_bust){\n prevent_bust_timer=500;\n }\n }\n function frameLoad(){\n if(!primer){\n from_loading_204 = true;\n window.top.location = '/?204';\n prevent_bust = false;\n frame_loading = true;\n prevent_bust_timer=1000;\n }else{\n primer = false;\n }\n }\n setInterval(function() { \n if (prevent_bust_timer>0) { \n if(prevent_bust){\n from_loading_204 = true;\n window.top.location = '/?204';\n prevent_bust = false;\n }else if(prevent_bust_timer == 1){\n frame_loading = false;\n prevent_bust = false;\n from_loading_204 = false;\n prevent_bust_timer == 0;\n }\n\n\n\n }\n prevent_bust_timer--;\n if(prevent_bust_timer==-100) {\n prevent_bust_timer = 0;\n }\n }, 1);\n</script>\n onload=\"frameLoad()\" onreadystatechange=\"frameLoad();\""
},
{
"answer_id": 18073191,
"author": "Parris",
"author_id": 181310,
"author_profile": "https://Stackoverflow.com/users/181310",
"pm_score": 4,
"selected": false,
"text": "sandbox=\"\""
},
{
"answer_id": 21347627,
"author": "adigioia",
"author_id": 3138540,
"author_profile": "https://Stackoverflow.com/users/3138540",
"pm_score": 6,
"selected": false,
"text": "sandbox iframe allow-forms allow-popups allow-pointer-lock allow-same-origin allow-scripts allow-top-navigation <iframe sandbox=\"allow-same-origin allow-scripts allow-popups allow-forms\" src=\"http://www.example.com\"</iframe>\n"
},
{
"answer_id": 72130459,
"author": "Ashnet",
"author_id": 3820361,
"author_profile": "https://Stackoverflow.com/users/3820361",
"pm_score": 1,
"selected": false,
"text": "<iframe sandbox=\" \"></iframe>\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4926/"
] |
369,504 | <p>We are considering Microsoft DSL toolkit for creating some abstract designers. I already did some POCs, but would like to get some opinions on the same.</p>
<p>Any one here to share their experiences working with Microsoft DSL Toolkit and T4? Also, any pointers to open source DSL projects will help - Eg. Microsoft Service Factory modeling edition is heavily relying on DSL toolkit.</p>
<p>As OSLO/Quadrant will take some time to get released, I think the only option we have is to rely on Microsoft DSL designer. (<a href="http://blogs.msdn.com/keith_short/archive/2008/11/06/oslo-and-the-dsl-toolkit.aspx" rel="noreferrer">See Kieth's blog on the same</a>)</p>
<p>Also, here is some information I already have on DSL:</p>
<p>1 - <a href="http://code.msdn.microsoft.com/DSLToolsLab" rel="noreferrer">A Nice Lab in MSDN on DSL tools</a></p>
<p>2 - <a href="http://www.codeplex.com/site/search?ProjectSearchText=DSL" rel="noreferrer">A List of Projects in Codeplex using DSL toolkit</a></p>
| [
{
"answer_id": 661989,
"author": "Glenn",
"author_id": 78936,
"author_profile": "https://Stackoverflow.com/users/78936",
"pm_score": 0,
"selected": false,
"text": "CREATE TABLE [dbo].[OrderProcessStep](\n [OrderProcessCode] [int] NOT NULL,\n [PreviousProcessStatusCode] [int] NOT NULL,\n [NextProcessStatusCode] [int] NULL,\n [DenialProcessStatusCode] [int] NULL,\n [ErrorProcessStatusCode] [int] NULL,\n [ProcessActionId] [int] NULL,\n [StepComment] [varchar](500) NOT NULL,\n [SecondsToNext] [int] NULL,\n [SecondsToError] [int] NULL,\n [SecondsToDenial] [int] NULL,\n CONSTRAINT [PK_OrderProcess] PRIMARY KEY CLUSTERED \n(\n [OrderProcessCode] ASC,\n [PreviousProcessStatusCode] ASC\n)\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45956/"
] |
369,506 | <p>I'm using a streamwriter to log errors</p>
<p>the way it has been designed (please dont ask why) is to open a new streamwriter everytime the application has to log a message. It outputs everything to ./Logs/[current-date].txt which usually resolves to "c:\myappfolder\logs[current-date].txt"</p>
<p>Everything works correctly, but after I use an open file dialog to say, "C:\home\myfolder\myfile" the streamwriter tries to write to "c:\home\myfolder\logs[current-date].txt"</p>
<p>I know solutions to this problem but i just dont understand what's going on</p>
| [
{
"answer_id": 369513,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 4,
"selected": true,
"text": "OpenFileDialog OpenFileDialog RestoreDirectory true RestoreDirectory"
},
{
"answer_id": 369523,
"author": "biozinc",
"author_id": 30698,
"author_profile": "https://Stackoverflow.com/users/30698",
"pm_score": 2,
"selected": false,
"text": "OpenFileDialog ./ RestoreDirectory OpenFileDialog openFileDialog1 = new OpenFileDialog();\n\nOpenFileDialog1.InitialDirectory = \"c:\\\\\" ;\nopenFileDialog1.Filter = \"txt files (*.txt)|*.txt|All files (*.*)|*.*\" ;\nopenFileDialog1.FilterIndex = 2 ;\nopenFileDialog1.RestoreDirectory = true ;\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6367/"
] |
369,510 | <p>I have an Excel file that has a bunch of VBA and macro code in it. When I open the file in Excel I can choose not to 'enable' them - so the values in the fields all stay as they were during the last save. I need to manipulate the values as they were last saved - so I don't want the macros (which look at the current date and update values accordingly) to run.</p>
<p>When I open it via our dot net code: </p>
<pre><code>Dim oxlRep As Excel.Application
Dim oWBRep As Excel.Workbook
Dim oSheetRep As Excel.Worksheet
Dim oRngRep As Excel.Range
oxlRep.Open(path)
</code></pre>
<p>the vb code runs - throwing off the values. I've been looking for a way to open it without macros, or in 'secure' mode where the macros aren't run. If I simply double click the file and don't choose to enable macros the values are all there as I want them. </p>
<p>Usually we run this code within the month that the files are created, so we haven't seen this problem in the 3 or 4 years that it has been working. Now I need to go back to some of the old files and run some archival code... </p>
<p>Anyone have a suggestion?</p>
| [
{
"answer_id": 369583,
"author": "shahkalpesh",
"author_id": 23574,
"author_profile": "https://Stackoverflow.com/users/23574",
"pm_score": 3,
"selected": true,
"text": "Application.AutomationSecurity = msoAutomationSecurity.msoAutomationSecurityForceDisable\n"
},
{
"answer_id": 369592,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 2,
"selected": false,
"text": "strLinkFile = \"C:\\Docs\\LTD.xls\"\n\nSet cn = CreateObject(\"ADODB.Connection\")\ncn.Open \"Provider=Microsoft.Jet.OLEDB.4.0;\" & _\n \"Data Source=\" & strLinkFile & \";\" & _\n \"Extended Properties=\"\"Excel 8.0;HDR=YES;\"\"\"\n\nSet rs = CreateObject(\"ADODB.Recordset\")\nrs.Open \"Select * from [Sheet1$A1:B5]\", cn, adOpenStatic \n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37559/"
] |
369,512 | <p>Assume you have some objects which have several fields they can be compared by:</p>
<pre><code>public class Person {
private String firstName;
private String lastName;
private String age;
/* Constructors */
/* Methods */
}
</code></pre>
<p>So in this example, when you ask if:</p>
<pre><code>a.compareTo(b) > 0
</code></pre>
<p>you might be asking if a's last name comes before b's, or if a is older than b, etc...</p>
<p>What is the cleanest way to enable multiple comparison between these kinds of objects without adding unnecessary clutter or overhead?</p>
<ul>
<li><code>java.lang.Comparable</code> interface allows comparison by one field only</li>
<li>Adding numerous compare methods (i.e. <code>compareByFirstName()</code>, <code>compareByAge()</code>, etc...) is cluttered in my opinion.</li>
</ul>
<p>So what is the best way to go about this?</p>
| [
{
"answer_id": 369537,
"author": "Elie",
"author_id": 23249,
"author_profile": "https://Stackoverflow.com/users/23249",
"pm_score": 8,
"selected": true,
"text": "Comparator Person"
},
{
"answer_id": 369867,
"author": "Steve Kuo",
"author_id": 24396,
"author_profile": "https://Stackoverflow.com/users/24396",
"pm_score": 7,
"selected": false,
"text": "Comparable <Person> compareTo public int compareTo(Person other) {\n int i = firstName.compareTo(other.firstName);\n if (i != 0) return i;\n\n i = lastName.compareTo(other.lastName);\n if (i != 0) return i;\n\n return Integer.compare(age, other.age);\n}\n"
},
{
"answer_id": 370068,
"author": "Boune",
"author_id": 45757,
"author_profile": "https://Stackoverflow.com/users/45757",
"pm_score": 4,
"selected": false,
"text": "Collections.sort(myChildren, Child.Order.ByAge.descending());\n"
},
{
"answer_id": 9842650,
"author": "Andrejs",
"author_id": 1180621,
"author_profile": "https://Stackoverflow.com/users/1180621",
"pm_score": -1,
"selected": false,
"text": "Objects.equal(name, name2) && Objects.equal(age, age2) && ..."
},
{
"answer_id": 10940234,
"author": "missingfaktor",
"author_id": 192247,
"author_profile": "https://Stackoverflow.com/users/192247",
"pm_score": 3,
"selected": false,
"text": "Comparator A Ord A Ord A A Comparator Ord A Ord B (A, B) Ord (A, B) Ord A Ord B Ord C Ord (A, B, C) Ord A, Ord B, Ord C, ..., Ord Z Ord (A, B, C, .., Z) Ord A B A f Ord B B A f Ord A B → A Ord A → Ord B comap Ord A, (B → A) Ord B Person String Ord String Ord (String, String, String) Person (String, String, String) Ord (String, String, String) Person → (String, String, String) comap Ord Person Ord<Person> personOrd = \n p3Ord(stringOrd, stringOrd, stringOrd).comap(\n new F<Person, P3<String, String, String>>() {\n public P3<String, String, String> f(Person x) {\n return p(x.getFirstName(), x.getLastname(), x.getAge());\n }\n }\n );\n stringOrd Ord<String> p3Ord Ord<A> Ord<B> Ord<C> Ord<P3<A, B, C>> P3 comap comap F<A, B> A → B p"
},
{
"answer_id": 17321802,
"author": "Ran Adler",
"author_id": 2447599,
"author_profile": "https://Stackoverflow.com/users/2447599",
"pm_score": 4,
"selected": false,
"text": "import com.google.common.collect.ComparisonChain;\n\n/**\n * @author radler\n * Class Description ...\n */\npublic class Attribute implements Comparable<Attribute> {\n\n private String type;\n private String value;\n\n public String getType() { return type; }\n public void setType(String type) { this.type = type; }\n\n public String getValue() { return value; }\n public void setValue(String value) { this.value = value; }\n\n @Override\n public String toString() {\n return \"Attribute [type=\" + type + \", value=\" + value + \"]\";\n }\n\n @Override\n public int compareTo(Attribute that) {\n return ComparisonChain.start()\n .compare(this.type, that.type)\n .compare(this.value, that.value)\n .result();\n }\n\n}\n"
},
{
"answer_id": 20093642,
"author": "Benny Bottema",
"author_id": 441662,
"author_profile": "https://Stackoverflow.com/users/441662",
"pm_score": 7,
"selected": false,
"text": "Collections.sort(reportList, Comparator.comparing(Report::getReportKey)\n .thenComparing(Report::getStudentNumber)\n .thenComparing(Report::getSchool));\n Collections.sort(pizzas, new Comparator<Pizza>() { \n @Override \n public int compare(Pizza p1, Pizza p2) { \n int sizeCmp = p1.size.compareTo(p2.size); \n if (sizeCmp != 0) { \n return sizeCmp; \n } \n int nrOfToppingsCmp = p1.nrOfToppings.compareTo(p2.nrOfToppings); \n if (nrOfToppingsCmp != 0) { \n return nrOfToppingsCmp; \n } \n return p1.name.compareTo(p2.name); \n } \n}); \n ComparatorChain chain = new ComparatorChain(Arrays.asList(\n new BeanComparator(\"size\"), \n new BeanComparator(\"nrOfToppings\"), \n new BeanComparator(\"name\")));\n\nCollections.sort(pizzas, chain); \n Collections.sort(pizzas, new Comparator<Pizza>() { \n @Override \n public int compare(Pizza p1, Pizza p2) { \n return ComparisonChain.start().compare(p1.size, p2.size).compare(p1.nrOfToppings, p2.nrOfToppings).compare(p1.name, p2.name).result(); \n // or in case the fields can be null: \n /* \n return ComparisonChain.start() \n .compare(p1.size, p2.size, Ordering.natural().nullsLast()) \n .compare(p1.nrOfToppings, p2.nrOfToppings, Ordering.natural().nullsLast()) \n .compare(p1.name, p2.name, Ordering.natural().nullsLast()) \n .result(); \n */ \n } \n}); \n Collections.sort(pizzas, new Comparator<Pizza>() { \n @Override \n public int compare(Pizza p1, Pizza p2) { \n return new CompareToBuilder().append(p1.size, p2.size).append(p1.nrOfToppings, p2.nrOfToppings).append(p1.name, p2.name).toComparison(); \n } \n}); \n MultiComparator class MultiComparator<T> implements Comparator<T> {\n private final List<Comparator<T>> comparators;\n\n public MultiComparator(List<Comparator<? super T>> comparators) {\n this.comparators = comparators;\n }\n\n public MultiComparator(Comparator<? super T>... comparators) {\n this(Arrays.asList(comparators));\n }\n\n public int compare(T o1, T o2) {\n for (Comparator<T> c : comparators) {\n int result = c.compare(o1, o2);\n if (result != 0) {\n return result;\n }\n }\n return 0;\n }\n\n public static <T> void sort(List<T> list, Comparator<? super T>... comparators) {\n Collections.sort(list, new MultiComparator<T>(comparators));\n }\n}\n Collections.sort(list, ComparatorUtils.chainedComparator(comparators));\n"
},
{
"answer_id": 24386282,
"author": "Pradeep Singh",
"author_id": 3710964,
"author_profile": "https://Stackoverflow.com/users/3710964",
"pm_score": 2,
"selected": false,
"text": "//here threshold,buyRange,targetPercentage are three keys on that i have sorted my arraylist \nfinal Comparator<BasicDBObject> \n\n sortOrder = new Comparator<BasicDBObject>() {\n public int compare(BasicDBObject e1, BasicDBObject e2) {\n int threshold = new Double(e1.getDouble(\"threshold\"))\n .compareTo(new Double(e2.getDouble(\"threshold\")));\n if (threshold != 0)\n return threshold;\n\n int buyRange = new Double(e1.getDouble(\"buyRange\"))\n .compareTo(new Double(e2.getDouble(\"buyRange\")));\n if (buyRange != 0)\n return buyRange;\n\n return (new Double(e1.getDouble(\"targetPercentage\")) < new Double(\n e2.getDouble(\"targetPercentage\")) ? -1 : (new Double(\n e1.getDouble(\"targetPercentage\")) == new Double(\n e2.getDouble(\"targetPercentage\")) ? 0 : 1));\n }\n };\n Collections.sort(objectList, sortOrder);\n"
},
{
"answer_id": 25501226,
"author": "Display Name",
"author_id": 3978127,
"author_profile": "https://Stackoverflow.com/users/3978127",
"pm_score": 9,
"selected": false,
"text": "Comparator.comparing((Person p)->p.firstName)\n .thenComparing(p->p.lastName)\n .thenComparingInt(p->p.age);\n Comparator.comparing(Person::getFirstName)\n .thenComparing(Person::getLastName)\n .thenComparingInt(Person::getAge);\n @Override\npublic int compareTo(Person o){\n return Comparator.comparing(Person::getFirstName)\n .thenComparing(Person::getLastName)\n .thenComparingInt(Person::getAge)\n .compare(this, o);\n}\n"
},
{
"answer_id": 26143022,
"author": "Xeroiris",
"author_id": 4099068,
"author_profile": "https://Stackoverflow.com/users/4099068",
"pm_score": 4,
"selected": false,
"text": "import org.apache.commons.lang3.builder.CompareToBuilder;\n public int compare(Person a, Person b){\n\n return new CompareToBuilder()\n .append(a.getName(), b.getName())\n .append(a.getAddress(), b.getAddress())\n .toComparison();\n}\n"
},
{
"answer_id": 26865152,
"author": "Luke Machowski",
"author_id": 231860,
"author_profile": "https://Stackoverflow.com/users/231860",
"pm_score": 3,
"selected": false,
"text": ".ThenBy(...)\n .thenComparing(...)\n Comparator<Person> comparator = Comparator.comparing(person -> person.name);\n comparator = comparator.thenComparing(Comparator.comparing(person -> person.age));\n @Test\npublic void testChainedSorting()\n{\n // Create the collection of people:\n ArrayList<Person> people = new ArrayList<>();\n people.add(new Person(\"Dan\", 4));\n people.add(new Person(\"Andi\", 2));\n people.add(new Person(\"Bob\", 42));\n people.add(new Person(\"Debby\", 3));\n people.add(new Person(\"Bob\", 72));\n people.add(new Person(\"Barry\", 20));\n people.add(new Person(\"Cathy\", 40));\n people.add(new Person(\"Bob\", 40));\n people.add(new Person(\"Barry\", 50));\n\n // Define chained comparators:\n // Great article explaining this and how to make it even neater:\n // http://blog.jooq.org/2014/01/31/java-8-friday-goodies-lambdas-and-sorting/\n Comparator<Person> comparator = Comparator.comparing(person -> person.name);\n comparator = comparator.thenComparing(Comparator.comparing(person -> person.age));\n\n // Sort the stream:\n Stream<Person> personStream = people.stream().sorted(comparator);\n\n // Make sure that the output is as expected:\n List<Person> sortedPeople = personStream.collect(Collectors.toList());\n Assert.assertEquals(\"Andi\", sortedPeople.get(0).name); Assert.assertEquals(2, sortedPeople.get(0).age);\n Assert.assertEquals(\"Barry\", sortedPeople.get(1).name); Assert.assertEquals(20, sortedPeople.get(1).age);\n Assert.assertEquals(\"Barry\", sortedPeople.get(2).name); Assert.assertEquals(50, sortedPeople.get(2).age);\n Assert.assertEquals(\"Bob\", sortedPeople.get(3).name); Assert.assertEquals(40, sortedPeople.get(3).age);\n Assert.assertEquals(\"Bob\", sortedPeople.get(4).name); Assert.assertEquals(42, sortedPeople.get(4).age);\n Assert.assertEquals(\"Bob\", sortedPeople.get(5).name); Assert.assertEquals(72, sortedPeople.get(5).age);\n Assert.assertEquals(\"Cathy\", sortedPeople.get(6).name); Assert.assertEquals(40, sortedPeople.get(6).age);\n Assert.assertEquals(\"Dan\", sortedPeople.get(7).name); Assert.assertEquals(4, sortedPeople.get(7).age);\n Assert.assertEquals(\"Debby\", sortedPeople.get(8).name); Assert.assertEquals(3, sortedPeople.get(8).age);\n // Andi : 2\n // Barry : 20\n // Barry : 50\n // Bob : 40\n // Bob : 42\n // Bob : 72\n // Cathy : 40\n // Dan : 4\n // Debby : 3\n}\n\n/**\n * A person in our system.\n */\npublic static class Person\n{\n /**\n * Creates a new person.\n * @param name The name of the person.\n * @param age The age of the person.\n */\n public Person(String name, int age)\n {\n this.age = age;\n this.name = name;\n }\n\n /**\n * The name of the person.\n */\n public String name;\n\n /**\n * The age of the person.\n */\n public int age;\n\n @Override\n public String toString()\n {\n if (name == null) return super.toString();\n else return String.format(\"%s : %d\", this.name, this.age);\n }\n}\n"
},
{
"answer_id": 34179812,
"author": "vaquar khan",
"author_id": 4812170,
"author_profile": "https://Stackoverflow.com/users/4812170",
"pm_score": 0,
"selected": false,
"text": "import java.util.Arrays;\nimport java.util.Comparator;\nimport java.util.List;\n\n/**\n * This is a chained comparator that is used to sort a list by multiple\n * attributes by chaining a sequence of comparators of individual fields\n * together.\n *\n */\npublic class EmployeeChainedComparator implements Comparator<Employee> {\n\n private List<Comparator<Employee>> listComparators;\n\n @SafeVarargs\n public EmployeeChainedComparator(Comparator<Employee>... comparators) {\n this.listComparators = Arrays.asList(comparators);\n }\n\n @Override\n public int compare(Employee emp1, Employee emp2) {\n for (Comparator<Employee> comparator : listComparators) {\n int result = comparator.compare(emp1, emp2);\n if (result != 0) {\n return result;\n }\n }\n return 0;\n }\n}\n Collections.sort(listEmployees, new EmployeeChainedComparator(\n new EmployeeJobTitleComparator(),\n new EmployeeAgeComparator(),\n new EmployeeSalaryComparator())\n );\n"
},
{
"answer_id": 42936643,
"author": "Gerold Broser",
"author_id": 1744774,
"author_profile": "https://Stackoverflow.com/users/1744774",
"pm_score": 0,
"selected": false,
"text": "public int compareTo(Person other) {\n int f = firstName.compareTo(other.firstName);\n int l = lastName.compareTo(other.lastName);\n return f != 0 ? f : l != 0 ? l : Integer.compare(age, other.age);\n}\n"
},
{
"answer_id": 47435442,
"author": "Exodus",
"author_id": 8978420,
"author_profile": "https://Stackoverflow.com/users/8978420",
"pm_score": 0,
"selected": false,
"text": "public class Sample{\n\n String a=null;\n String b=null;\n\n public Sample(){\n a=\"s\";\n b=\"a\";\n }\n public Sample(String a,String b){\n this.a=a;\n this.b=b;\n }\n public static void main(String args[]){\n Sample f=new Sample(\"b\",\"12\");\n Sample s=new Sample(\"b\",\"12\");\n //will return true\n System.out.println((s.a.hashCode()+s.b.hashCode())==(f.a.hashCode()+f.b.hashCode()));\n\n //will return false\n Sample f=new Sample(\"b\",\"12\");\n Sample s=new Sample(\"b\",\"13\");\n System.out.println((s.a.hashCode()+s.b.hashCode())==(f.a.hashCode()+f.b.hashCode()));\n\n}\n"
},
{
"answer_id": 50194468,
"author": "Pawan",
"author_id": 8380642,
"author_profile": "https://Stackoverflow.com/users/8380642",
"pm_score": 3,
"selected": false,
"text": "//Following is the example in jdk 1.8\npackage com;\nimport java.util.ArrayList;\nimport java.util.Comparator;\nimport java.util.List;\n\nclass User {\n private String firstName;\n private String lastName;\n private Integer age;\n\n public Integer getAge() {\n return age;\n }\n\n public User setAge(Integer age) {\n this.age = age;\n return this;\n }\n\n public String getFirstName() {\n return firstName;\n }\n\n public User setFirstName(String firstName) {\n this.firstName = firstName;\n return this;\n }\n\n public String getLastName() {\n return lastName;\n }\n\n public User setLastName(String lastName) {\n this.lastName = lastName;\n return this;\n }\n\n}\n\npublic class MultiFieldsComparision {\n\n public static void main(String[] args) {\n List<User> users = new ArrayList<User>();\n\n User u1 = new User().setFirstName(\"Pawan\").setLastName(\"Singh\").setAge(38);\n User u2 = new User().setFirstName(\"Pawan\").setLastName(\"Payal\").setAge(37);\n User u3 = new User().setFirstName(\"Anuj\").setLastName(\"Kumar\").setAge(60);\n User u4 = new User().setFirstName(\"Anuj\").setLastName(\"Kumar\").setAge(43);\n User u5 = new User().setFirstName(\"Pawan\").setLastName(\"Chamoli\").setAge(44);\n User u6 = new User().setFirstName(\"Pawan\").setLastName(\"Singh\").setAge(5);\n\n users.add(u1);\n users.add(u2);\n users.add(u3);\n users.add(u4);\n users.add(u5);\n users.add(u6);\n\n System.out.println(\"****** Before Sorting ******\");\n\n users.forEach(user -> {\n System.out.println(user.getFirstName() + \" , \" + user.getLastName() + \" , \" + user.getAge());\n });\n\n System.out.println(\"****** Aftre Sorting ******\");\n\n users.sort(\n Comparator.comparing(User::getFirstName).thenComparing(User::getLastName).thenComparing(User::getAge));\n\n users.forEach(user -> {\n System.out.println(user.getFirstName() + \" , \" + user.getLastName() + \" , \" + user.getAge());\n });\n\n }\n\n}\n"
},
{
"answer_id": 59575149,
"author": "Sachchit Bansal",
"author_id": 2874585,
"author_profile": "https://Stackoverflow.com/users/2874585",
"pm_score": 2,
"selected": false,
"text": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\n\npublic class Person {\n\nprivate String firstName;\nprivate String lastName;\nprivate int age;\n\npublic String getFirstName() {\n return firstName;\n}\n\npublic void setFirstName(String firstName) {\n this.firstName = firstName;\n}\n\npublic String getLastName() {\n return lastName;\n}\n\npublic void setLastName(String lastName) {\n this.lastName = lastName;\n}\n\npublic int getAge() {\n return age;\n}\n\npublic void setAge(int age) {\n this.age = age;\n}\n\npublic Person(String firstName, String lastName, int age) {\n this.firstName = firstName;\n this.lastName = lastName;\n this.age = age;\n}\n\n\nstatic class PersonSortingComparator implements Comparator<Person> {\n\n @Override\n public int compare(Person person1, Person person2) {\n\n // for first name comparison\n int firstNameCompare = person1.getFirstName().compareTo(person2.getFirstName());\n\n // for last name comparison\n int lastNameCompare = person1.getLastName().compareTo(person2.getLastName());\n\n // for last name comparison\n int ageCompare = person1.getAge() - person2.getAge();\n\n // Now comparing\n if (firstNameCompare == 0) {\n if (lastNameCompare == 0) {\n return ageCompare;\n }\n return lastNameCompare;\n }\n return firstNameCompare;\n }\n}\n\npublic static void main(String[] args) {\n Person person1 = new Person(\"Ajay\", \"Kumar\", 27);\n Person person2 = new Person(\"Ajay\",\"Gupta\", 23);\n Person person3 = new Person(\"Ajay\",\"Kumar\", 22);\n\n\n ArrayList<Person> persons = new ArrayList<>();\n persons.add(person1);\n persons.add(person2);\n persons.add(person3);\n\n\n System.out.println(\"Before Sorting:\\n\");\n for (Person person : persons) {\n System.out.println(person.firstName + \" \" + person.lastName + \" \" + person.age);\n }\n\n Collections.sort(persons, new PersonSortingComparator());\n\n System.out.println(\"After Sorting:\\n\");\n for (Person person : persons) {\n System.out.println(person.firstName + \" \" + person.lastName + \" \" + person.age);\n }\n}\n\n}\n"
},
{
"answer_id": 65369206,
"author": "pallgeuer",
"author_id": 12235376,
"author_profile": "https://Stackoverflow.com/users/12235376",
"pm_score": 2,
"selected": false,
"text": "public class MyData {\n int id;\n boolean relevant;\n String name;\n float value;\n}\n public class MultiFieldComparator implements Comparator<MyData> {\n @Override\n public int compare(MyData dataA, MyData dataB) {\n int result;\n if((result = Integer.compare(dataA.id, dataB.id)) == 0 &&\n (result = Boolean.compare(dataA.relevant, dataB.relevant)) == 0 &&\n (result = dataA.name.compareTo(dataB.name)) == 0)\n result = Float.compare(dataA.value, dataB.value);\n return result;\n }\n}\n myDataList.sort((dataA, dataB) -> {\n int result;\n if((result = Integer.compare(dataA.id, dataB.id)) == 0 &&\n (result = Boolean.compare(dataA.relevant, dataB.relevant)) == 0 &&\n (result = dataA.name.compareTo(dataB.name)) == 0)\n result = Float.compare(dataA.value, dataB.value);\n return result;\n});\n"
},
{
"answer_id": 70686559,
"author": "Abhilash Ranjan",
"author_id": 1620446,
"author_profile": "https://Stackoverflow.com/users/1620446",
"pm_score": 2,
"selected": false,
"text": "public class Student {\nint id;\nString firstName;\nString lastName;\nString subject;\n\npublic Student(int id, String firstName, String lastName, String subject) {\n this.id = id;\n this.firstName = firstName;\n this.lastName = lastName;\n this.subject = subject;\n}\nenter code here\n 1. id->FirstName->LastName->Subject 2. Subject->id->FirstName->LastName public class TestComprator {\npublic static void main(String[] args) {\n Student s1= new Student(108, \"James\", \"Testo\", \"Physics\");\n Student s2= new Student(101, \"Fundu\", \"Barito\", \"Chem\");\n Student s3= new Student(105, \"Sindhu\", \"Sharan\", \"Math\");\n Student s4= new Student(98, \"Rechel\", \"Stephen\", \"Physics\");\n System.out.printf(\"----------id->FirstName->LastName->Subject-------------\");\n Arrays.asList(s1,s2,s3,s4).stream()\n .sorted(Comparator.comparing(Student::getId)\n .thenComparing(Student::getFirstName)\n .thenComparing(Student::getLastName)\n .thenComparing(Student::getSubject))\n .forEach(System.out::println);\n\n System.out.printf(\"----Subject->id->FirstName->LastName ------\\n\");\n Arrays.asList(s1,s2,s3,s4).stream()\n .sorted(Comparator. comparing(Student::getSubject)\n .thenComparing(Student::getId)\n .thenComparing(Student::getFirstName)\n .thenComparing(Student::getLastName)\n )\n .forEach(System.out::println);\n}\n `----------id->FirstName->LastName->Subject-------------\nStudent{id=98, firstName='Rechel', lastName='Stephen', subject='Physics'}\nStudent{id=101, firstName='Fundu', lastName='Barito', subject='Chem'}\nStudent{id=105, firstName='Sindhu', lastName='Sharan', subject='Math'}\nStudent{id=108, firstName='James', lastName='Testo', subject='Physics'}\n ----Subject->id->FirstName->LastName ------\nStudent{id=101, firstName='Fundu', lastName='Barito', subject='Chem'}\nStudent{id=105, firstName='Sindhu', lastName='Sharan', subject='Math'}\nStudent{id=98, firstName='Rechel', lastName='Stephen', subject='Physics'}\nStudent{id=108, firstName='James', lastName='Testo', subject='Physics'}\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24545/"
] |
369,515 | <p>I have a weird issue that only seems to be affecting IE 7. The web site is a 3.5 c# asp.net website that utilizes ajax and the ajax control toolkit deployed to a win 2003 server. Everything appears to be correct in the web.config. In fact, everything works perfectly in IE6 and Firefox 3. It is only in IE7 that I get the dreaded sys is undefined error.</p>
<p>Also, the site appears to be working fine for IE7 on a different installation of the same code. That server is running win 2003 with very similar setups.</p>
<p>Since this appears to be a server issue, are there any kind of settings that would prevent ajax-enabled sites from displaying properly in IE7?</p>
| [
{
"answer_id": 370106,
"author": "Strelok",
"author_id": 2788,
"author_profile": "https://Stackoverflow.com/users/2788",
"pm_score": 1,
"selected": false,
"text": "<add verb=\"GET,HEAD\"\n path=\"ScriptResource.axd\"\n type=\"System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"\n validate=\"false\"/>\n <httpHandlers>"
},
{
"answer_id": 3410251,
"author": "Henry D",
"author_id": 411332,
"author_profile": "https://Stackoverflow.com/users/411332",
"pm_score": 0,
"selected": false,
"text": "<system.web> <httpHandlers>\n <remove verb=\"*\" path=\"*.asmx\"/>\n <add verb=\"*\" path=\"*.asmx\" validate=\"false\" type=\"System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/>\n <add verb=\"*\" path=\"*_AppService.axd\" validate=\"false\" type=\"System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/>\n <add verb=\"GET,HEAD\" path=\"ScriptResource.axd\" type=\"System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" validate=\"false\"/>\n </httpHandlers>\n\n <httpModules>\n <add name=\"ScriptModule\" type=\"System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/>\n </httpModules>\n"
},
{
"answer_id": 5009788,
"author": "dm80",
"author_id": 331884,
"author_profile": "https://Stackoverflow.com/users/331884",
"pm_score": 0,
"selected": false,
"text": "<asp:ToolkitScriptManager>"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2849/"
] |
369,519 | <p>Is it better to use NOT or to use <> when comparing values in VBScript?<br>
is this:</p>
<pre><code>
If NOT value1 = value2 Then
</code></pre>
<p>or this:</p>
<pre><code>
If value1 <> value2 Then
</code></pre>
<p>better?<br></p>
<p>EDIT:
Here is my counterargument. <br>
When looking to logically negate a Boolean value you would use the NOT operator, so this is correct:</p>
<pre><code>
If NOT boolValue1 Then
</code></pre>
<p>and when a comparison is made in the case of the first example a Boolean value is returned. either the values are equal True, or they are not False. So using the NOT operator would be appropriate, because you are logically negating a Boolean value. <br></p>
<p>For readability placing the comparison in parenthesis would probably help. </p>
| [
{
"answer_id": 369525,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 7,
"selected": true,
"text": "<> Not ="
},
{
"answer_id": 369593,
"author": "hmcclungiii",
"author_id": 24333,
"author_profile": "https://Stackoverflow.com/users/24333",
"pm_score": 0,
"selected": false,
"text": "If NOT (value1 = value2)\n"
},
{
"answer_id": 48562449,
"author": "Regis Desrosiers",
"author_id": 6340652,
"author_profile": "https://Stackoverflow.com/users/6340652",
"pm_score": 2,
"selected": false,
"text": "StartTime = Timer\nFor x = 1 to 100000000\n If 4 <> 3 Then\n End if\nNext\nWScript.echo Timer-StartTime\n\nStartTime = Timer\nFor x = 1 to 100000000\n If Not (4 = 3) Then\n End if\nNext\nWScript.echo Timer-StartTime\n 4.783203\n5.552734\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38695/"
] |
369,543 | <p>I'm working on a small project in VB.Net where I get a input from a textbox, and need to verify that this is an e-email address.</p>
<p>I found this expression "^[_a-z0-9-]+(.[_a-z0-9-]+)<em>@[a-z0-9-]+(.[a-z0-9-]+)</em>(.[a-z]{2,4})$", but i cant find any way to test if it passes.</p>
<p>I want some code like: </p>
<pre><code>if not txtEmail.text = regexString then
something happens..
else
something else happens..
end if
</code></pre>
| [
{
"answer_id": 369554,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 6,
"selected": true,
"text": "System.Text.RegularExpressions.Regex Function IsEmail(Byval email as string) as boolean\n Static emailExpression As New Regex(\"^[_a-z0-9-]+(.[a-z0-9-]+)@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,4})$\")\n\n return emailExpression.IsMatch(email)\nEnd Function\n"
},
{
"answer_id": 369628,
"author": "Mick",
"author_id": 12458,
"author_profile": "https://Stackoverflow.com/users/12458",
"pm_score": -1,
"selected": false,
"text": "Dim FoundMatch As Boolean\nTry\n FoundMatch = Regex.IsMatch(txtEmail.text, \"\\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\\Z\", RegexOptions.IgnoreCase)\nCatch ex As ArgumentException\n 'Syntax error in the regular expression\nEnd Try\n\nIf Not FoundMatch Then\n Error = True\nElse\n Error = False\nEnd If\n"
},
{
"answer_id": 374811,
"author": "Jan Goyvaerts",
"author_id": 33358,
"author_profile": "https://Stackoverflow.com/users/33358",
"pm_score": 3,
"selected": false,
"text": "If Regex.IsMatch(SubjectString, \"regex\") Then\n Error = False\nElse\n Error = True\nEnd If\n"
},
{
"answer_id": 521890,
"author": "Rick",
"author_id": 45405,
"author_profile": "https://Stackoverflow.com/users/45405",
"pm_score": 3,
"selected": false,
"text": "try\n{\n MailAddress email = new MailAddress(txtEmail.Text);\n}\ncatch(FormatException fe)\n{\n // output error\n}\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41807/"
] |
369,558 | <p>I'm researching game development in Flash and Flex. I've downloaded the Flex Builder trial and have worked with older versions of Flash. I see that generally, Flex Builder is a developer's tool, and Flash is a designer's tool. It's not clear to me whether one is better suited to game development than the other, or if it's necessary to have both to effectively design games. To my mind, games are equal parts design/art and programming. Which tool is more commonly, or more intensively, used for game development?</p>
| [
{
"answer_id": 373666,
"author": "aaaidan",
"author_id": 26331,
"author_profile": "https://Stackoverflow.com/users/26331",
"pm_score": 3,
"selected": false,
"text": "Asset [Embed] public class Asset {\n\n [Embed(source=\"./assets/Enemies.swf\", symbol=\"asset.KohrAhMeleeShip\")]\n public static var KohrAhMeleeShip:Class;\n\n // etc.\n}\n var enemyFighter:EnemyFighter = new EnemyFighter( Asset.KohrAhMeleeShip );\naddChild(enemyFighter);\n Loader"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34796/"
] |
369,572 | <p>For some reason, when using two sums on a group by, i run into the error "invalid column name 'id'. When i only do one sum, it works as expected.</p>
<p>The following <strong>fails</strong> and throws the error:</p>
<pre><code>from pd in PrDetails.Where(_pd => _pd.PrId == 46)
group pd by new { pd.ProgramFund, pd.ProjectDetail.CostCenter, pd.ProjectDetail.Wbs }
into g
select new
{
g.Key.ProgramFund,
g.Key.CostCenter,
g.Key.Wbs,
CommittedTotal = g.Sum(_pd => _pd.PrDetailPrAmounts.Sum(_pa => _pa.CommittedAmount)),
OverheadTotal = g.Sum(_pd => _pd.PrDetailPrAmounts.Sum(_pa => _pa.OverheadAmount))
}
</code></pre>
<p>However, the following <strong>does</strong> work fine:</p>
<pre><code>from pd in PrDetails.Where(_pd => _pd.PrId == 46)
group pd by new { pd.ProgramFund, pd.ProjectDetail.CostCenter, pd.ProjectDetail.Wbs }
into g
select new
{
g.Key.ProgramFund,
g.Key.CostCenter,
g.Key.Wbs,
CommittedTotal = g.Sum(_pd => _pd.PrDetailPrAmounts.Sum(_pa => _pa.CommittedAmount))
}
</code></pre>
<p><strong>And also</strong>, when I get the overhead total, instead of the committed total, it works great:</p>
<pre><code>from pd in PrDetails.Where(_pd => _pd.PrId == 46)
group pd by new { pd.ProgramFund, pd.ProjectDetail.CostCenter, pd.ProjectDetail.Wbs }
into g
select new
{
g.Key.ProgramFund,
g.Key.CostCenter,
g.Key.Wbs,
OverheadTotal = g.Sum(_pd => _pd.PrDetailPrAmounts.Sum(_pa => _pa.OverheadAmount))
}
</code></pre>
<p>Why can't i get the committed total and overhead total at the same time?</p>
<p>I have our basic table structure below:</p>
<h2>PrDetails</h2>
<p>Id (int)<br>
PrId (int)<br>
ProgramFund (linq class)<br>
ProjectDetail (linq class) </p>
<h2>ProjectDetails</h2>
<p>Id (int)<br>
CostCenter (linq class)<br>
Wbs (linq class) </p>
<h2>PrAmounts</h2>
<p>Id (int)<br>
PrDetailId (int)<br>
CommittedAmount (decimal)<br>
OverheadAmount (decimal)</p>
| [
{
"answer_id": 369880,
"author": "Cameron MacFarland",
"author_id": 3820,
"author_profile": "https://Stackoverflow.com/users/3820",
"pm_score": 2,
"selected": true,
"text": "from pd in PrDetails.Where(_pd => _pd.PrId == 46)\ngroup pd by new { pd.ProgramFund, pd.ProjectDetail.CostCenter, pd.ProjectDetail.Wbs }\ninto g\nselect new\n{\n g.Key.ProgramFund,\n g.Key.CostCenter,\n g.Key.Wbs,\n CommittedTotal = g.Sum(_pd1 => _pd1.PrDetailPrAmounts.Sum(_pa1 => _pa1.CommittedAmount)),\n OverheadTotal = g.Sum(_pd2 => _pd2.PrDetailPrAmounts.Sum(_pa2 => _pa2.OverheadAmount))\n}\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5203/"
] |
369,573 | <p>I have a strongly typed user control ("partial") and I'd like to be able to pass it some additional information from its containing view. For example, I have view that's bound to a product class and i have a partial that also is strongly typed to that same model, but I also need to pass an additional parameter for imageSize to my partial. I'd like to be able to do something like this:</p>
<pre><code><% Html.RenderPartial("_ProductImage", ViewData.Model, new { imageSize = 100 }); %>
</code></pre>
<p>As far as I know there is no way to do this, but I'm hoping that someone smarter than me may have a solution ;)</p>
| [
{
"answer_id": 369584,
"author": "Craig Stuntz",
"author_id": 7714,
"author_profile": "https://Stackoverflow.com/users/7714",
"pm_score": 4,
"selected": true,
"text": "class PartialModel \n{\n public int ImageSize { get; set; }\n public ParentModelType ParentModel { get; set; }\n}\n <% Html.RenderPartial(\"_ProductImage\", \n new PartialModel() { ImageSize = 100, ParentModel = ViewData.Model }); %>\n"
},
{
"answer_id": 370592,
"author": "Todd Smith",
"author_id": 31624,
"author_profile": "https://Stackoverflow.com/users/31624",
"pm_score": 2,
"selected": false,
"text": "<% ViewData[\"imageSize\"] = 100; %>\n\n<% Html.RenderPartial(\"_ProductImage\"); %>\n"
},
{
"answer_id": 584752,
"author": "Simon_Weaver",
"author_id": 16940,
"author_profile": "https://Stackoverflow.com/users/16940",
"pm_score": 1,
"selected": false,
"text": "RenderPartial object data public class PartialControlModel<T> : ModelBase \n {\n public T ParentModel { get; set; }\n public object Data { get; set; }\n\n public PartialControlModel(T parentModel, object data) : base()\n {\n ParentModel = parentModel;\n Data = data;\n }\n }\n PartialControlModel public partial class ThumbnailPanel : \n ViewUserControl<PartialControlModel<GalleryModel>>\n <% Html.RenderPartial(\"ThumbnailPanel\", \nnew PartialControlModel<GalleryModel>(ViewData.Model, tag)); %>\n ViewData.Model.ParentModel.Images\n ViewData.Model.Data\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369573",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4541/"
] |
369,594 | <p>I have a WebBrowser control which is being instantiated dynamically from a background STA thread because the parent thread is a BackgroundWorker and has lots of other things to do.</p>
<p>The problem is that the Navigated event never fires, unless I pop a MessageBox.Show() in the method that told it to .Navigate(). I shall explain:</p>
<pre><code>ThreadStart ts = new ThreadStart(GetLandingPageContent_ChildThread);
Thread t = new Thread(ts);
t.SetApartmentState(ApartmentState.STA);
t.Name = "Mailbox Processor";
t.Start();
protected void GetLandingPageContent_ChildThread()
{
WebBrowser wb = new WebBrowser();
wb.Navigated += new WebBrowserNavigatedEventHandler(wb_Navigated);
wb.Navigate(_url);
MessageBox.Show("W00t");
}
protected void wb_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
WebBrowser wb = (WebBrowser)sender; // Breakpoint
HtmlDocument hDoc = wb.Document;
}
</code></pre>
<p>This works fine; but the messagebox will get in the way since this is an automation app. When I remove the MessageBox.Show(), the WebBrowser.Navigated event never fires. I've tried supplanting this line with a Thread.Sleep(), and by suspending the parent thread.</p>
<p>Once I get this out of the way, I intend to Suspend the parent thread while the WebBrowser is doing its job and find some way of passing the resulting HTML back to the parent thread so it can continue with further logic.</p>
<p><em>Why does it do this? How can I fix it?</em></p>
<p>If someone can provide me with a way to fetch the content of a web page, fill out some data, and return the content of the page on the other side of the submit button, all against a webserver that doesn't support POST verbs nor passing data via QueryString, I'll also accept that answer as this whole exercise will have been unneccessary.</p>
<hr>
<p><strong>Solution:</strong> I ended up just not using the BackgroundWorker and slave thread at all at the suggestion of the team architect... Though at the expense of responsiveness :(</p>
| [
{
"answer_id": 369623,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 3,
"selected": true,
"text": "WebBrowser WebClient"
},
{
"answer_id": 371347,
"author": "Rick",
"author_id": 45405,
"author_profile": "https://Stackoverflow.com/users/45405",
"pm_score": 1,
"selected": false,
"text": "wb.Visible = true;\nwb.Left = -wb.Width; // notice the minus sign\n"
},
{
"answer_id": 2933698,
"author": "Mike Kelley",
"author_id": 353400,
"author_profile": "https://Stackoverflow.com/users/353400",
"pm_score": 1,
"selected": false,
"text": "webBrowser1.Navigated += new WebBrowserNavigatedEventHandler(webBrowser1_Navigated);\n webBrowswer1_Navigated"
},
{
"answer_id": 10418741,
"author": "Fred",
"author_id": 1370649,
"author_profile": "https://Stackoverflow.com/users/1370649",
"pm_score": 0,
"selected": false,
"text": "Thread.SetApartmentState(ApartmentState.STA);"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11112/"
] |
369,595 | <p>I have found ASP.Net PageMethods very handy and easy to use, but I have just started developing using MVC and am not sure how to use them?</p>
<p>What is the equivalent of <code>PageMethods.MyFunction()</code> in MVC where MyFunction is a Controller action?</p>
<p>I know I can use the <code>Json</code> function to return a value, but how do I call the action from the client?</p>
| [
{
"answer_id": 369730,
"author": "Dan Esparza",
"author_id": 19020,
"author_profile": "https://Stackoverflow.com/users/19020",
"pm_score": 4,
"selected": true,
"text": "$.getJSON(\"/controller/action\", function(json)\n{\n alert(\"JSON Data: \" + json.users[3].name);\n});\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18107/"
] |
369,602 | <p>Is there an easy way to delete an element from an array using PHP, such that <code>foreach ($array)</code> no longer includes that element?</p>
<p>I thought that setting it to <code>null</code> would do it, but apparently it does not work.</p>
| [
{
"answer_id": 369608,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 13,
"selected": true,
"text": "unset() \\array_splice() \\array_search() \\array_search unset() unset() \\array_values() unset() $array = [0 => \"a\", 1 => \"b\", 2 => \"c\"];\nunset($array[1]);\n // ↑ Key which you want to delete\n [\n [0] => a\n [2] => c\n]\n \\array_splice() \\array_splice() \\array_values() \\array_splice() $array = [0 => \"a\", 1 => \"b\", 2 => \"c\"];\n\\array_splice($array, 1, 1);\n // ↑ Offset which you want to delete\n [\n [0] => a\n [1] => c\n]\n array_splice() unset() unset() \\array_splice() \\array_diff() \\array_diff_key() \\array_diff() \\array_diff() unset() $array = [0 => \"a\", 1 => \"b\", 2 => \"c\", 3 => \"c\"];\n$array = \\array_diff($array, [\"a\", \"c\"]);\n // └────────┘\n // Array values which you want to delete\n [\n [1] => b\n]\n \\array_diff_key() \\array_diff_key() $array = [0 => \"a\", 1 => \"b\", 2 => \"c\"];\n$array = \\array_diff_key($array, [0 => \"xy\", \"2\" => \"xy\"]);\n // ↑ ↑\n // Array keys which you want to delete\n [\n [1] => b\n]\n unset() \\array_splice() \\array_keys() \\array_filter() \\array_filter() $array = [0 => \"a\", 1 => \"b\", 2 => \"c\"];\n$array = \\array_filter($array, static function ($element) {\n return $element !== \"b\";\n // ↑\n // Array value which you want to delete\n});\n [\n [0] => a\n [1] => c\n]\n"
},
{
"answer_id": 369612,
"author": "Eran Galperin",
"author_id": 10585,
"author_profile": "https://Stackoverflow.com/users/10585",
"pm_score": 7,
"selected": false,
"text": "unset($array[$index]);\n"
},
{
"answer_id": 369761,
"author": "Stefan Gehrig",
"author_id": 11354,
"author_profile": "https://Stackoverflow.com/users/11354",
"pm_score": 10,
"selected": false,
"text": "unset() $array = array(0, 1, 2, 3);\nunset($array[2]);\nvar_dump($array);\n/* array(3) {\n [0]=>\n int(0)\n [1]=>\n int(1)\n [3]=>\n int(3)\n} */\n\n$array = array(0, 1, 2, 3);\narray_splice($array, 2, 1);\nvar_dump($array);\n/* array(3) {\n [0]=>\n int(0)\n [1]=>\n int(1)\n [2]=>\n int(3)\n} */\n array_splice() array_values() unset() $array = array(0, 1, 2, 3);\n\nunset($array[2]);\n$array = array_values($array);\nvar_dump($array);\n/* array(3) {\n [0]=>\n int(0)\n [1]=>\n int(1)\n [2]=>\n int(3)\n} */\n"
},
{
"answer_id": 3376355,
"author": "DefenestrationDay",
"author_id": 130230,
"author_profile": "https://Stackoverflow.com/users/130230",
"pm_score": 6,
"selected": false,
"text": "unset($array[\"elementName\"]);\n"
},
{
"answer_id": 6914929,
"author": "Marcel Cozma",
"author_id": 874961,
"author_profile": "https://Stackoverflow.com/users/874961",
"pm_score": 9,
"selected": false,
"text": " // Our initial array\n $arr = array(\"blue\", \"green\", \"red\", \"yellow\", \"green\", \"orange\", \"yellow\", \"indigo\", \"red\");\n print_r($arr);\n\n // Remove the elements who's values are yellow or red\n $arr = array_diff($arr, array(\"yellow\", \"red\"));\n print_r($arr);\n Array\n(\n [0] => blue\n [1] => green\n [2] => red\n [3] => yellow\n [4] => green\n [5] => orange\n [6] => yellow\n [7] => indigo\n [8] => red\n)\n\nArray\n(\n [0] => blue\n [1] => green\n [4] => green\n [5] => orange\n [7] => indigo\n)\n $arr = array_merge(array_diff($arr, array(\"yellow\", \"red\")));\nprint_r($arr);\n Array\n(\n [0] => blue\n [1] => green\n [2] => green\n [3] => orange\n [4] => indigo\n)\n"
},
{
"answer_id": 8135667,
"author": "liamvictor",
"author_id": 7278,
"author_profile": "https://Stackoverflow.com/users/7278",
"pm_score": 8,
"selected": false,
"text": "$key = array_search($needle, $array);\nif ($key !== false) {\n unset($array[$key]);\n}\n"
},
{
"answer_id": 13561058,
"author": "Robin Nixon",
"author_id": 1081335,
"author_profile": "https://Stackoverflow.com/users/1081335",
"pm_score": 6,
"selected": false,
"text": "$my_array = array_diff($my_array, array('Value_to_remove'));\n $my_array = array('Andy', 'Bertha', 'Charles', 'Diana');\necho sizeof($my_array) . \"\\n\";\n$my_array = array_diff($my_array, array('Charles'));\necho sizeof($my_array);\n 4\n3\n"
},
{
"answer_id": 16605134,
"author": "Sunil Kumar Sain",
"author_id": 2282117,
"author_profile": "https://Stackoverflow.com/users/2282117",
"pm_score": 3,
"selected": false,
"text": "$arr = array('orange', 'banana', 'apple', 'raspberry');\n$result = array_pop($arr);\nprint_r($result);\n"
},
{
"answer_id": 17037318,
"author": "Saurabh Chandra Patel",
"author_id": 1371778,
"author_profile": "https://Stackoverflow.com/users/1371778",
"pm_score": 5,
"selected": false,
"text": "<?php\n $stack = [\"fruit1\", \"fruit2\", \"fruit3\", \"fruit4\"];\n $fruit = array_shift($stack);\n print_r($stack);\n\n echo $fruit;\n?>\n [\n [0] => fruit2\n [1] => fruit3\n [2] => fruit4\n]\n\nfruit1\n"
},
{
"answer_id": 17890207,
"author": "Ankit Aggarwal",
"author_id": 1779217,
"author_profile": "https://Stackoverflow.com/users/1779217",
"pm_score": 4,
"selected": false,
"text": "unset() unset() unset() unset() <?php\n function destroy_foo()\n {\n global $foo;\n unset($foo);\n }\n\n $foo = 'bar';\n destroy_foo();\n echo $foo;\n?>\n unset() <?php\n function foo()\n {\n unset($GLOBALS['bar']);\n }\n\n $bar = \"something\";\n foo();\n?>\n"
},
{
"answer_id": 18347927,
"author": "Oxydel",
"author_id": 1758435,
"author_profile": "https://Stackoverflow.com/users/1758435",
"pm_score": 3,
"selected": false,
"text": "class obj {\n protected $fields = array('field1','field2');\n protected $field1 = array();\n protected $field2 = array();\n protected loadfields(){}\n // This will load the $field1 and $field2 with rows of data for the column they describe\n protected function clearFields($num){\n foreach($fields as $field) {\n unset($this->$field[$num]);\n // This did not work the line below worked\n unset($this->{$field}[$num]); // You have to resolve $field first using {}\n }\n }\n}\n $fields"
},
{
"answer_id": 30792476,
"author": "Tebe",
"author_id": 758158,
"author_profile": "https://Stackoverflow.com/users/758158",
"pm_score": 3,
"selected": false,
"text": "Array\n(\n [user_id] => 193\n [storage] => 5\n)\n storage unset($attributes['storage']);\n$attributes = array_filter($attributes);\n Array\n(\n [user_id] => 193\n)\n"
},
{
"answer_id": 31502899,
"author": "KTAnj",
"author_id": 2142760,
"author_profile": "https://Stackoverflow.com/users/2142760",
"pm_score": 5,
"selected": false,
"text": "unset() $array1 = array('A', 'B', 'C', 'D', 'E');\nunset($array1[2]); // Delete known index(2) value from array\nvar_dump($array1);\n array(4) {\n [0]=>\n string(1) \"A\"\n [1]=>\n string(1) \"B\"\n [3]=>\n string(1) \"D\"\n [4]=>\n string(1) \"E\"\n}\n $array1 = array_values($array1);\nvar_dump($array1);\n array(4) {\n [0]=>\n string(1) \"A\"\n [1]=>\n string(1) \"B\"\n [2]=>\n string(1) \"D\"\n [3]=>\n string(1) \"E\"\n}\n mixed array_pop(array &$array) $stack = array(\"orange\", \"banana\", \"apple\", \"raspberry\");\n$last_fruit = array_pop($stack);\nprint_r($stack);\nprint_r('Last Fruit:'.$last_fruit); // Last element of the array\n Array\n(\n [0] => orange\n [1] => banana\n [2] => apple\n)\nLast Fruit: raspberry\n mixed array_shift ( array &$array ) $color = array(\"a\" => \"red\", \"b\" => \"green\" , \"c\" => \"blue\");\n$first_color = array_shift($color);\nprint_r ($color);\nprint_r ('First Color: '.$first_color);\n Array\n(\n [b] => green\n [c] => blue\n)\nFirst Color: red\n"
},
{
"answer_id": 34993411,
"author": "msvairam",
"author_id": 2428333,
"author_profile": "https://Stackoverflow.com/users/2428333",
"pm_score": 4,
"selected": false,
"text": "unset() $Array = array(\"test1\", \"test2\", \"test3\", \"test3\");\n\nunset($Array[2]);\n array_pop() $Array = array(\"test1\", \"test2\", \"test3\", \"test3\");\n\narray_pop($Array);\n array_splice() $Array = array(\"test1\", \"test2\", \"test3\", \"test3\");\n\narray_splice($Array,1,2);\n array_shift() $Array = array(\"test1\", \"test2\", \"test3\", \"test3\");\n\narray_shift($Array);\n"
},
{
"answer_id": 35471212,
"author": "spyle",
"author_id": 326979,
"author_profile": "https://Stackoverflow.com/users/326979",
"pm_score": 5,
"selected": false,
"text": "array_filter() $array = [\n ['x'=>1,'y'=>2,'z'=>3], \n ['x'=>2,'y'=>4,'z'=>6], \n ['x'=>3,'y'=>6,'z'=>9]\n];\n\n$results = array_filter($array, function($value) {\n return $value['x'] > 2; \n}); //=> [['x'=>3,'y'=>6,z=>'9']]\n"
},
{
"answer_id": 35947723,
"author": "John Slegers",
"author_id": 1946501,
"author_profile": "https://Stackoverflow.com/users/1946501",
"pm_score": 5,
"selected": false,
"text": "unset $arr = array('a' => 1, 'b' => 2, 'c' => 3);\nunset($arr['b']);\n\n// RESULT: array('a' => 1, 'c' => 3)\n array_splice $arr = array(1, 2, 3);\narray_splice($arr, 1, 1);\n\n// RESULT: array(0 => 1, 1 => 3)\n unset $arr = array(1, 2, 3);\nunset($arr[1]);\n\n// RESULT: array(0 => 1, 2 => 3)\n"
},
{
"answer_id": 36377356,
"author": "Gigoland",
"author_id": 2467348,
"author_profile": "https://Stackoverflow.com/users/2467348",
"pm_score": 4,
"selected": false,
"text": "// Remove by value\nfunction removeFromArr($arr, $val)\n{\n unset($arr[array_search($val, $arr)]);\n return array_values($arr);\n}\n"
},
{
"answer_id": 36755169,
"author": "Simon",
"author_id": 1226018,
"author_profile": "https://Stackoverflow.com/users/1226018",
"pm_score": 5,
"selected": false,
"text": "$my_array = array(\n \"key1\" => \"value 1\",\n \"key2\" => \"value 2\",\n \"key3\" => \"value 3\",\n \"key4\" => \"value 4\",\n \"key5\" => \"value 5\",\n);\n\n$to_remove = array(\"key2\", \"key4\");\n\n$result = array_diff_key($my_array, array_flip($to_remove));\n\nprint_r($result);\n Array ( [key1] => value 1 [key3] => value 3 [key5] => value 5 ) \n"
},
{
"answer_id": 38979047,
"author": "Umar Farooque Khan",
"author_id": 4569116,
"author_profile": "https://Stackoverflow.com/users/4569116",
"pm_score": 3,
"selected": false,
"text": "<?php\n // If you want to remove a particular array element use this method\n $my_array = array(\"key1\"=>\"value 1\", \"key2\"=>\"value 2\", \"key3\"=>\"value 3\");\n\n print_r($my_array);\n if (array_key_exists(\"key1\", $my_array)) {\n unset($my_array['key1']);\n print_r($my_array);\n }\n else {\n echo \"Key does not exist\";\n }\n?>\n\n<?php\n //To remove first array element\n $my_array = array(\"key1\"=>\"value 1\", \"key2\"=>\"value 2\", \"key3\"=>\"value 3\");\n print_r($my_array);\n $new_array = array_slice($my_array, 1);\n print_r($new_array);\n?>\n\n\n<?php\n echo \"<br/> \";\n // To remove first array element to length\n // starts from first and remove two element\n $my_array = array(\"key1\"=>\"value 1\", \"key2\"=>\"value 2\", \"key3\"=>\"value 3\");\n print_r($my_array);\n $new_array = array_slice($my_array, 1, 2);\n print_r($new_array);\n?>\n Array ( [key1] => value 1 [key2] => value 2 [key3] =>\n value 3 ) Array ( [key2] => value 2 [key3] => value 3 )\n Array ( [key1] => value 1 [key2] => value 2 [key3] => value 3 )\n Array ( [key2] => value 2 [key3] => value 3 )\n Array ( [key1] => value 1 [key2] => value 2 [key3] => value 3 )\n Array ( [key2] => value 2 [key3] => value 3 )\n"
},
{
"answer_id": 46362557,
"author": "MahdiY",
"author_id": 2302051,
"author_profile": "https://Stackoverflow.com/users/2302051",
"pm_score": 3,
"selected": false,
"text": "unset $a = array(\n 'salam',\n '10',\n 1\n);\n\nunset($a[1]);\n\nprint_r($a);\n\n/*\n\n Output:\n\n Array\n (\n [0] => salam\n [2] => 1\n )\n\n*/\n array_search $a = array(\n 'salam',\n '10',\n 1\n);\n\n$key = array_search(10, $a);\n\nif ($key !== false) {\n unset($a[$key]);\n}\n\nprint_r($a);\n\n/*\n\n Output:\n\n Array\n (\n [0] => salam\n [2] => 1\n )\n\n*/\n"
},
{
"answer_id": 47688922,
"author": "Kristoffer Bohmann",
"author_id": 169224,
"author_profile": "https://Stackoverflow.com/users/169224",
"pm_score": 3,
"selected": false,
"text": "unset() unset() // Delete multiple, noncontiguous elements from an array\n$array = [ 'foo', 'bar', 'baz', 'quz' ];\nunset( $array[2], $array[3] );\nprint_r($array);\n// Output: [ 'foo', 'bar' ]\n $array = range(0,5);\n$remove = [1,2];\n$array = unset( $remove ); // FAILS: \"unexpected 'unset'\"\nprint_r($array);\n $array = range(0,5);\n$remove = [1,2];\nforeach ($remove as $k=>$v) {\n unset($array[$v]);\n}\nprint_r($array);\n// Output: [ 0, 3, 4, 5 ]\n $array1 = range(1,10);\nforeach ($array1 as $v) {\n // Remove all even integers from the array\n if( $v % 2 ) {\n $array2[] = $v;\n }\n}\nprint_r($array2);\n// Output: [ 1, 3, 5, 7, 9 ];\n $array1 = [ 'foo', '_bar', 'baz' ];\nforeach ($array1 as $v) {\n // Remove all strings beginning with underscore\n if( strpos($v,'_')===false ) {\n $array2[] = $v;\n }\n}\nprint_r($array2);\n// Output: [ 'foo', 'baz' ]\n"
},
{
"answer_id": 48499831,
"author": "Abdur Rehman",
"author_id": 3704489,
"author_profile": "https://Stackoverflow.com/users/3704489",
"pm_score": 4,
"selected": false,
"text": "unset($array[3]);\nunset($array['foo']);\n unset($array[3], $array[5]);\nunset($array['foo'], $array['bar']);\n array_splice($array, $offset, $length);\n $array[3] = $array['foo'] = '';\n This doesn't exist anymore, This still exists, but its value is the empty string. unset($products['XL1000']);\n $products['XL1000'] = 0;\n // Create a \"numeric\" array\n$animals = array('ant', 'bee', 'cat', 'dog', 'elk', 'fox');\nprint $animals[1]; // Prints 'bee'\nprint $animals[2]; // Prints 'cat'\ncount($animals); // Returns 6\n\n// unset()\nunset($animals[1]); // Removes element $animals[1] = 'bee'\nprint $animals[1]; // Prints '' and throws an E_NOTICE error\nprint $animals[2]; // Still prints 'cat'\ncount($animals); // Returns 5, even though $array[5] is 'fox'\n\n// Add a new element\n$animals[ ] = 'gnu'; // Add a new element (not Unix)\nprint $animals[1]; // Prints '', still empty\nprint $animals[6]; // Prints 'gnu', this is where 'gnu' ended up\ncount($animals); // Returns 6\n\n// Assign ''\n$animals[2] = ''; // Zero out value\nprint $animals[2]; // Prints ''\ncount($animals); // Returns 6, count does not decrease\n $animals = array_values($animals);\n // Create a \"numeric\" array\n$animals = array('ant', 'bee', 'cat', 'dog', 'elk', 'fox');\narray_splice($animals, 2, 2);\nprint_r($animals);\nArray\n(\n [0] => ant\n [1] => bee\n [2] => elk\n [3] => fox\n)\n"
},
{
"answer_id": 52826684,
"author": "Nabi K.A.Z.",
"author_id": 1407491,
"author_profile": "https://Stackoverflow.com/users/1407491",
"pm_score": 3,
"selected": false,
"text": "// 1 is the index of the first object to get\n// NULL to get everything until the end\n// true to preserve keys\n$array = array_slice($array, 1, null, true);\n // Rewinds the array's internal pointer to the first element\n// and returns the value of the first array element.\n$value = reset($array);\n// Returns the index element of the current array position\n$key = key($array);\nunset($array[$key]);\n $array = array(10 => \"a\", 20 => \"b\", 30 => \"c\");\n array(2) {\n [20]=>\n string(1) \"b\"\n [30]=>\n string(1) \"c\"\n}\n"
},
{
"answer_id": 56275213,
"author": "Ahmad Mobaraki",
"author_id": 5458806,
"author_profile": "https://Stackoverflow.com/users/5458806",
"pm_score": 5,
"selected": false,
"text": "$arr = ['a', 'b', 'c'];\n$index = 0; \nunset($arr[$index]); // $arr = ['b', 'c']\n $arr = ['a', 'b', 'c'];\n\n// search the value to find index\n// Notice! this will only find the first occurrence of value\n$index = array_search('a', $arr);\n\nif($index !== false){\n unset($arr[$index]); // $arr = ['b', 'c']\n}\n if index unset()"
},
{
"answer_id": 56541490,
"author": "Sam Tigle",
"author_id": 8542816,
"author_profile": "https://Stackoverflow.com/users/8542816",
"pm_score": 3,
"selected": false,
"text": "if(in_array($object,$array)) unset($array[array_search($object,$array)]);\n unset($array[array_search($object,$array)]);\n <?php\nclass Foo\n{\n public $id;\n public $name;\n}\n\n$foo1 = new Foo();\n$foo1->id = 1;\n$foo1->name = 'Name1';\n\n$foo2 = new Foo();\n$foo2->id = 2;\n$foo2->name = 'Name2';\n\n$foo3 = new Foo();\n$foo3->id = 3;\n$foo3->name = 'Name3';\n\n\n$array = array($foo1,$foo2,$foo3);\nunset($array[array_search($foo2,$array)]);\n\necho '<pre>';\nvar_dump($array);\necho '</pre>';\n?>\n array(2) {\n[0]=>\n object(Foo)#1 (2) {\n [\"id\"]=>\n int(1)\n [\"name\"]=>\n string(5) \"Name1\"\n }\n[2]=>\n object(Foo)#3 (2) {\n [\"id\"]=>\n int(3)\n [\"name\"]=>\n string(5) \"Name3\"\n }\n}\n"
},
{
"answer_id": 64337258,
"author": "Jed Lynch",
"author_id": 1718887,
"author_profile": "https://Stackoverflow.com/users/1718887",
"pm_score": 1,
"selected": false,
"text": "$arr = [1,2,2,3];\n\nforeach($arr as $i => $n){\n $b = array_diff($arr,[$n]);\n echo \"\\n\".json_encode($b);\n}\n [2,2,3]\n[1,3]\n[1,2,2] \n $arr = [1,2,3];\n\nforeach($arr as $i => $n){\n $b = array_merge(array_slice($arr,0,$i),array_slice($arr,$i+1));\n echo \"\\n\".json_encode($b);\n}\n\nResults...\n\n[2,3];\n[1,3];\n[1,2];\n $arr = [1,2,2,3];\n//$arr = ['a'=>'z','b'=>'y','c'=>'x','d'=>'w'];\nforeach($arr as $key => $n){\n $b = array_diff_uassoc($arr, [$key=>$n], function($a,$b) {\n if($a != $b){\n return 1;\n }\n });\n echo \"\\n\".json_encode($b);\n} \n [2,2,3];\n[1,2,3];\n[1,2,2];\n\n['b'=>'y','c'=>'x','d'=>'w'];\n['a'=>'z','c'=>'x','d'=>'w'];\n['a'=>'z','b'=>'y','d'=>'w'];\n['a'=>'z','b'=>'y','c'=>'x'];\n"
},
{
"answer_id": 73872491,
"author": "Muhammad Ali Shah",
"author_id": 19907088,
"author_profile": "https://Stackoverflow.com/users/19907088",
"pm_score": 1,
"selected": false,
"text": "<?php\n <?php \n$animals= array(\n \n 'cat', // [0]\n 'dog', // [1]\n 'cow' // [2]\n \n);\n unset($animals1[1]); \n var_dump($danimals1);\n $newarray = array_values($animals1);\n \n var_dump($newarray);\n ?>\n"
},
{
"answer_id": 74675442,
"author": "odnualam",
"author_id": 10875688,
"author_profile": "https://Stackoverflow.com/users/10875688",
"pm_score": 0,
"selected": false,
"text": "$array = array(\"foo\" => \"bar\", \"baz\" => \"qux\");\n\n// Delete the element with the key \"foo\"\nunset($array[\"foo\"]);\n\n// Reindex the array\n$array = array_values($array);\n\n// Use the foreach loop\nforeach ($array as $key => $value) {\n// Do something with each element\n}\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11522/"
] |
369,626 | <p>I'm in a situation where I have the class "progress" - trouble is that I'm interested in incorporating some open source that also has the class "progress". I remember very vaguely some reference to an app that's able to inspect the various files in a development for a given class name ... and either return it ... or change it. Have you experience of this?</p>
<p>thanks</p>
| [
{
"answer_id": 369638,
"author": "JW.",
"author_id": 4321,
"author_profile": "https://Stackoverflow.com/users/4321",
"pm_score": 0,
"selected": false,
"text": "$name = \"prog\";\n$name .= \"ress\";\n$cls = new $name();\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
369,636 | <p>I have a <a href="http://en.wikipedia.org/wiki/Pseudorandom_number_generator" rel="nofollow noreferrer">pseudorandom number generator</a> (PRNG) with nice properties which uses six <code>UInt32</code>s as state. I need to come up with a reasonable way to seed it. Two obvious possibilities are: 1) generate six random numbers using <code>System.Random</code> and use them as seeds; 2) generate two <code>GUID</code>s with <code>Guid.NewGuid()</code>. Which would be better?</p>
<p>I do <em>not</em> need cryptographic security.</p>
| [
{
"answer_id": 369646,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 3,
"selected": true,
"text": "UInt32 Random Next() Next() Next() Random new Random()"
},
{
"answer_id": 14943768,
"author": "tvwxyz",
"author_id": 1356618,
"author_profile": "https://Stackoverflow.com/users/1356618",
"pm_score": 0,
"selected": false,
"text": "(UInt32)Math.Pow(System.DateTime.Now.TimeOfDay.TotalMilliseconds, 11.0 / 7.0)\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9204/"
] |
369,637 | <p>is there an easy way of importing data from a mysql/odbc datasource into an excel spreadsheet? </p>
<p>The user should be able to select some values from drop downs (e..g date range, branch name etc.) and the values from the dropdown should be used to populate (prepared) SQL statements. The results should be displayed in the Excel file. </p>
<p>Ideally there would be a "save snapshot" menu item that would convert the dynamic excel file (with sql statements saved) as a static excel file thus reducing the exposure of internals (e.g. sql) to external ressources.</p>
<p>Thanks</p>
| [
{
"answer_id": 369674,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 0,
"selected": false,
"text": "Set cn = CreateObject(\"ADODB.Connection\")\nSet rs = CreateObject(\"ADODB.Recordset\")\n\nstrCon = \"Driver={MySQL ODBC 3.51 Driver};Server=localhost;Database=MyDB;\" _\n& \"User=UName;Password=PWord;Option=3;\"\n\n\ncn.Open strCon\n\nstrSQL = \"SELECT * FROM Members\"\n\nrs.Open strSQL, cn\n\nWorksheets(3).Cells(2, 1).CopyFromRecordset rs\n"
},
{
"answer_id": 3182291,
"author": "ErikE",
"author_id": 57611,
"author_profile": "https://Stackoverflow.com/users/57611",
"pm_score": 0,
"selected": false,
"text": "With AWorksheet.QueryTables.Add( _\n Connection:=\"ODBC;Driver=MySQL ODBC 5.1 Driver;Port=3306;Server=mysqlservername;Database=snort;User=username;Password=password;Option=3;\"\n Destination:=AWorksheet.Range(AWorksheet.Cells(1, 1), AWorksheet.Cells(1, 15)) _\n )\n\n .CommandText = \"SELECT Something FROM Somewhere\"\n .Name = \"Name\"\n .FieldNames = True\n .RowNumbers = False\n .FillAdjacentFormulas = False\n .PreserveFormatting = True\n .RefreshOnFileOpen = False\n .BackgroundQuery = True\n .RefreshStyle = xlOverwriteCells\n .SavePassword = False\n .SaveData = True\n .AdjustColumnWidth = False\n .RefreshPeriod = 0\n .PreserveColumnInfo = True\n .Refresh BackgroundQuery:=False\n .Delete\nEnd With\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
369,639 | <p>Is there anything I can add to <code>pom.xml</code> that will copy the generated <code>.war</code> file from the <code>target</code> directory to my Tomcat's <code>webapps</code> directory?</p>
| [
{
"answer_id": 372470,
"author": "sal",
"author_id": 13753,
"author_profile": "https://Stackoverflow.com/users/13753",
"pm_score": 2,
"selected": false,
"text": "<build>\n ....\n <plugins>\n <plugin>\n <artifactId>maven-antrun-plugin</artifactId>\n <executions>\n <execution>\n <phase>package</phase>\n <configuration>\n <tasks>\n <!-- Ant copy tasks go here -->\n </tasks>\n </configuration>\n <goals>\n <goal>run</goal>\n </goals>\n </execution>\n </executions>\n </plugin>\n </plugins>\n </build>\n"
},
{
"answer_id": 535551,
"author": "Clay",
"author_id": 37104,
"author_profile": "https://Stackoverflow.com/users/37104",
"pm_score": 3,
"selected": false,
"text": "<Context path=\"\" docBase=\"/path/to/target/exploded\">\n...\n</Context>\n"
},
{
"answer_id": 4966805,
"author": "koszu28",
"author_id": 612710,
"author_profile": "https://Stackoverflow.com/users/612710",
"pm_score": 6,
"selected": false,
"text": "<build>\n <plugins>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-war-plugin</artifactId>\n <version>3.2.1</version>\n <configuration>\n <outputDirectory><!-- Tomcat webapps location--></outputDirectory>\n <!-- Example of Tomcat webapps location :D:\\tomcat\\webapps\\ -->\n </configuration>\n </plugin>\n </plugins>\n</build>\n pom.xml mvn package mvn war:war"
},
{
"answer_id": 16951394,
"author": "Aled Evans",
"author_id": 2426437,
"author_profile": "https://Stackoverflow.com/users/2426437",
"pm_score": 3,
"selected": false,
"text": " <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-war-plugin</artifactId>\n <version>2.3</version>\n <configuration>\n <warName>${name}</warName>\n <outputDirectory>C:\\Tomcat7\\webapps</outputDirectory>\n </configuration>\n </plugin>\n"
},
{
"answer_id": 41093369,
"author": "GrabNewTech",
"author_id": 2295676,
"author_profile": "https://Stackoverflow.com/users/2295676",
"pm_score": 2,
"selected": false,
"text": "</project>\n ........ \n <build>\n <finalName>HelloWorld1</finalName>\n <plugins>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId> \n <artifactId>maven-war-plugin</artifactId>\n <configuration>\n <outputDirectory>C:\\Program Files (x86)\\apache-tomcat-8.5.8\\webapps\\</outputDirectory>\n </configuration>\n </plugin>\n </plugins>\n </build>\n</project>\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33178/"
] |
369,678 | <p>I'm looking for a reliable design for handling assignments that have asynchronous requests involved. To further clarify, I have a class which handles Data Management. It is a singleton and contains a lot of top level data for me which is used throughout my iPhone application.</p>
<p>A view controller might do something such as the following:</p>
<pre><code>users = [MySingleton sharedInstance].users;
</code></pre>
<p>MySingleton will then override the synthesized users getter and see if it is set. If it is not set, it will speak to a Connection Manager (a wrapper for NSURLConnection and its delegate methods) which fires off an asynchronous request, and this is where problems begin. I cannot guarantee when "users" will be available. I could change the request to synchronous, but that will directly effect user experience, especially in a mobile environment where bandwidth is limited already.</p>
<p>I need to be able to at some point, have some kind of locking/synchronization code going on in my getter that doesn't return users until it is available or is nil. </p>
<p>Once the NSURLConnection has the data available, it needs to callback something/somewhere with a response object and let the getter know the data is available.. whether it's failed or succeeded.</p>
<p>Any suggestions on handling this?</p>
| [
{
"answer_id": 370368,
"author": "amrox",
"author_id": 4468,
"author_profile": "https://Stackoverflow.com/users/4468",
"pm_score": 2,
"selected": false,
"text": "- (id)getUsersAndNotifyObject:(id)object selector:(SEL)selector\n // register observer first so you don't miss an update\n[[MySingleton sharedInstance] addObserver:self\n forKeyPath:@\"users\"\n options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld)\n context:&kvo_users_context];\n users = [MySingleton sharedInstance].users;\n\n // implement appropriate observeValueForKeyPath:ofObject:change:context: method\n [[NSNotificationCenter defaultCenter] addObserver:self\n selector:@selector(sharedDataChanged:)\n name:MySingletonDataUpdatedNotification\n object:[MySingletonDataUpdatedNotification sharedInstance]];\n users = [MySingleton sharedInstance].users;\n\n // implement appropriate sharedDataChanged: method\n"
},
{
"answer_id": 1071883,
"author": "Luke Redpath",
"author_id": 110300,
"author_profile": "https://Stackoverflow.com/users/110300",
"pm_score": 0,
"selected": false,
"text": "users = [MyDataFactory getUsers];\n getUsers Recipe RecipeRepository @interface RecipeRepository {}\n- (void)initWithDelegate:(id)aDelegate;\n- (void)findAllRecipes;\n- (void)findRecipeById:(NSUInteger)anId;\n@end\n @protocol RepositoryDelegateProtocol\n- (void)repository:(id)repository didRetrieveEntityCollection:(NSArray *)collection;\n- (void)repository:(id)repository didRetrieveEntity:(id)entity;\n@end\n XXXRepository EntityRepository - (void)viewDidLoad \n{\n self.users = [MySingleton getUsers];\n [self.view setNeedsDisplay];\n}\n - (void)viewDidLoad \n{\n if(self.repository == nil) { // just some simple lazy loading, we only need one repository instance\n self.repository = [[[RecipeRepository alloc] initWithDelegate:self] autorelease];\n }\n [self.repository findAllRecipes];\n}\n\n- (void)repository:(id)repository didRetrieveEntityCollection:(NSArray *)collection;\n{\n self.users = collection;\n [self.view setNeedsDisplay];\n}\n @protocol RepositoryDelegateProtocol\n- (void)repositoryWillLoadEntities:(id)repository;\n@end\n\n// in your controller\n\n- (void)repositoryWillLoadEntities:(id)repository;\n{\n [self showLoadingView]; // etc.\n}\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369678",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40882/"
] |
369,697 | <p>I'm looking for a command line to remove all view-private files and directories from a ClearCase view on Windows. I have Cygwin available as well.</p>
<p>The script available at <a href="http://www.ibm.com/developerworks/rational/library/4687.html" rel="noreferrer">this article</a> is not quite what I want, since I'm working with a large number of files and want to delete them all without having to select each one.</p>
| [
{
"answer_id": 369704,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 2,
"selected": false,
"text": "ct lsprivate | xargs rm\n"
},
{
"answer_id": 369713,
"author": "mbyrne215",
"author_id": 5241,
"author_profile": "https://Stackoverflow.com/users/5241",
"pm_score": 1,
"selected": false,
"text": "cleartool ls -recurse -view_only | sed -e 's:\\\\:/:g' | xargs rm -r\n"
},
{
"answer_id": 369952,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 5,
"selected": false,
"text": "ct lsprivate ct ls -rec -view_only ct lsprivate for /F \"usebackq delims=\" %i in (`cleartool ls -r ^| find /V \"Rule:\" ^| find /V \"hijacked\" ^| find /V \"eclipsed\" ^| find /V \"-->\"`) do @echo \"%i\" @echo \"%i\" del /F \"%i\" rmdir /S /Q \"%i\" del /F \"%i\""
},
{
"answer_id": 372754,
"author": "Mr. Muskrat",
"author_id": 2657951,
"author_profile": "https://Stackoverflow.com/users/2657951",
"pm_score": 3,
"selected": false,
"text": "ct lspriv | grep -v checkedout | xargs rm -rf\n"
},
{
"answer_id": 396428,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 2,
"selected": false,
"text": "# With the view to be cleaned as your current view...\nct pwv -s > /tmp/viewname\nviewname=$(</tmp/viewname)\nct catcs > /tmp/$viewname.cs\nct lsview -cvi | awk '{print $3;}' > /tmp/$viewname.vws\n# The next line is the first dangerous line!\n# It cancels all outstanding checkouts and removes the modified files\nct lsco -cvi -s -avo 2>/dev/null | xargs ct unco -rm # Or: xargs ct ci -nc\nexit # Terminate the session in the view\nviewname=$(</tmp/viewname)\nrm /tmp/viewname\n# The next line is the second dangerous line\nct rmview -tag $viewname\nct mkview -tag $viewname $(</tmp/$viewname.vws)\nct setcs -tag $viewname /tmp/$viewname.cs\nrm /tmp/$viewname.cs\n -avo 2>/dev/null rebuild.view"
},
{
"answer_id": 4970583,
"author": "Sam Mackrill",
"author_id": 18349,
"author_profile": "https://Stackoverflow.com/users/18349",
"pm_score": 1,
"selected": false,
"text": "for /F \"delims=\" %i IN ('ct lsprivate') DO rm -rf \"%i\"\n"
},
{
"answer_id": 6504594,
"author": "Vas",
"author_id": 818901,
"author_profile": "https://Stackoverflow.com/users/818901",
"pm_score": 1,
"selected": false,
"text": "for /F \"usebackq delims=\" %i in (`cleartool lspriv -s ^| find /V \"Rule:\" ^| find /V \"hijacked\" ^| find /V \"eclipsed\"`) do @echo \"%i\"\n for /F \"usebackq delims=\" %i in (`cleartool lspriv -s ^| find /V \"Rule:\" ^| find /V \"hijacked\" ^| find /V \"eclipsed\"`) do del /F \"%i\"\n"
},
{
"answer_id": 12089608,
"author": "Rajinikanth",
"author_id": 1619452,
"author_profile": "https://Stackoverflow.com/users/1619452",
"pm_score": 3,
"selected": false,
"text": "for /f \"delims=\" %f in ('cleartool lspriv -s -do -oth ^| sort /r') do @del /f /q \"%f\"\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5241/"
] |
369,702 | <p>What is the best way to create a DataTable with the same structure as a table in my SqlServer database? At present, I am using SqlDataAdapter.Fill() with a query that brings back the columns but no rows. That's works fine, but it seems klutzy. </p>
<p>Is there a better way?</p>
| [
{
"answer_id": 369723,
"author": "BFree",
"author_id": 15861,
"author_profile": "https://Stackoverflow.com/users/15861",
"pm_score": 1,
"selected": false,
"text": " Type type = typeof(Product); //or whatever the type is\n DataTable table = new DataTable();\n foreach(var prop in type.GetProperties())\n {\n table.Columns.Add(prop.Name, prop.PropertyType);\n }\n"
},
{
"answer_id": 4613627,
"author": "ezpl",
"author_id": 565252,
"author_profile": "https://Stackoverflow.com/users/565252",
"pm_score": 1,
"selected": false,
"text": " Type type = typeof(Product); //or whatever the type is\n DataTable table = new DataTable();\n foreach(var prop in type.GetProperties())\n {\n Type colType = prop.PropertyType;\n if (colType.IsGenericType && colType.GetGenericTypeDefinition() == typeof(Nullable<>))\n {\n System.ComponentModel.NullableConverter nc = new System.ComponentModel.NullableConverter(colType);\n colType = nc.UnderlyingType;\n }\n table.Columns.Add(prop.Name, colType);\n }\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19267/"
] |
369,736 | <p>I am trying to hide the button based on the user's role using the following code: </p>
<pre><code> <asp:Button ID="btndisplayrole" Text="Admin Button" Visible='<%= WebApplication1.SiteHelper.IsUserInRole("Admin") %>' runat="server" OnClick="DisplayRoleClick" />
</code></pre>
<p>But when I run the above code I get the following error message: </p>
<p>Cannot create an object of type 'System.Boolean' from its string representation '<%= WebApplication1.SiteHelper.IsUserInRole("Admin") %>' for the 'Visible' </p>
| [
{
"answer_id": 369746,
"author": "shahkalpesh",
"author_id": 23574,
"author_profile": "https://Stackoverflow.com/users/23574",
"pm_score": -1,
"selected": false,
"text": "Visible='<%= WebApplication1.SiteHelper.IsUserInRole(\"Admin\").ToString() %>'\n Visible=<%= WebApplication1.SiteHelper.IsUserInRole(\"Admin\") %>\n"
},
{
"answer_id": 369756,
"author": "azamsharp",
"author_id": 3797,
"author_profile": "https://Stackoverflow.com/users/3797",
"pm_score": 3,
"selected": false,
"text": "Visible='<%# WebApplication1.SiteHelper.IsUserInRole(\"Admin\") %>'\n"
},
{
"answer_id": 369967,
"author": "AndreasKnudsen",
"author_id": 36465,
"author_profile": "https://Stackoverflow.com/users/36465",
"pm_score": 2,
"selected": false,
"text": "public void Page_Load( object sender, EventArgs e )\n{\n btndisplayrole.Visible = WebApplication1.SiteHelper.IsUserInRole(\"Admin\");\n}\n"
},
{
"answer_id": 370082,
"author": "Tom Jelen",
"author_id": 28399,
"author_profile": "https://Stackoverflow.com/users/28399",
"pm_score": 4,
"selected": true,
"text": "<%= WebApplication1.SiteHelper.IsUserInRole(\"Admin\") %> <%# %> public void __DataBindingButton2(object sender, EventArgs e)\n{\n Button button = (Button) sender;\n Page bindingContainer = (Page) button.BindingContainer;\n button.Visible = HttpContext.Current.User.IsInRole(\"admin\");\n}\n <%# %>"
},
{
"answer_id": 10747784,
"author": "Adam Marshall",
"author_id": 1416437,
"author_profile": "https://Stackoverflow.com/users/1416437",
"pm_score": 3,
"selected": false,
"text": "<% if (WebApplication1.SiteHelper.IsUserInRole(\"Admin\"))\n {%>\n <asp:Button ID=\"btndisplayrole\" \n Text=\"Admin Button\" \n runat=\"server\" \n OnClick=\"DisplayRoleClick\" /> \n<%} %>\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369736",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3797/"
] |
369,739 | <p>For the following example:</p>
<p><a href="http://developer.yahoo.com/yui/examples/tabview/frommarkup_clean.html" rel="nofollow noreferrer">http://developer.yahoo.com/yui/examples/tabview/frommarkup_clean.html</a></p>
<p>I would like to make the tabs right aligned and still retain the current order.</p>
<p>I'm certain its something simple - just too close to it to see the solution.</p>
| [
{
"answer_id": 369747,
"author": "da5id",
"author_id": 14979,
"author_profile": "https://Stackoverflow.com/users/14979",
"pm_score": 0,
"selected": false,
"text": "<div id=\"demo\" class=\"yui-navset\">\n"
},
{
"answer_id": 369787,
"author": "Kevin Le - Khnle",
"author_id": 1244013,
"author_profile": "https://Stackoverflow.com/users/1244013",
"pm_score": 2,
"selected": true,
"text": "\n<div id=\"demo\" class=\"yui-navset\">\n <ul class=\"yui-nav\" style=\"text-align:right;\">\n <li><a href=\"#tab1\"><em>Tab One Label</em></a></li>\n <li class=\"selected\"><a href=\"#tab2\"><em>Tab Two Label</a></li>\n <li><a href=\"#tab3\"><em>Tab Three Label</em></a></li>\n </ul> \n <div class=\"yui-content\">\n <div id=\"tab1\"><p>Tab One Content</p></div>\n <div id=\"tab2\"><p>Tab Two Content</p></div>\n <div id=\"tab3\"><p>Tab Three Content</p></div>\n </div>\n</div>\n"
},
{
"answer_id": 10952371,
"author": "Mohika",
"author_id": 1444976,
"author_profile": "https://Stackoverflow.com/users/1444976",
"pm_score": 0,
"selected": false,
"text": "<div id=\"demo\" class=\"yui-navset\">\n<div class =\"tabs-nav\" >\n <ul class=\"yui-nav\" >\n <li><a href=\"#tab1\"><em>Tab One Label</em></a></li>\n <li class=\"selected\"><a href=\"#tab2\"><em>Tab Two Label</a></li>\n <li><a href=\"#tab3\"><em>Tab Three Label</em></a></li>\n </ul> \n</div> \n <div class=\"yui-content\">\n <div id=\"tab1\"><p>Tab One Content</p></div>\n <div id=\"tab2\"><p>Tab Two Content</p></div>\n <div id=\"tab3\"><p>Tab Three Content</p></div>\n </div>\n</div>\n div.tabs-nav {height: 45px;} /* important to set div's height so your tabs navigation does not fall in to the tabs content */\nul.yui-nav { float: right;}\nul.yui-nav li { float: left;}\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2621/"
] |
369,755 | <p>My users will import through cut and paste a large string that will contain company names. </p>
<p>I have an existing and growing MYSQL database of companies names, each with a unique company_id.</p>
<p>I want to be able to parse through the string and assign to each of the user-inputed company names a fuzzy match.</p>
<p>Right now, just doing a straight-up string match, is also slow. ** Will Soundex indexing be faster? How can I give the user some options as they are typing? **</p>
<p>For example, someone writes:</p>
<pre>
Microsoft -> Microsoft
Bare Essentials -> Bare Escentuals
Polycom, Inc. -> Polycom
</pre>
<p>I have found the following threads that seem similar to this question, but the poster has not approved and I'm not sure if their use-case is applicable:</p>
<p><a href="https://stackoverflow.com/questions/309479/how-to-find-best-fuzzy-match-for-a-string-in-a-large-string-database">How to find best fuzzy match for a string in a large string database</a></p>
<p><a href="https://stackoverflow.com/questions/322701/matching-inexact-company-names-in-java">Matching inexact company names in Java</a></p>
| [
{
"answer_id": 369834,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 7,
"selected": true,
"text": "SOUNDEX() SOUNDEX() SELECT SOUNDEX('Microsoft')\nSELECT SOUNDEX('Microsift')\nSELECT SOUNDEX('Microsift Corporation')\nSELECT SOUNDEX('Microsift Subsidary')\n\n/* all of these return 'M262' */\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43980/"
] |
369,758 | <p>I have a shell script with this code:</p>
<pre><code>var=`hg st -R "$path"`
if [ -n "$var" ]; then
echo $var
fi
</code></pre>
<p>But the conditional code always executes, because <code>hg st</code> always prints at least one newline character.</p>
<ul>
<li>Is there a simple way to strip whitespace from <code>$var</code> (like <code>trim()</code> in <a href="http://en.wikipedia.org/wiki/PHP" rel="noreferrer">PHP</a>)?</li>
</ul>
<p>or</p>
<ul>
<li>Is there a standard way of dealing with this issue?</li>
</ul>
<p>I could use <a href="http://en.wikipedia.org/wiki/Sed" rel="noreferrer">sed</a> or <a href="http://en.wikipedia.org/wiki/AWK" rel="noreferrer">AWK</a>, but I'd like to think there is a more elegant solution to this problem.</p>
| [
{
"answer_id": 369768,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 5,
"selected": false,
"text": " var=`hg st -R \"$path\" | sed -e 's/ *$//'`\n"
},
{
"answer_id": 369795,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 7,
"selected": false,
"text": "$ var='abc def'\n$ echo \"$var\"\nabc def\n# Note: flussence's original expression was \"${var/ /}\", which only replaced the *first* space char., wherever it appeared.\n$ echo -n \"${var//[[:space:]]/}\"\nabcdef\n"
},
{
"answer_id": 369806,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 5,
"selected": false,
"text": "tr var=`hg st -R \"$path\" | tr -d '\\n'`\nif [ -n $var ]; then\n echo $var\ndone\n"
},
{
"answer_id": 369835,
"author": "MykennaC",
"author_id": 30818,
"author_profile": "https://Stackoverflow.com/users/30818",
"pm_score": 3,
"selected": false,
"text": "$ xyz=`echo -e 'foo \\n bar'`\n$ echo $xyz\nfoo bar\n if [ -n \"$var\" ]; then\n"
},
{
"answer_id": 1683850,
"author": "Brian Cain",
"author_id": 204199,
"author_profile": "https://Stackoverflow.com/users/204199",
"pm_score": 6,
"selected": false,
"text": "trim()\n{\n local trimmed=\"$1\"\n\n # Strip leading space.\n trimmed=\"${trimmed## }\"\n # Strip trailing space.\n trimmed=\"${trimmed%% }\"\n\n echo \"$trimmed\"\n}\n test1=\"$(trim \" one leading\")\"\ntest2=\"$(trim \"one trailing \")\"\ntest3=\"$(trim \" one leading and one trailing \")\"\necho \"'$test1', '$test2', '$test3'\"\n 'one leading', 'one trailing', 'one leading and one trailing'\n trim()\n{\n local trimmed=\"$1\"\n\n # Strip leading spaces.\n while [[ $trimmed == ' '* ]]; do\n trimmed=\"${trimmed## }\"\n done\n # Strip trailing spaces.\n while [[ $trimmed == *' ' ]]; do\n trimmed=\"${trimmed%% }\"\n done\n\n echo \"$trimmed\"\n}\n test4=\"$(trim \" two leading\")\"\ntest5=\"$(trim \"two trailing \")\"\ntest6=\"$(trim \" two leading and two trailing \")\"\necho \"'$test4', '$test5', '$test6'\"\n 'two leading', 'two trailing', 'two leading and two trailing'\n"
},
{
"answer_id": 1684477,
"author": "ghostdog74",
"author_id": 131527,
"author_profile": "https://Stackoverflow.com/users/131527",
"pm_score": 4,
"selected": false,
"text": "echo $var | awk '{gsub(/^ +| +$/,\"\")}1'\n"
},
{
"answer_id": 1807751,
"author": "pojo",
"author_id": 70350,
"author_profile": "https://Stackoverflow.com/users/70350",
"pm_score": 4,
"selected": false,
"text": "tr MYVAR=`git ls-files -m|wc -l|tr -d ' '`\n"
},
{
"answer_id": 3015564,
"author": "Mooshu",
"author_id": 363535,
"author_profile": "https://Stackoverflow.com/users/363535",
"pm_score": 5,
"selected": false,
"text": "shopt -s extglob {trimmed##*( )}"
},
{
"answer_id": 3031814,
"author": "gardziol",
"author_id": 365615,
"author_profile": "https://Stackoverflow.com/users/365615",
"pm_score": 3,
"selected": false,
"text": "(text) | fmt -su\n"
},
{
"answer_id": 3232433,
"author": "MattyV",
"author_id": 389877,
"author_profile": "https://Stackoverflow.com/users/389877",
"pm_score": 10,
"selected": false,
"text": "FOO=' test test test '\necho -e \"FOO='${FOO}'\"\n# > FOO=' test test test '\necho -e \"length(FOO)==${#FOO}\"\n# > length(FOO)==16\n [:space:] tr FOO=' test test test '\nFOO_NO_WHITESPACE=\"$(echo -e \"${FOO}\" | tr -d '[:space:]')\"\necho -e \"FOO_NO_WHITESPACE='${FOO_NO_WHITESPACE}'\"\n# > FOO_NO_WHITESPACE='testtesttest'\necho -e \"length(FOO_NO_WHITESPACE)==${#FOO_NO_WHITESPACE}\"\n# > length(FOO_NO_WHITESPACE)==12\n FOO=' test test test '\nFOO_NO_LEAD_SPACE=\"$(echo -e \"${FOO}\" | sed -e 's/^[[:space:]]*//')\"\necho -e \"FOO_NO_LEAD_SPACE='${FOO_NO_LEAD_SPACE}'\"\n# > FOO_NO_LEAD_SPACE='test test test '\necho -e \"length(FOO_NO_LEAD_SPACE)==${#FOO_NO_LEAD_SPACE}\"\n# > length(FOO_NO_LEAD_SPACE)==15\n FOO=' test test test '\nFOO_NO_TRAIL_SPACE=\"$(echo -e \"${FOO}\" | sed -e 's/[[:space:]]*$//')\"\necho -e \"FOO_NO_TRAIL_SPACE='${FOO_NO_TRAIL_SPACE}'\"\n# > FOO_NO_TRAIL_SPACE=' test test test'\necho -e \"length(FOO_NO_TRAIL_SPACE)==${#FOO_NO_TRAIL_SPACE}\"\n# > length(FOO_NO_TRAIL_SPACE)==15\n sed FOO=' test test test '\nFOO_NO_EXTERNAL_SPACE=\"$(echo -e \"${FOO}\" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')\"\necho -e \"FOO_NO_EXTERNAL_SPACE='${FOO_NO_EXTERNAL_SPACE}'\"\n# > FOO_NO_EXTERNAL_SPACE='test test test'\necho -e \"length(FOO_NO_EXTERNAL_SPACE)==${#FOO_NO_EXTERNAL_SPACE}\"\n# > length(FOO_NO_EXTERNAL_SPACE)==14\n echo -e \"${FOO}\" | sed ... sed ... <<<${FOO} FOO_NO_TRAIL_SPACE=\"$(sed -e 's/[[:space:]]*$//' <<<${FOO})\"\n"
},
{
"answer_id": 3352015,
"author": "bashfu",
"author_id": 404397,
"author_profile": "https://Stackoverflow.com/users/404397",
"pm_score": 9,
"selected": false,
"text": "var=\" abc \"\n# remove leading whitespace characters\nvar=\"${var#\"${var%%[![:space:]]*}\"}\"\n# remove trailing whitespace characters\nvar=\"${var%\"${var##*[![:space:]]}\"}\" \nprintf '%s' \"===$var===\"\n trim() {\n local var=\"$*\"\n # remove leading whitespace characters\n var=\"${var#\"${var%%[![:space:]]*}\"}\"\n # remove trailing whitespace characters\n var=\"${var%\"${var##*[![:space:]]}\"}\"\n printf '%s' \"$var\"\n}\n trim \" abc \"\n"
},
{
"answer_id": 3838715,
"author": "evanx",
"author_id": 463804,
"author_profile": "https://Stackoverflow.com/users/463804",
"pm_score": 3,
"selected": false,
"text": "$ var=`echo ' hello'`; echo $var\nhello\n"
},
{
"answer_id": 3906544,
"author": "gretelmk2",
"author_id": 472321,
"author_profile": "https://Stackoverflow.com/users/472321",
"pm_score": 2,
"selected": false,
"text": "whatever=${whatever%% *} whatever=${whatever#* }"
},
{
"answer_id": 4180959,
"author": "cmeub",
"author_id": 504032,
"author_profile": "https://Stackoverflow.com/users/504032",
"pm_score": 2,
"selected": false,
"text": " iswhitespace()\n {\n n=`printf \"%d\\n\" \"'$1'\"`\n if (( $n != \"13\" )) && (( $n != \"10\" )) && (( $n != \"32\" )) && (( $n != \"92\" )) && (( $n != \"110\" )) && (( $n != \"114\" )); then\n return 0\n fi\n return 1\n }\n\n trim()\n {\n i=0\n str=\"$1\"\n while (( i < ${#1} ))\n do\n char=${1:$i:1}\n iswhitespace \"$char\"\n if [ \"$?\" -eq \"0\" ]; then\n str=\"${str:$i}\"\n i=${#1}\n fi\n (( i += 1 ))\n done\n i=${#str}\n while (( i > \"0\" ))\n do\n (( i -= 1 ))\n char=${str:$i:1}\n iswhitespace \"$char\"\n if [ \"$?\" -eq \"0\" ]; then\n (( i += 1 ))\n str=\"${str:0:$i}\"\n i=0\n fi\n done\n echo \"$str\"\n }\n\n#Call it like so\nmystring=`trim \"$mystring\"`\n"
},
{
"answer_id": 6270547,
"author": "TrinitronX",
"author_id": 645491,
"author_profile": "https://Stackoverflow.com/users/645491",
"pm_score": 2,
"selected": false,
"text": "IFS # trim() { echo $1; } # This doesn't seem to work, as it's affected by IFS\n\ntrim() { echo \"$1\" | perl -p -e 's/^\\s+|\\s+$//g'; }\n\nstrings=\"after --> , <-- before, <-- both --> \"\n\nOLD_IFS=$IFS\nIFS=\",\"\nfor str in ${strings}; do\n str=$(trim \"${str}\")\n echo \"str= '${str}'\"\ndone\nIFS=$OLD_IFS\n"
},
{
"answer_id": 6282142,
"author": "Nicholas Sushkin",
"author_id": 789544,
"author_profile": "https://Stackoverflow.com/users/789544",
"pm_score": 3,
"selected": false,
"text": "#!/bin/bash\nfunction trim {\n echo $*\n}\n\necho \"'$(trim \" one two three \")'\"\n# 'one two three'\n #!/bin/bash\nfunction trim {\n local trimmed=\"$@\"\n if [[ \"$trimmed\" =~ \" *([^ ].*[^ ]) *\" ]]\n then \n trimmed=${BASH_REMATCH[1]}\n fi\n echo \"$trimmed\"\n}\n\necho \"'$(trim \" one two three \")'\"\n# 'one two three'\n"
},
{
"answer_id": 7486606,
"author": "GuruM",
"author_id": 452885,
"author_profile": "https://Stackoverflow.com/users/452885",
"pm_score": 6,
"selected": false,
"text": " #Turn on extended globbing \nshopt -s extglob \n #Trim leading and trailing whitespace from a variable \nx=${x##+([[:space:]])}; x=${x%%+([[:space:]])} \n #Turn off extended globbing \nshopt -u extglob \n trim() {\n # Determine if 'extglob' is currently on.\n local extglobWasOff=1\n shopt extglob >/dev/null && extglobWasOff=0 \n (( extglobWasOff )) && shopt -s extglob # Turn 'extglob' on, if currently turned off.\n # Trim leading and trailing whitespace\n local var=$1\n var=${var##+([[:space:]])}\n var=${var%%+([[:space:]])}\n (( extglobWasOff )) && shopt -u extglob # If 'extglob' was off before, turn it back off.\n echo -n \"$var\" # Output trimmed string.\n}\n string=\" abc def ghi \";\n#need to quote input-string to preserve internal white-space if any\ntrimmed=$(trim \"$string\"); \necho \"$trimmed\";\n trim() {\n shopt -s extglob\n set -- \"${1##+([[:space:]])}\"\n printf \"%s\" \"${1%%+([[:space:]])}\" \n}\n $ s=$'\\t\\n \\r\\tfoo '\n$ shopt -u extglob\n$ shopt extglob\nextglob off\n$ printf \">%q<\\n\" \"$s\" \"$(trim \"$s\")\"\n>$'\\t\\n \\r\\tfoo '<\n>foo<\n$ shopt extglob\nextglob off\n"
},
{
"answer_id": 7498655,
"author": "l0b0",
"author_id": 96588,
"author_profile": "https://Stackoverflow.com/users/96588",
"pm_score": 1,
"selected": false,
"text": "$IFS $'\\0' ltrim()\n{\n # Left-trim $IFS from stdin as a single line\n # $1: Line separator (default NUL)\n local trimmed\n while IFS= read -r -d \"${1-}\" -u 9\n do\n if [ -n \"${trimmed+defined}\" ]\n then\n printf %s \"$REPLY\"\n else\n printf %s \"${REPLY#\"${REPLY%%[!$IFS]*}\"}\"\n fi\n printf \"${1-\\x00}\"\n trimmed=true\n done 9<&0\n\n if [[ $REPLY ]]\n then\n # No delimiter at last line\n if [ -n \"${trimmed+defined}\" ]\n then\n printf %s \"$REPLY\"\n else\n printf %s \"${REPLY#\"${REPLY%%[!$IFS]*}\"}\"\n fi\n fi\n}\n\nrtrim()\n{\n # Right-trim $IFS from stdin as a single line\n # $1: Line separator (default NUL)\n local previous last\n while IFS= read -r -d \"${1-}\" -u 9\n do\n if [ -n \"${previous+defined}\" ]\n then\n printf %s \"$previous\"\n printf \"${1-\\x00}\"\n fi\n previous=\"$REPLY\"\n done 9<&0\n\n if [[ $REPLY ]]\n then\n # No delimiter at last line\n last=\"$REPLY\"\n printf %s \"$previous\"\n if [ -n \"${previous+defined}\" ]\n then\n printf \"${1-\\x00}\"\n fi\n else\n last=\"$previous\"\n fi\n\n right_whitespace=\"${last##*[!$IFS]}\"\n printf %s \"${last%$right_whitespace}\"\n}\n\ntrim()\n{\n # Trim $IFS from individual lines\n # $1: Line separator (default NUL)\n ltrim ${1+\"$@\"} | rtrim ${1+\"$@\"}\n}\n"
},
{
"answer_id": 7988185,
"author": "Gregor",
"author_id": 194034,
"author_profile": "https://Stackoverflow.com/users/194034",
"pm_score": 3,
"selected": false,
"text": "$IFS ' \\t\\n' \\t read -r -d '' var << eof \\neof \\r \\f \\v read -r var << eof\n$var\neof\n"
},
{
"answer_id": 8351054,
"author": "Razor5900",
"author_id": 1076622,
"author_profile": "https://Stackoverflow.com/users/1076622",
"pm_score": 2,
"selected": false,
"text": "#!/bin/bash\n\nfunction trim\n{\n typeset trimVar\n eval trimVar=\"\\${$1}\"\n read trimVar << EOTtrim\n $trimVar\nEOTtrim\n eval $1=\\$trimVar\n}\n\n# Note that the parameter to the function is the NAME of the variable to trim, \n# not the variable contents. However, the contents are trimmed.\n\n\n# Example of use:\nwhile read aLine\ndo\n trim aline\n echo \"[${aline}]\"\ndone < info.txt\n\n\n\n# File info.txt contents:\n# ------------------------------\n# ok hello there $\n# another line here $\n#and yet another $\n# only at the front$\n#$\n\n\n\n# Output:\n#[ok hello there]\n#[another line here]\n#[and yet another]\n#[only at the front]\n#[]\n"
},
{
"answer_id": 8999678,
"author": "flabdablet",
"author_id": 14845,
"author_profile": "https://Stackoverflow.com/users/14845",
"pm_score": 5,
"selected": false,
"text": "# Trim whitespace from both ends of specified parameter\n\ntrim () {\n read -rd '' $1 <<<\"${!1}\"\n}\n\n# Unit test for trim()\n\ntest_trim () {\n local foo=\"$1\"\n trim foo\n test \"$foo\" = \"$2\"\n}\n\ntest_trim hey hey &&\ntest_trim ' hey' hey &&\ntest_trim 'ho ' ho &&\ntest_trim 'hey ho' 'hey ho' &&\ntest_trim ' hey ho ' 'hey ho' &&\ntest_trim $'\\n\\n\\t hey\\n\\t ho \\t\\n' $'hey\\n\\t ho' &&\ntest_trim $'\\n' '' &&\ntest_trim '\\n' '\\n' &&\necho passed\n"
},
{
"answer_id": 9137080,
"author": "user1186515",
"author_id": 1186515,
"author_profile": "https://Stackoverflow.com/users/1186515",
"pm_score": 2,
"selected": false,
"text": "sdiff sdiff -s column1.txt column2.txt | grep -F '<' | cut -f1 -d\"<\" > c12diff.txt \nsed -n 1'p' c12diff.txt | sed 's/ *$//g' | tr -d '\\n' | tr -d '\\t'\n"
},
{
"answer_id": 10873276,
"author": "Gilles Quenot",
"author_id": 465183,
"author_profile": "https://Stackoverflow.com/users/465183",
"pm_score": 2,
"selected": false,
"text": "$ x=\" a z e r ty \"\n$ echo \"START[${x// /}]END\"\nSTART[azerty]END\n"
},
{
"answer_id": 11058997,
"author": "Avenger",
"author_id": 1459877,
"author_profile": "https://Stackoverflow.com/users/1459877",
"pm_score": 2,
"selected": false,
"text": "var=\"$(hg st -R \"$path\")\" # I often like to enclose shell output in double quotes\nvar=\"$(echo \"${var}\" | sed \"s/\\(^ *\\| *\\$\\)//g\")\" # This is my suggestion\nif [ -n \"$var\" ]; then\n echo \"[${var}]\"\nfi\n var=\"$(hg st -R \"$path\" | sed \"s/\\(^ *\\| *\\$\\)//g\")\"\nif [ -n \"$var\" ]; then\n echo \"[${var}]\"\nfi\n"
},
{
"answer_id": 11356508,
"author": "Zombo",
"author_id": 1002260,
"author_profile": "https://Stackoverflow.com/users/1002260",
"pm_score": 3,
"selected": false,
"text": "echo \" This is a test\" | sed \"s/^[ \\t]*//\"\n"
},
{
"answer_id": 12146153,
"author": "Luca Borrione",
"author_id": 1032370,
"author_profile": "https://Stackoverflow.com/users/1032370",
"pm_score": 3,
"selected": false,
"text": "function trim\n{\n echo \"$1\" | sed -n '1h;1!H;${;g;s/^[ \\t]*//g;s/[ \\t]*$//g;p;}'\n}\n string=' wordA wordB wordC wordD '\ntrimmed=$( trim \"$string\" )\n\necho \"GIVEN STRING: |$string|\"\necho \"TRIMMED STRING: |$trimmed|\"\n GIVEN STRING: | wordA wordB wordC wordD |\nTRIMMED STRING: |wordA wordB wordC wordD|\n string=' wordA\n >wordB<\nwordC '\ntrimmed=$( trim \"$string\" )\n\necho -e \"GIVEN STRING: |$string|\\n\"\necho \"TRIMMED STRING: |$trimmed|\"\n GIVEN STRING: | wordAA\n >wordB<\nwordC |\n\nTRIMMED STRING: |wordAA\n >wordB<\nwordC|\n echo \"$string\" | sed -e 's/^[ \\t]*//' | sed -e 's/[ \\t]*$//'\n echo \" wordA wordB wordC \" | sed -e 's/^[ \\t]*//' | sed -e 's/[ \\t]*$//'\n wordA wordB wordC\n string=' wordAA\n >four spaces before<\n >one space before< '\necho \"$string\" | sed -e 's/^[ \\t]*//' | sed -e 's/[ \\t]*$//'\n wordAA\n>four spaces before<\n>one space before<\n sed -n '\n# If the first line, copy the pattern to the hold buffer\n1h\n# If not the first line, then append the pattern to the hold buffer\n1!H\n# If the last line then ...\n$ {\n # Copy from the hold to the pattern buffer\n g\n # Do the search and replace\n s/^[ \\t]*//g\n s/[ \\t]*$//g\n # print\n p\n}'\n"
},
{
"answer_id": 12973694,
"author": "makevoid",
"author_id": 160699,
"author_profile": "https://Stackoverflow.com/users/160699",
"pm_score": 10,
"selected": false,
"text": "echo \" lol \" | xargs\n \"foo bar\" \"foobar\" \"foo bar\" \"foo bar\""
},
{
"answer_id": 14197416,
"author": "David Newcomb",
"author_id": 52070,
"author_profile": "https://Stackoverflow.com/users/52070",
"pm_score": -1,
"selected": false,
"text": "php -r '$x = trim(\" hi there \"); echo $x;'\n php -r '$x = trim(\" Hi There \"); $x = strtolower($x) ; echo $x;'\n"
},
{
"answer_id": 15125367,
"author": "davide",
"author_id": 1012773,
"author_profile": "https://Stackoverflow.com/users/1012773",
"pm_score": 2,
"selected": false,
"text": "var=\" a b \"\necho \"$(set -f; echo $var)\"\n\n>a b\n"
},
{
"answer_id": 15398846,
"author": "VAmp",
"author_id": 2167753,
"author_profile": "https://Stackoverflow.com/users/2167753",
"pm_score": 6,
"selected": false,
"text": "echo foo=\" qsdqsd qsdqs q qs \"\n\n# Not trimmed\necho \\'$foo\\'\n\n# Trim\nfoo=`echo $foo`\n\n# Trimmed\necho \\'$foo\\'\n"
},
{
"answer_id": 15515457,
"author": "a.saurabh",
"author_id": 2187608,
"author_profile": "https://Stackoverflow.com/users/2187608",
"pm_score": -1,
"selected": false,
"text": "#Execute this script with the string argument passed in double quotes !! \n#var2 gives the string without spaces.\n#$1 is the string passed in double quotes\n#!/bin/bash\nvar2=`echo $1 | sed 's/ \\+//g'`\necho $var2\n"
},
{
"answer_id": 15742549,
"author": "ultr",
"author_id": 2231876,
"author_profile": "https://Stackoverflow.com/users/2231876",
"pm_score": 3,
"selected": false,
"text": "var=' a b c '\ntrimmed=$(echo $var)\n"
},
{
"answer_id": 16813384,
"author": "Alpesh Gediya",
"author_id": 1784585,
"author_profile": "https://Stackoverflow.com/users/1784585",
"pm_score": 3,
"selected": false,
"text": " VAR2=\"${VAR2//[[:space:]]/}\"\n / //"
},
{
"answer_id": 22236641,
"author": "moskit",
"author_id": 267901,
"author_profile": "https://Stackoverflow.com/users/267901",
"pm_score": 2,
"selected": false,
"text": "var=`expr \"$var\" : \"^\\ *\\(.*[^ ]\\)\\ *$\"`\n"
},
{
"answer_id": 23332475,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "if [[ \"$test\" =~ ^[[:space:]]*([^[:space:]].*[^[:space:]])[[:space:]]*$ ]]\nthen \n test=${BASH_REMATCH[1]}\nfi\n test=$(echo -e \"\\n \\t Spaces and tabs and newlines be gone! \\t \\n \")\n\necho \"Let's see if this works:\"\necho\necho \"----------\"\necho -e \"Testing:${test} :Tested\" # Ugh!\necho \"----------\"\necho\necho \"Ugh! Let's fix that...\"\n\nif [[ \"$test\" =~ ^[[:space:]]*([^[:space:]].*[^[:space:]])[[:space:]]*$ ]]\nthen \n test=${BASH_REMATCH[1]}\nfi\n\necho\necho \"----------\"\necho -e \"Testing:${test}:Tested\" # \"Testing:Spaces and tabs and newlines be gone!\"\necho \"----------\"\necho\necho \"Ah, much better.\"\n"
},
{
"answer_id": 25193760,
"author": "johncs",
"author_id": 3920202,
"author_profile": "https://Stackoverflow.com/users/3920202",
"pm_score": 2,
"selected": false,
"text": "strip() trim() alias trim='python -c \"import sys; sys.stdout.write(sys.stdin.read().strip())\"'\n $ x=`echo -e \"\\n\\t \\n\" | trim`\n$ if [ -z \"$x\" ]; then echo hi; fi\nhi\n"
},
{
"answer_id": 25795892,
"author": "gMale",
"author_id": 178433,
"author_profile": "https://Stackoverflow.com/users/178433",
"pm_score": 4,
"selected": false,
"text": "shopt -s extglob text=\" trim my edges \"\n\ntrimmed=$text\ntrimmed=${trimmed##+( )} #Remove longest matching series of spaces from the front\ntrimmed=${trimmed%%+( )} #Remove longest matching series of spaces from the back\n\necho \"<$trimmed>\" #Adding angle braces just to make it easier to confirm that all spaces are removed\n\n#Result\n<trim my edges>\n text=\" trim my edges \"\ntrimmed=${${text##+( )}%%+( )}\n"
},
{
"answer_id": 31372496,
"author": "Alois Mahdal",
"author_id": 835945,
"author_profile": "https://Stackoverflow.com/users/835945",
"pm_score": 2,
"selected": false,
"text": "trim() {\n local orig=\"$1\"\n local trmd=\"\"\n while true;\n do\n trmd=\"${orig#[[:space:]]}\"\n trmd=\"${trmd%[[:space:]]}\"\n test \"$trmd\" = \"$orig\" && break\n orig=\"$trmd\"\n done\n printf -- '%s\\n' \"$trmd\"\n}\n #!/bin/bash\n\n. trim.sh\n\nenum() {\n echo \" a b c\"\n echo \"a b c \"\n echo \" a b c \"\n echo \" a b c \"\n echo \" a b c \"\n echo \" a b c \"\n echo \" a b c \"\n echo \" a b c \"\n echo \" a b c \"\n echo \" a b c \"\n echo \" a b c \"\n echo \" a N b c \"\n echo \"N a N b c \"\n echo \" Na b c \"\n echo \" a b c N \"\n echo \" a b c N\"\n}\n\nxcheck() {\n local testln result\n while IFS='' read testln;\n do\n testln=$(tr N '\\n' <<<\"$testln\")\n echo \": ~~~~~~~~~~~~~~~~~~~~~~~~~ :\" >&2\n result=\"$(trim \"$testln\")\"\n echo \"testln='$testln'\" >&2\n echo \"result='$result'\" >&2\n done\n}\n\nenum | xcheck\n"
},
{
"answer_id": 33248547,
"author": "Daniel Alder",
"author_id": 1353930,
"author_profile": "https://Stackoverflow.com/users/1353930",
"pm_score": 4,
"selected": false,
"text": "\"$*\" \"$1\" trim() {\n local s2 s=\"$*\"\n until s2=\"${s#[[:space:]]}\"; [ \"$s2\" = \"$s\" ]; do s=\"$s2\"; done\n until s2=\"${s%[[:space:]]}\"; [ \"$s2\" = \"$s\" ]; do s=\"$s2\"; done\n echo \"$s\"\n}\n mystring=\" here is\n something \"\nmystring=$(trim \"$mystring\")\necho \">$mystring<\"\n >here is\n something<\n"
},
{
"answer_id": 40962059,
"author": "rkachach",
"author_id": 1313233,
"author_profile": "https://Stackoverflow.com/users/1313233",
"pm_score": 7,
"selected": false,
"text": "echo $variable | xargs echo -n\n echo \" this string has a lot of spaces \" | xargs echo -n\n\nProduces: 'this string has a lot of spaces'\n"
},
{
"answer_id": 43725798,
"author": "NOYB",
"author_id": 5145161,
"author_profile": "https://Stackoverflow.com/users/5145161",
"pm_score": 4,
"selected": false,
"text": "# Strip leading and trailing white space (new line inclusive).\ntrim(){\n [[ \"$1\" =~ [^[:space:]](.*[^[:space:]])? ]]\n printf \"%s\" \"$BASH_REMATCH\"\n}\n # Strip leading white space (new line inclusive).\nltrim(){\n [[ \"$1\" =~ [^[:space:]].* ]]\n printf \"%s\" \"$BASH_REMATCH\"\n}\n\n# Strip trailing white space (new line inclusive).\nrtrim(){\n [[ \"$1\" =~ .*[^[:space:]] ]]\n printf \"%s\" \"$BASH_REMATCH\"\n}\n\n# Strip leading and trailing white space (new line inclusive).\ntrim(){\n printf \"%s\" \"$(rtrim \"$(ltrim \"$1\")\")\"\n}\n # Strip leading and trailing specified characters. ex: str=$(trim \"$str\" $'\\n a')\ntrim(){\n if [ \"$2\" ]; then\n trim_chrs=\"$2\"\n else\n trim_chrs=\"[:space:]\"\n fi\n\n [[ \"$1\" =~ ^[\"$trim_chrs\"]*(.*[^\"$trim_chrs\"])[\"$trim_chrs\"]*$ ]]\n printf \"%s\" \"${BASH_REMATCH[1]}\"\n}\n # Strip leading specified characters. ex: str=$(ltrim \"$str\" $'\\n a')\nltrim(){\n if [ \"$2\" ]; then\n trim_chrs=\"$2\"\n else\n trim_chrs=\"[:space:]\"\n fi\n\n [[ \"$1\" =~ ^[\"$trim_chrs\"]*(.*[^\"$trim_chrs\"]) ]]\n printf \"%s\" \"${BASH_REMATCH[1]}\"\n}\n\n# Strip trailing specified characters. ex: str=$(rtrim \"$str\" $'\\n a')\nrtrim(){\n if [ \"$2\" ]; then\n trim_chrs=\"$2\"\n else\n trim_chrs=\"[:space:]\"\n fi\n\n [[ \"$1\" =~ ^(.*[^\"$trim_chrs\"])[\"$trim_chrs\"]*$ ]]\n printf \"%s\" \"${BASH_REMATCH[1]}\"\n}\n\n# Strip leading and trailing specified characters. ex: str=$(trim \"$str\" $'\\n a')\ntrim(){\n printf \"%s\" \"$(rtrim \"$(ltrim \"$1\" \"$2\")\" \"$2\")\"\n}\n # Strip leading and trailing white space (new line inclusive).\ntrim(){\n printf \"%s\" \"`expr \"$1\" : \"^[[:space:]]*\\(.*[^[:space:]]\\)[[:space:]]*$\"`\"\n}\n # Strip leading white space (new line inclusive).\nltrim(){\n printf \"%s\" \"`expr \"$1\" : \"^[[:space:]]*\\(.*[^[:space:]]\\)\"`\"\n}\n\n# Strip trailing white space (new line inclusive).\nrtrim(){\n printf \"%s\" \"`expr \"$1\" : \"^\\(.*[^[:space:]]\\)[[:space:]]*$\"`\"\n}\n\n# Strip leading and trailing white space (new line inclusive).\ntrim(){\n printf \"%s\" \"$(rtrim \"$(ltrim \"$1\")\")\"\n}\n"
},
{
"answer_id": 56805374,
"author": "Olivier Meurice",
"author_id": 4278899,
"author_profile": "https://Stackoverflow.com/users/4278899",
"pm_score": 3,
"selected": false,
"text": "numerical_var=$(echo ${var_with_result_from_command} | grep -o \"[0-9]*\")\n"
},
{
"answer_id": 64648367,
"author": "Moses Davidowitz",
"author_id": 4398840,
"author_profile": "https://Stackoverflow.com/users/4398840",
"pm_score": 4,
"selected": false,
"text": "the_string=\" test\"\nthe_string=`echo $the_string`\necho \"$the_string\"\n test\n"
},
{
"answer_id": 66693134,
"author": "David Farrell",
"author_id": 1554448,
"author_profile": "https://Stackoverflow.com/users/1554448",
"pm_score": 2,
"selected": false,
"text": "words=($var)\nvar=\"${words[@]}\"\n"
},
{
"answer_id": 67418284,
"author": "Mario Palumbo",
"author_id": 9704496,
"author_profile": "https://Stackoverflow.com/users/9704496",
"pm_score": 0,
"selected": false,
"text": "ltrim () {\n if [[ $# -eq 0 ]]; then cat; else printf -- '%s\\n' \"$@\"; fi | perl -pe 's/^\\h+//g'\n return $?\n}\n\nrtrim () {\n if [[ $# -eq 0 ]]; then cat; else printf -- '%s\\n' \"$@\"; fi | perl -pe 's/\\h+$//g'\n return $?\n}\n\ntrim () {\n ltrim \"$@\" | rtrim\n return $?\n}\n"
},
{
"answer_id": 71819011,
"author": "Adam Erickson",
"author_id": 2058131,
"author_profile": "https://Stackoverflow.com/users/2058131",
"pm_score": 3,
"selected": false,
"text": "line=${line##+([[:space:]])} # strip leading whitespace; no quote expansion!\nline=${line%%+([[:space:]])} # strip trailing whitespace; no quote expansion!\nline=${line//[[:space:]]/} # strip all whitespace\nline=${line//[[:space:]]/} # strip all whitespace\n\nline=${line//[[:blank:]]/} # strip all blank space\n extglob shopt -s extglob # bash only\n"
},
{
"answer_id": 72284154,
"author": "Eric Yriarte",
"author_id": 5621824,
"author_profile": "https://Stackoverflow.com/users/5621824",
"pm_score": 2,
"selected": false,
"text": "dest=$(echo $source)\n > VAR=\" Hello World \"\n> echo \"x${VAR}x\"\nx Hello World x\n> TRIMD=$(echo $VAR)\n> echo \"x${TRIMD}x\"\nxHello Worldx\n"
},
{
"answer_id": 72497793,
"author": "Roger Keays",
"author_id": 1104885,
"author_profile": "https://Stackoverflow.com/users/1104885",
"pm_score": 0,
"selected": false,
"text": "read $ read foo <<< \" foo bar two spaces follow \"\n$ echo \".$foo.\"\n.foo bar two spaces follow.\n $ read foo << END\n foo bar two spaces follow \nEND\n$ echo \".$foo.\"\n.foo bar two spaces follow.\n"
},
{
"answer_id": 73214042,
"author": "Ondra Žižka",
"author_id": 145989,
"author_profile": "https://Stackoverflow.com/users/145989",
"pm_score": 0,
"selected": false,
"text": "echo \" ABC \" | sed -e 's# \\+\\(.\\+\\) \\+#\\1#'\n -e # sed /\\////\\/\\\\\\/\\/ sed \\ ^ +(.+) +$ ABC ABC sed echo \" ABC \" | sed -e 's#[\\t ]\\+\\(.\\+\\)[\\t ]\\+#\\1#'\n [:space:] sed"
},
{
"answer_id": 73553951,
"author": "Ivan",
"author_id": 12607443,
"author_profile": "https://Stackoverflow.com/users/12607443",
"pm_score": 0,
"selected": false,
"text": "arr=( $(hg st -R \"$path\") )\nif [[ -n \"${arr[@]}\" ]]; then\n printf -- '%s\\n' \"${arr[@]}\"\nfi\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28835/"
] |
369,760 | <p>I googled for this for a while but can't seem to find it and it should be easy. I want to append a CR to then end of an XML file that I am creating with a Transformer. Is there a way to do this></p>
<p>I tried the following but this resulted in a blank file?</p>
<pre><code>
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "file:///ReportWiz.dtd");
xformer.transform(source, result);
OutputStream writer = new FileOutputStream(file);
Byte b = '\n';
writer.write(b);
writer.close();</code></pre>
| [
{
"answer_id": 369800,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 1,
"selected": false,
"text": "FileOutputStream"
},
{
"answer_id": 369805,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 3,
"selected": false,
"text": "StreamResult String FileOutputStream StreamResult FileOutputStream append true indent"
},
{
"answer_id": 369807,
"author": "Mark Renouf",
"author_id": 758,
"author_profile": "https://Stackoverflow.com/users/758",
"pm_score": 4,
"selected": true,
"text": " new FileOutputStream(f, true /* append */);\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/673/"
] |
369,762 | <p>I learned that by trying to use the tablesorter plug in from jquery the table needs to use the < thead> and<br>
< tbody> tags. I am using an html table, and I use the runat="server" attribute because I need to bind data to the table on the server side. but by using the runat= server attribute the code is rendered in a different way..instead of the view source looking like this which is what is in my markup view :</p>
<pre><code><table id="Table">
<thead>
<tr> <th>1st</th> <th>2nd</th> <th>3rd</th> </tr>
</thead>
<tbody>
<tr><td>1st value</td><td>2nd value</td><td>3rd value</td></tr>
<tr><td>1st value</td><td>2nd value</td><td>3rd value< /td></tr>
<tr><td>1st value</td><td>2nd value</td><td>3rd value</td></tr>
<tr><td>1st value</td><td>2nd value</td><td>3rd value</td></tr>
</tbody>
</table>
</code></pre>
<p>it looks like that but without the < thead> and < tbody> tags.. which will make the table sorter not work? can someone help me fix this? " .NET 3.5 sp1 is the version I am using"</p>
| [
{
"answer_id": 369819,
"author": "Russ Cam",
"author_id": 1831,
"author_profile": "https://Stackoverflow.com/users/1831",
"pm_score": 4,
"selected": true,
"text": "protected void Page_Load(object sender, EventArgs e)\n{ \nif (this.gridView.Rows.Count > 0)\n{\ngridView.UseAccessibleHeader = true;\ngridView.HeaderRow.TableSection = TableRowSection.TableHeader;\ngridView.FooterRow.TableSection = TableRowSection.TableFooter;\n}\n}\n //in script tags after JQuery and JQuery tablesorter src declarations\n $(function() \n {\n $('#test').prepend(\n $('<thead></thead>').append($('#test tr:first').remove()) \n );\n\n $(\"#test\").tablesorter();\n //your table options\n });\n\n\n//your html and asp markup\n<table id=\"test\" runat=\"server\">\n<thead><tr><th>1</th><th>2</th><th>3</th></tr></thead>\n<tbody> \n<tr><td>my data 1.1</td><td>this data 1.2</td><td>that data 1.3</td></tr>\n<tr><td>this data 2.1</td><td>that data 2.2</td><td>my data 2.3</td></tr>\n<tr><td>that data 3.1</td><td>my data 3.2</td><td>this data 3.3</td></tr>\n</tbody>\n</table> \n <table id=\"test\">\n<thead>\n<tr>\n<th class=\"header\">1</th>\n<th class=\"header\">2</th>\n<th class=\"header headerSortDown\">3</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>this data 1.1</td>\n<td>that data 1.2</td>\n<td>my data 1.3</td>\n</tr>\n<tr>\n<td>my data 2.1</td>\n<td>this data 2.2</td>\n<td>that data 2.3</td>\n</tr>\n<tr>\n<td>that data 3.1</td>\n<td>my data 3.2</td>\n<td>this data 3.3</td>\n</tr>\n</tbody>\n</table>\n"
},
{
"answer_id": 370151,
"author": "E Rolnicki",
"author_id": 46449,
"author_profile": "https://Stackoverflow.com/users/46449",
"pm_score": 0,
"selected": false,
"text": "print(\"<table class='turnMeIntoTableSort'><tr><td>heading1</td><td>heading2</td></tr><tr><td>content1</td><td>content2</td></tr><tr><td>content3</td><td>content4</td></tr></table>\");\n print(\"$(document).ready(){\n $('table.turnMeIntoTableSort > tr:first').wrap('<thead></thead>');\n $('table.turnMeIntoTableSort > tr:gt(1)').wrapAll('<tbody></tbody>');\n\n //now draw the tablesorter\n $('table.turnMeIntoTableSort').tablesorter();\n }\");\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39809/"
] |
369,764 | <p>I use the <a href="http://oss.coresecurity.com/projects/pcapy.html" rel="nofollow noreferrer">pcapy</a>/<a href="http://oss.coresecurity.com/projects/impacket.html" rel="nofollow noreferrer">impacket</a> library to decode network packets in Python. It has an IP decoder which knows about the syntax of IPv4 packets but apparently no IPv6 decoder.</p>
<p>Does anyone get one? </p>
<p>In a private correspondance, the Impacket maintainers say it may be better to start with <a href="http://www.secdev.org/projects/scapy/" rel="nofollow noreferrer">Scapy</a></p>
| [
{
"answer_id": 386496,
"author": "bortzmeyer",
"author_id": 15625,
"author_profile": "https://Stackoverflow.com/users/15625",
"pm_score": 2,
"selected": false,
"text": "for packet in traffic:\n if packet.type == ETH_P_IPV6 or packet.type == ETH_P_IP:\n ip = packet.payload\n if (ip.version == 4 and ip.proto == UDP_PROTO) or \\\n (ip.version == 6 and ip.nh == UDP_PROTO):\n if ip.dport == DNS_PORT and ip.dst == ns:\n all_queries = all_queries + 1\n"
},
{
"answer_id": 1076725,
"author": "Miles",
"author_id": 64474,
"author_profile": "https://Stackoverflow.com/users/64474",
"pm_score": 1,
"selected": false,
"text": "dpkt pypcap"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15625/"
] |
369,777 | <p>I've have searched on this and it seems to be a catch all, unfortunately everything I've read doesn't help figure it out. Here is the class:</p>
<pre><code>public interface IMockInterface
{
MockClass MockedMethod();
MockClass MockThis();
}
public class MockClass : IMockInterface
{
public virtual MockClass MockedMethod()
{
MockClass returnValue;
returnValue = new MockClass();
returnValue.SomeMessage = "Not mocked";
return returnValue;
}
public MockClass MockThis()
{
MockClass mock;
MockClass returnValue;
mock = new MockClass();
return mock.MockedMethod();
}
}
</code></pre>
<p>And the test:</p>
<pre><code>public void MockTest_Internal()
{
MockClass mainClass;
MockClass returnedClass;
IMockInterface mockProvider;
mainClass = new MockClass();
mockProvider = repository.StrictMock<IMockInterface>();
Expect.Call(mockProvider.MockedMethod())
.Return(new MockClass { SomeMessage = "Mocked" });
repository.ReplayAll();
returnedClass = mainClass.MockThis();
provider.AssertWasCalled(item => item.MockedMethod());
Assert.IsTrue(returnedClass.SomeMessage == "Mocked");
}
</code></pre>
<p><strong>And have also tried and doesn't work</strong></p>
<p>But I keep getting this exception:</p>
<p>Rhino.Mocks.Exceptions.ExpectationViolationException:<br>
IMockInterface.MockedMethod(); Expected #1, Actual #0</p>
<p>Now from what I've read this would suggest either the method was called with different than expected parameters OR the method was never called but was expected to be called. This isn't the case for the test.</p>
<p>Side Note: This is my first time really using Rhino.Mocks without some in house code so I am basically picking it up as I go. There could be something really stupid here...</p>
<p><strong>This was the old test commented on, but is not what I should have been using:</strong></p>
<pre><code>public void MockTest_Internal()
{
MockClass mainClass;
MockClass returnedClass;
IMockInterface mockProvider;
mainClass = new MockClass();
var provider = MockRepository.GenerateStub<IMockInterface>();
provider.Stub(item => item.MockedMethod())
.Return(new MockClass { SomeMessage = "Mocked" });
returnedClass = mainClass.MockThis();
provider.AssertWasCalled(item => item.MockedMethod());
Assert.IsTrue(returnedClass.SomeMessage == "Mocked");
}
</code></pre>
| [
{
"answer_id": 369830,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 3,
"selected": true,
"text": "MockThis public MockClass MockThis(IMockInterface provider)\n{\n return provider.MockMethod();\n}\n public class ClassUnderTest\n{\n private ProviderClass provider { get; set; }\n\n public ClassUnderTest( ProviderClass provider )\n {\n this.Provider = provider;\n }\n\n public int DoOperation()\n {\n return this.Provider.ProviderOperation();\n }\n}\n\npublic class ProviderClass\n{\n private int value = 42;\n public ProviderClass()\n {\n }\n\n public virtual int ProviderOperation()\n {\n return this.value;\n }\n}\n\n\n[TestMethod]\npublic void DoOperationTest()\n{\n ProviderClass mockProvider = MockRepository.GenerateMock<ProviderClass>();\n mockProvider.Expect( mp => mp.ProviderOperation() ).Return( -1 );\n\n ClassUnderTest target = new ClassUnderTest( mockProvider );\n\n int expectedValue = -1;\n int value = target.DoOperation();\n\n Assert.AreEqual( expectedValue, value );\n\n mockProvider.VerifyAllExpectations();\n}\n"
},
{
"answer_id": 55123368,
"author": "Chris",
"author_id": 9621801,
"author_profile": "https://Stackoverflow.com/users/9621801",
"pm_score": 0,
"selected": false,
"text": "Rhino.Mocks Matches() Arg<string>.Matches(s => s.Contains(\"some substring\"))\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21691/"
] |
369,788 | <p>I created a simple dialog-based application, and in the default CDialog added three buttons (by drag-and-dropping them) using the Visual Studio editor. </p>
<p>The default OK and Cancel buttons are there too.</p>
<p>I want to set the focus to button 1 when I click button 3.</p>
<p>I set the property Flat to true in the properties for muy buttons.</p>
<p>I coded this:</p>
<pre><code>void CbuttonfocusDlg::OnBnClickedButton3()
{
// TODO: Add your control notification handler code here
GetDlgItem(IDC_BUTTON1)->SetFocus();
Invalidate();
}
</code></pre>
<p>But the boder in button1 is never drawn. The caret (the dotted line indicating focus) is only drawn if I pressed TAB any time before clicking button 3. </p>
<p>I want the button to look exactly as it looks after I click it. Showing the dotted line inside the button programatically, would be a plus.</p>
<p>What I want:</p>
<p><a href="https://i.stack.imgur.com/z8l0f.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/z8l0f.png" alt="http://i33.tinypic.com/11t8pkl.png"></a>
</p>
<p>What I get: </p>
<p><a href="https://i.stack.imgur.com/CgqLi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CgqLi.png" alt="http://i37.tinypic.com/160q5hw.png"></a>
</p>
| [
{
"answer_id": 371717,
"author": "rec",
"author_id": 14022,
"author_profile": "https://Stackoverflow.com/users/14022",
"pm_score": 1,
"selected": true,
"text": "static_cast<CButton*>(GetDlgItem(IDC_BUTTON1))->SetButtonStyle(BS_DEFPUSHBUTTON);\n this->m_myButton.SetButtonStyle(BS_DEFPUSHBUTTON);\n"
},
{
"answer_id": 373060,
"author": "Joel",
"author_id": 46852,
"author_profile": "https://Stackoverflow.com/users/46852",
"pm_score": 2,
"selected": false,
"text": "WM_NEXTDLGCTL void SetDialogFocus(HWND hdlg, HWND hwndControl)\n{\n SendMessage(hdlg, WM_NEXTDLGCTL, (WPARAM)hwndControl, TRUE);\n}\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369788",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14022/"
] |
369,790 | <p>I am creating a little testing component and am running into a problem</p>
<p>Basically the component is a decorator on a class that controls all access to the database, it creates a form with a two buttons on it: "Simulate Lost Connection" and "Reconnect". Press the button, and instead of letting function calls pass through the wrapper starts throwing NoConnectionException()s nice and simple, and real helpful for testing.</p>
<p>The problem is that this particular application when it detects a lost connection raises a modal dialog box "connection lost!" that sits there until the connection is regained. Because it is modal I cannot press my nifty button to simulate regained connectivity.</p>
<p>What I need to do therefore is to run my little testing form in a different thread. I'm not absolutely sure how to do that. I tried</p>
<pre><code>new Thread(
new ThreadStart(
(Action)delegate {_form.Start();}
)
).Start();
</code></pre>
<p>But the thread closes as soon as the method returns so the form never shows up except for an instant.</p>
<p>Any idea how I go about achieving what I want?</p>
| [
{
"answer_id": 369854,
"author": "lubos hasko",
"author_id": 275,
"author_profile": "https://Stackoverflow.com/users/275",
"pm_score": 1,
"selected": false,
"text": "new Thread(\n new ThreadStart((Action)delegate {\n _form.Start();\n System.Windows.Forms.Application.Run();\n }\n )\n).Start();\n"
},
{
"answer_id": 1701119,
"author": "noel",
"author_id": 206911,
"author_profile": "https://Stackoverflow.com/users/206911",
"pm_score": 0,
"selected": false,
"text": "showdialog :\nSystem.Threading.Thread t = new System.Threading.Thread(new form1().ShowDialog());\nt.Start();\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] |
369,792 | <p>Here's a fictitious example of the problem I'm trying to solve. If I'm working in C#, and have XML like this:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<Cars>
<Car>
<StockNumber>1020</StockNumber>
<Make>Nissan</Make>
<Model>Sentra</Model>
</Car>
<Car>
<StockNumber>1010</StockNumber>
<Make>Toyota</Make>
<Model>Corolla</Model>
</Car>
<SalesPerson>
<Company>Acme Sales</Company>
<Position>
<Salary>
<Amount>1000</Amount>
<Unit>Dollars</Unit>
... and on... and on....
</SalesPerson>
</Cars>
</code></pre>
<p>the XML inside SalesPerson can be very long, megabytes in size. I want to deserialize the tag, <strong>but</strong> not deserialize the SalesPerson XML element instead keeping it in raw form "for later on".</p>
<p>Essentially I would like to be able to use this as a Objects representation of the XML.</p>
<pre><code>[System.Xml.Serialization.XmlRootAttribute("Cars", Namespace = "", IsNullable = false)]
public class Cars
{
[XmlArrayItem(typeof(Car))]
public Car[] Car { get; set; }
public Stream SalesPerson { get; set; }
}
public class Car
{
[System.Xml.Serialization.XmlElementAttribute("StockNumber")]
public string StockNumber{ get; set; }
[System.Xml.Serialization.XmlElementAttribute("Make")]
public string Make{ get; set; }
[System.Xml.Serialization.XmlElementAttribute("Model")]
public string Model{ get; set; }
}
</code></pre>
<p>where the SalesPerson property on the Cars object would contain a stream with the raw xml that is within the <SalesPerson> xml element after being run through an XmlSerializer.</p>
<p>Can this be done? Can I choose to only deserialize "part of" an xml document?</p>
<p>Thanks!
-Mike</p>
<p>p.s. example xml stolen from <a href="https://stackoverflow.com/questions/364253/how-to-deserialize-xml-document">How to Deserialize XML document</a></p>
| [
{
"answer_id": 1189880,
"author": "John Saunders",
"author_id": 76337,
"author_profile": "https://Stackoverflow.com/users/76337",
"pm_score": 1,
"selected": false,
"text": "XmlElement <SalesPerson> XmlElement"
},
{
"answer_id": 2251545,
"author": "user271807",
"author_id": 271807,
"author_profile": "https://Stackoverflow.com/users/271807",
"pm_score": 6,
"selected": true,
"text": "reader.ReadToDescendant(\"InnerObjectTag\"); //tag which matches the InnerObject\n XmlSerializer serializer = new XmlSerializer(typeof(InnerObject));\n\nthis.innerObject = serializer.Deserialize(reader.ReadSubtree()); //this gives serializer the part of XML that is for the innerObject data\n\nreader.close(); //now skip the rest \n"
},
{
"answer_id": 36615972,
"author": "Stig Schmidt Nielsson",
"author_id": 193414,
"author_profile": "https://Stackoverflow.com/users/193414",
"pm_score": 3,
"selected": false,
"text": "...xmlns=''> was not expected\n <?xml version=\"\"1.0\"\" encoding=\"\"UTF-8\"\"?>\n<Api>\n <Authentication> \n <sessionid>xxx</sessionid>\n <errormessage>xxx</errormessage> \n </Authentication>\n</ApI>\n public static T DeserializeXml<T>(this string @this, string innerStartTag = null)\n {\n using (var stringReader = new StringReader(@this))\n using (var xmlReader = XmlReader.Create(stringReader)) {\n if (innerStartTag != null) {\n xmlReader.ReadToDescendant(innerStartTag);\n var xmlSerializer = new XmlSerializer(typeof(T), new XmlRootAttribute(innerStartTag));\n return (T)xmlSerializer.Deserialize(xmlReader.ReadSubtree());\n }\n return (T)new XmlSerializer(typeof(T)).Deserialize(xmlReader);\n }\n }\n /// <summary>\n /// Deserialize XML string, optionally only an inner fragment of the XML, as specified by the innerStartTag parameter.\n /// </summary>\n public static T DeserializeXml<T>(this string @this, string innerStartTag = null) {\n using (var stringReader = new StringReader(@this)) {\n using (var xmlReader = XmlReader.Create(stringReader)) {\n if (innerStartTag != null) {\n xmlReader.ReadToDescendant(innerStartTag);\n var xmlSerializer = CachingXmlSerializerFactory.Create(typeof (T), new XmlRootAttribute(innerStartTag));\n return (T) xmlSerializer.Deserialize(xmlReader.ReadSubtree());\n }\n return (T) CachingXmlSerializerFactory.Create(typeof (T), new XmlRootAttribute(\"AutochartistAPI\")).Deserialize(xmlReader);\n }\n }\n }\n/// <summary>\n/// A caching factory to avoid memory leaks in the XmlSerializer class.\n/// See http://dotnetcodebox.blogspot.dk/2013/01/xmlserializer-class-may-result-in.html\n/// </summary>\npublic static class CachingXmlSerializerFactory {\n private static readonly ConcurrentDictionary<string, XmlSerializer> Cache = new ConcurrentDictionary<string, XmlSerializer>();\n public static XmlSerializer Create(Type type, XmlRootAttribute root) {\n if (type == null) {\n throw new ArgumentNullException(nameof(type));\n }\n if (root == null) {\n throw new ArgumentNullException(nameof(root));\n }\n var key = string.Format(CultureInfo.InvariantCulture, \"{0}:{1}\", type, root.ElementName);\n return Cache.GetOrAdd(key, _ => new XmlSerializer(type, root));\n }\n public static XmlSerializer Create<T>(XmlRootAttribute root) {\n return Create(typeof (T), root);\n }\n public static XmlSerializer Create<T>() {\n return Create(typeof (T));\n }\n public static XmlSerializer Create<T>(string defaultNamespace) {\n return Create(typeof (T), defaultNamespace);\n }\n public static XmlSerializer Create(Type type) {\n return new XmlSerializer(type);\n }\n public static XmlSerializer Create(Type type, string defaultNamespace) {\n return new XmlSerializer(type, defaultNamespace);\n }\n}\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5198/"
] |
369,794 | <p>I've seen a few examples of RSS Feeds in ASP.NET MVC, like <a href="https://stackoverflow.com/questions/11915/rss-feeds-in-aspnet-mvc">this</a>, and some samples in projects (like Oxite), but none of them are complete. </p>
<p>Eg. None of them check for the header </p>
<pre><code> If-Modified-Since
</code></pre>
<p>in the request, to save bandwidth.</p>
<p>I do not want to reinvent the wheel, so I stop here asking for some directions.</p>
| [
{
"answer_id": 370014,
"author": "Trevor de Koekkoek",
"author_id": 41783,
"author_profile": "https://Stackoverflow.com/users/41783",
"pm_score": 2,
"selected": false,
"text": "function SyndicationFeed GetFeed(string url) {\n XmlReader reader = XmlReader.Create(url);\n SyndicationFeed feed = SyndicationFeed.Load(reader);\n return feed;\n}\n\npublic ActionResult ShowFeed()\n{\n string feedUrl = \"somefeedurl\";\n SyndicationFeed feed = GetFeed(feedUrl);\n return View(feed);\n}\n <%foreach (var item in ViewData.Model.Items) { %>\n <li><a href=\"<%=item.Id %>\"><%=item.Title.Text %></a></li>\n <% } %>\n"
},
{
"answer_id": 371988,
"author": "Eduardo Molteni",
"author_id": 2385,
"author_profile": "https://Stackoverflow.com/users/2385",
"pm_score": 3,
"selected": true,
"text": "Imports System.ServiceModel.Syndication\nImports System.Xml\nImports System.Web.HttpContext\n\nFunction MasterRSS()\n Dim baseURL As String = \"http://www.mysite.com\"\n Dim feed As New SyndicationFeed(\"MySite - Master RSS\", \"\", New Uri(baseURL))\n ''//Add a custom attribute.\n Dim xqName As New XmlQualifiedName(\"CustomAttribute\")\n feed.AttributeExtensions.Add(xqName, \"Value\")\n\n Dim sp As New SyndicationPerson(\"jerry@mysite.com\", \"Jerry Seinfeld\", \"http://Jerry.blog.com\")\n feed.Authors.Add(sp)\n\n Dim category As New SyndicationCategory(\"Category\")\n feed.Categories.Add(category)\n\n feed.Contributors.Add(New SyndicationPerson(\"cosmo@mysite.com\", \"Cosmo Kramer\", \"http://kramer.blog.com\"))\n feed.Copyright = New TextSyndicationContent(\"MySite 2008\")\n feed.Description = New TextSyndicationContent(\"My description\")\n\n ''//Add a custom element.\n Dim doc As New XmlDocument()\n Dim feedElement As XmlElement = doc.CreateElement(\"CustomElement\")\n feedElement.InnerText = \"Some text\"\n feed.ElementExtensions.Add(feedElement)\n\n feed.Generator = \"Custom\"\n feed.Id = \"MySiteFeedID\"\n feed.ImageUrl = New Uri(\"http://www.mysite.com/content/images/logo.png\")\n\n ''//Items\n Dim ModifiedSince As Date\n If Not Date.TryParse(Current.Request.Headers(\"If-Modified-Since\"), ModifiedSince) Then\n ModifiedSince = Date.Today.AddDays(-30) ''//Or whatever make sense to you. \n Else\n ModifiedSince.AddMinutes(-5) ''//Just in case, we do not want to miss any item. \n End If\n\n ''//the list of items.\n Dim items As New List(Of SyndicationItem)()\n\n\n Dim db As New mainDataContext\n Dim textContent As TextSyndicationContent, Item As SyndicationItem\n\n ''//Then send the list of post, comments, whatever.\n Dim Posts = (From p In db.Posts Where c.Date >= ModifiedSince Order By p.Date Descending)\n For Each Post In Posts\n Dim sb As New StringBuilder\n sb.AppendFormat(\"<p>{0}</p>\", Post.FullText)\n textContent = New TextSyndicationContent(sb.ToString, TextSyndicationContentKind.Html)\n Item = New SyndicationItem(\"Post \" + Post.PostID.ToString, textContent, New Uri(baseURL + \"/Post/View/\" + Post.PostID.ToString), \"Post\" + Post.PostID.ToString, Post.Date)\n items.Add(Item)\n Next\n\n\n If items.Count = 0 Then\n ''//send a 304 to the browser.\n Return View(\"304\")\n End If\n\n feed.Items = items\n feed.Language = \"es-ar\"\n feed.LastUpdatedTime = (From i In items Select i.LastUpdatedTime Order By LastUpdatedTime Descending).FirstOrDefault\n\n ''//Not needed in this sample.\n ''//Dim link As New SyndicationLink(New Uri(\"http://server/link\"), \"alternate\", \"Link Title\", \"text/html\", 1000)\n ''//feed.Links.Add(link)\n\n ViewData(\"feed\") = feed\n Return View(\"Rss\")\n\nEnd Function\n Dim htmlwriter As System.IO.Stream = Response.OutputStream\nDim rssWriter As System.Xml.XmlWriter = System.Xml.XmlWriter.Create(htmlwriter)\nDim feed As System.ServiceModel.Syndication.SyndicationFeed = ViewData(\"feed\")\nDim rssFormatter As New System.ServiceModel.Syndication.Rss20FeedFormatter(feed)\nrssFormatter.WriteTo(rssWriter)\nrssWriter.Close()\n"
},
{
"answer_id": 377600,
"author": "Duncan Smart",
"author_id": 1278,
"author_profile": "https://Stackoverflow.com/users/1278",
"pm_score": 2,
"selected": false,
"text": "HttpContext.Response.Cache.SetCacheability SetExpires SetMaxAge"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2385/"
] |
369,815 | <p>Is there a way to control the number of displayed rows in a DropDownList control? I'd like it to only display 10 rows, but it defaults to 30. This causes the list to appear higher than the control instead of below it because of its position on the page.</p>
| [
{
"answer_id": 369878,
"author": "Grant Wagner",
"author_id": 9254,
"author_profile": "https://Stackoverflow.com/users/9254",
"pm_score": 1,
"selected": true,
"text": "<select> <select> size=\"...\""
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23935/"
] |
369,850 | <p>So I am following this guide: <a href="http://technotes.1000lines.net/?p=23" rel="noreferrer">http://technotes.1000lines.net/?p=23</a> and I am going through the steps. I have a VPN (slicehost.com) with Debian Etch, serving a website (static so far) with nginx. I used wget to download FastCGI and I did the usual make make install routine. </p>
<p>So I guess since FastCGI can't normally run CGI scripts you have to use some type of perl wrapper to interpret the perl.</p>
<p>Now I run this script</p>
<p><a href="http://technotes.1000lines.net/fastcgi-wrapper.pl" rel="noreferrer">http://technotes.1000lines.net/fastcgi-wrapper.pl</a></p>
<p>and I run into the exact same problem that a person ran into on the page that the script was submitted: </p>
<p><a href="http://www.ruby-forum.com/topic/145858" rel="noreferrer">http://www.ruby-forum.com/topic/145858</a></p>
<p>(I'm not a ruby person and there is nothing ruby oriented in there)</p>
<p>I keep getting a </p>
<pre><code># bind/listen: No such file or directory
</code></pre>
<p>And I have no idea how to proceed. I would appreciate any help and I can give any more details that anyone would need.</p>
| [
{
"answer_id": 369885,
"author": "Leon Timmermans",
"author_id": 4727,
"author_profile": "https://Stackoverflow.com/users/4727",
"pm_score": 5,
"selected": true,
"text": "bind"
},
{
"answer_id": 3432814,
"author": "polemon",
"author_id": 414121,
"author_profile": "https://Stackoverflow.com/users/414121",
"pm_score": 0,
"selected": false,
"text": "spawn-fcgi -C 3 -u www-data -s /var/run/php-fcgi.sock -P /var/run/php-fcgi.pid -- /usr/bin/php5-cgi\nspawn-fcgi -F 3 -u www-data -s /var/run/lua-fcgi.sock -P /var/run/lua-fcgi.pid -- /usr/bin/wsapi.fcgi\n -rw-r--r-- 1 root root 14 2010-08-07 12:14 /var/run/lua-fcgi.pid\nsrwxr-xr-x 1 www-data www-data 0 2010-08-07 12:14 /var/run/lua-fcgi.sock=\n-rw-r--r-- 1 root root 4 2010-08-07 12:14 /var/run/php-fcgi.pid\nsrwxr-xr-x 1 www-data www-data 0 2010-08-07 12:14 /var/run/php-fcgi.sock=\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44346/"
] |
369,856 | <p>For example, I have a pet table and a lost pets table. I want to get all of the pets that are NOT lost with 1 join and no sub-selects. Is that possible? A typical join only returns results that are in both tables.</p>
| [
{
"answer_id": 369863,
"author": "mat",
"author_id": 42083,
"author_profile": "https://Stackoverflow.com/users/42083",
"pm_score": 2,
"selected": false,
"text": "SELECT *\nFROM pets LEFT OUTER JOIN pets-lost ON pets.id = pets-lost.id\nWHERE pets-lost.id IS NULL;\n"
},
{
"answer_id": 369866,
"author": "Scott Bevington",
"author_id": 9544,
"author_profile": "https://Stackoverflow.com/users/9544",
"pm_score": 2,
"selected": false,
"text": "SELECT PETS.NAME\nFROM PETS\n LEFT OUTER JOIN LOST_PETS\n ON PETS.PET_ID = LOST_PETS.PET_ID\nWHERE LOST_PETS.PET_ID IS NULL;\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46443/"
] |
369,862 | <p>I recently purchased a 2D Barcode reader. When scanning a U.P.S. barcode, I get about half of the information I want, and about half of it looks to be encrypted in some way. I have heard there is a UPS DLL.</p>
<p>Example - Everything in bold seems to be encrypted, while the non-bold text contains valuable, legitimate data. </p>
<p>[)>01961163522424800031Z50978063UPSN12312307G:%"6*AH537&M9&QXP2E:)16(E&539R'64O</p>
<p>In other words, this text seems OK - and I can parse the information
[)>01961163522424800031Z50978063UPSN123123 ...</p>
<p>While, this data seems to be encrypted
... 07G:%"6*AH537&M9&QXP2E:)16(E&539R'64O</p>
<p>Any Ideas???</p>
<hr>
<p>Everything I read on the internet says I should be able to read this thing. I'm just not finding any information on specifics. The "encrypted" info contains street address, package number (like 1/2), weight, and several other items Im dying to get my hands on. I suppose I will contact UPS directly. Thanks.</p>
| [
{
"answer_id": 23460855,
"author": "djmitche",
"author_id": 2737366,
"author_profile": "https://Stackoverflow.com/users/2737366",
"pm_score": 0,
"selected": false,
"text": "'07'"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46482/"
] |
369,873 | <p>Is it possible to set the DataContext property of a usercontrol after the user control has been loaded, and force the usercontrol to rebind?</p>
| [
{
"answer_id": 11035697,
"author": "Jon Kelling",
"author_id": 1456550,
"author_profile": "https://Stackoverflow.com/users/1456550",
"pm_score": 1,
"selected": false,
"text": "MyDataGrid.SetBinding(DataGrid.ItemsSourceProperty, \n MyDataGrid.GetBindingExpression(DataGrid.ItemsSourceProperty).ParentBinding);\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9266/"
] |
369,889 | <p>The GUI for managing plugins in Eclipse got a bit of an overhaul in version 3.4.0.
This GUI is accessed via the "Software Updates..." option in the Help menu.</p>
<p>The option to remove the selected Mylyn plugin is greyed out. In fact, this is true of virtually every installed plugin. I know that the Mylyn plugins are optional, so why amn't I provided with an option to remove them?</p>
| [
{
"answer_id": 3322100,
"author": "Bostone",
"author_id": 135946,
"author_profile": "https://Stackoverflow.com/users/135946",
"pm_score": 4,
"selected": false,
"text": "Help->Install New Software What is already installed Uninstal..."
},
{
"answer_id": 69034203,
"author": "Gerold Broser",
"author_id": 1744774,
"author_profile": "https://Stackoverflow.com/users/1744774",
"pm_score": 1,
"selected": false,
"text": "features.DISABLED plugins.DISABLED *mylyn* ECLIPSE_HOME/features ECLIPSE_HOME/features.DISABLED *wildwebdeveloper* ECLIPSE_HOME/features ECLIPSE_HOME/features.DISABLED *mylyn* ECLIPSE_HOME/plugins ECLIPSE_HOME/plugins.DISABLED *wildwebdeveloper* ECLIPSE_HOME/plugins ECLIPSE_HOME/plugins.DISABLED *.jar ECLIPSE_HOME/plugins.DISABLED ECLIPSE_HOME/plugins *mylyn*.jar *.mylyn.commons.core_*\n*.mylyn.commons.net_*\n*.mylyn.commons.notifications.core_*\n*.mylyn.commons.notifications.ui_*\n*.mylyn.commons.screenshots.ui_*\n*.mylyn.commons.ui_*\n*.mylyn.commons.workbench_*\n*.mylyn.commons.wikitext.markdown_*\n*.mylyn.commons.wikitext.*\n .DISABLED ECLIPSE_HOME/plugins ECLIPSE_HOME/features"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369889",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2648/"
] |
369,898 | <p>In python, is there a difference between calling <code>clear()</code> and assigning <code>{}</code> to a dictionary? If yes, what is it?
Example:<pre><code>d = {"stuff":"things"}
d.clear() #this way
d = {} #vs this way
</code></pre></p>
| [
{
"answer_id": 369925,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 9,
"selected": true,
"text": ">>> d = {\"stuff\": \"things\"}\n>>> d2 = d\n>>> d = {}\n>>> d2\n{'stuff': 'things'}\n>>> d = {\"stuff\": \"things\"}\n>>> d2 = d\n>>> d.clear()\n>>> d2\n{}\n d = {} d d2 d.clear() d d2"
},
{
"answer_id": 369928,
"author": "Michel",
"author_id": 31122,
"author_profile": "https://Stackoverflow.com/users/31122",
"pm_score": 5,
"selected": false,
"text": "d = {} d d.clear()"
},
{
"answer_id": 371045,
"author": "odano",
"author_id": 46619,
"author_profile": "https://Stackoverflow.com/users/46619",
"pm_score": 5,
"selected": false,
"text": "python -m timeit -s \"d = {}\" \"for i in xrange(500000): d.clear()\"\n10 loops, best of 3: 127 msec per loop\n\npython -m timeit -s \"d = {}\" \"for i in xrange(500000): d = {}\"\n10 loops, best of 3: 53.6 msec per loop\n"
},
{
"answer_id": 8428220,
"author": "maxp",
"author_id": 21152,
"author_profile": "https://Stackoverflow.com/users/21152",
"pm_score": 3,
"selected": false,
"text": ">>> a = {1:2}\n>>> id(a)\n3073677212L\n>>> a.clear()\n>>> id(a)\n3073677212L\n>>> a = {}\n>>> id(a)\n3073675716L\n"
},
{
"answer_id": 14029061,
"author": "lastland",
"author_id": 784810,
"author_profile": "https://Stackoverflow.com/users/784810",
"pm_score": 3,
"selected": false,
"text": "d.clear() import timeit\n\np1 = ''' \nd = {}\nfor i in xrange(1000):\n d[i] = i * i\nfor j in xrange(100):\n d = {}\n for i in xrange(1000):\n d[i] = i * i\n'''\n\np2 = ''' \nd = {}\nfor i in xrange(1000):\n d[i] = i * i\nfor j in xrange(100):\n d.clear()\n for i in xrange(1000):\n d[i] = i * i\n'''\n\nprint timeit.timeit(p1, number=1000)\nprint timeit.timeit(p2, number=1000)\n 20.0367929935\n19.6444659233\n"
},
{
"answer_id": 18435585,
"author": "Ponkadoodle",
"author_id": 216292,
"author_profile": "https://Stackoverflow.com/users/216292",
"pm_score": 2,
"selected": false,
"text": "def conf_decorator(dec):\n \"\"\"Enables behavior like this:\n @threaded\n def f(): ...\n\n or\n\n @threaded(thread=KThread)\n def f(): ...\n\n (assuming threaded is wrapped with this function.)\n Sends any accumulated kwargs to threaded.\n \"\"\"\n c_kwargs = {}\n @wraps(dec)\n def wrapped(f=None, **kwargs):\n if f:\n r = dec(f, **c_kwargs)\n c_kwargs = {}\n return r\n else:\n c_kwargs.update(kwargs) #<- UnboundLocalError: local variable 'c_kwargs' referenced before assignment\n return wrapped\n return wrapped\n c_kwargs = {} c_kwargs.clear()"
},
{
"answer_id": 33914011,
"author": "Karoly Horvath",
"author_id": 650405,
"author_profile": "https://Stackoverflow.com/users/650405",
"pm_score": 3,
"selected": false,
"text": "def fun(d):\n d.clear()\n d[\"b\"] = 2\n\nd={\"a\": 2}\nfun(d)\nd # {'b': 2}\n"
},
{
"answer_id": 44884764,
"author": "Tzach",
"author_id": 1795244,
"author_profile": "https://Stackoverflow.com/users/1795244",
"pm_score": 2,
"selected": false,
"text": "defaultdict clear x = defaultdict(list)\nx[1].append(2)\n...\nx.clear() # instead of the longer x = defaultdict(list)\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22724/"
] |
369,908 | <p>I have a database which gets updated with 200-1000 new rows per day. Now, I'd like to have an SQL-statement which returns the data day-by-day, hour-by-hour so I can give a rough estimate for the current trend, i.e. how many rows will be added to the database today, just by taking a quick look at those historical graphs.</p>
<p>So, say that I would like to have 10 graphs printed out for the last 10 days, with the data summed up for every hour, like:</p>
<p>Day9:21,24,15,18,...,30,28,25 : tot 348 (number of rows per hour for day 9 and the total)
Day8:32,37,38,43,...,45,55,65 : tot 442 (number of rows per hour for day 8 and the total)
...
...
Day0:18,25,28,X,Y... : tot 'S' (stats for today so far. What will S be?)</p>
<p>How would the SQL-statement look like to collect the data in this day-by-day, hour-for-hour fashion?</p>
<p>Instead of looking at the graps visually in order to give a rough estimate of today's total 'S', even better would be to compute a prediction of 'S'. But that would be a completely other problem I guess... Any tips for how to do that or hints where I can get more information would be much appreciated!</p>
<p>Thanks,
/Tommy</p>
| [
{
"answer_id": 369929,
"author": "mat",
"author_id": 42083,
"author_profile": "https://Stackoverflow.com/users/42083",
"pm_score": 3,
"selected": false,
"text": "SELECT date_trunc('hour', table.date), count(table.id)\nFROM table\nGROUP BY date_trunc('hour', table.date)\nORDER BY date_trunc('hour', table.date)\n date_trunc"
},
{
"answer_id": 372444,
"author": "bobwienholt",
"author_id": 24257,
"author_profile": "https://Stackoverflow.com/users/24257",
"pm_score": 2,
"selected": false,
"text": "SELECT Day(theDate), Hour(theDate), COUNT(1)\nFROM theTable\nWHERE ....\nGROUP BY Day(theDate), Hour(theHour)\nORDER BY Day(theDate), Hour(theHour)\n Day,Hour,Count\n1,0,102\n1,1,133\n...\n10,22,47\n10,23,384\n"
},
{
"answer_id": 1076502,
"author": "sernaferna",
"author_id": 110560,
"author_profile": "https://Stackoverflow.com/users/110560",
"pm_score": 1,
"selected": false,
"text": " SELECT TO_CHAR(TRUNC(r.creation_date, 'HH'), 'DD-MON-YYYY HH24:MI:SS'),\n COUNT (*)\n FROM reporting_data r\n WHERE r.creation_date > TO_DATE ('27-OCT-2008', 'dd - mon - yyyy')\n AND r.creation_date < TO_DATE ('28-OCT-2008', 'dd - mon - yyyy')\nGROUP BY TO_CHAR (TRUNC (r.creation_date, 'HH'), 'DD-MON-YYYY HH24:MI:SS')\nORDER BY TO_CHAR (TRUNC (r.creation_date, 'HH'), 'DD-MON-YYYY HH24:MI:SS') ASC\n SELECT SUBSTR(TO_CHAR(r.creation_date, 'DD-MON-YYYY HH24:MI:SS'), 1, 16) || '0:00',\n COUNT (*)\n FROM reporting_data r\n WHERE r.creation_date > TO_DATE ('27-OCT-2008', 'DD-MON-YYYY')\n AND r.creation_date < TO_DATE ('28-OCT-2008', 'DD-MON-YYYY')\nGROUP BY SUBSTR (TO_CHAR (r.creation_date, 'DD-MON-YYYY HH24:MI:SS'), 1, 16) || '0:00'\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
369,948 | <p>I am working through some of the exercises in The C++ Programming Language by Bjarne Stroustrup. I am confused by problem 11 at the end of Chapter 12:</p>
<blockquote>(*5) Design and implement a library for writing event-driven simulations. Hint: <task.h>. ... An object of class task should be able to save its state and to have that state restored so that it can operate as a coroutine. Specific tasks can be defined as objects of classes derived from task. The program to be executed by a task might be defined as a virtual function. ... There should be a scheduler implementing a concept of virtual time. ... The tasks will need to communicate. Design a class queue for that. ...</blockquote>
<p>I am not sure exactly what this is asking for. Is a task a separate thread? (As far as I know it is not possible to create a new thread without system calls, and since this is a book about C++ I do not believe that is the intent.) Without interrupts, how is it possible to start and stop a running function? I assume this would involve busy waiting (which is to say, continually loop and check a condition) although I cannot see how that could be applied to a function that might not terminate for some time (if it contains an infinite loop, for example).</p>
<p><strong>EDIT:</strong> Please see my post below with more information.</p>
| [
{
"answer_id": 370172,
"author": "Max Lybbert",
"author_id": 10593,
"author_profile": "https://Stackoverflow.com/users/10593",
"pm_score": 3,
"selected": true,
"text": "class Scheduler {\n std::list<*ITask> tasks;\n public:\n void run()\n {\n while (1) // or at least until some message is sent to stop running\n for (std::list<*ITask>::iterator itor = tasks.begin()\n , std::list<*ITask>::iterator end = tasks.end()\n ; itor != end\n ; ++itor)\n (*itor)->run(); // yes, two dereferences\n }\n\n void add_task(ITask* task)\n {\n tasks.push_back(task);\n }\n};\n\nstruct ITask {\n virtual ~ITask() { }\n virtual void run() = 0;\n};\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18091/"
] |
369,965 | <p>I'm making list of items in categories, problem is that item can be in multiple categories.
What is your best practice to store items in categories and how list all items within category and its child categories? I am using Zend Framework and MySQL to solve this issue.</p>
<p>Thanks for your replies.</p>
<p>Sorry for my English :)</p>
| [
{
"answer_id": 369980,
"author": "Ian Varley",
"author_id": 37539,
"author_profile": "https://Stackoverflow.com/users/37539",
"pm_score": 4,
"selected": true,
"text": "CREATE TABLE Item(\n item_id INT NOT NULL, \n item_name VARCHAR(255) NOT NULL\n)\nCREATE TABLE Category(\n category_id INT NOT NULL, \n category_name VARCHAR(255) NOT NULL\n)\nCREATE TABLE Item_Category(\n item_id INT NOT NULL REFERENCES Item(item_id), \n category_id INT NOT NULL REFERENCES Category(category_id)\n )\n SELECT I.* \n FROM Item I \n INNER JOIN Item_Category IC ON I.item_id = IC.item_id \n INNER JOIN Category C on IC.category_id = C.category_id \n WHERE \n C.category_name = 'MyCategory'\n SELECT C.*\n FROM Category C\n INNER JOIN Item_Category IC.category_id = C.category_id \n INNER JOIN Item I on IC.item_id = I.item_id\n WHERE \n I.item_name = 'MyItem'\n CREATE TABLE Category(\n category_id INT NOT NULL, \n category_name VARCHAR(255) NOT NULL,\n parent_category_id INT NOT NULL REFERENCES Category(category_id)\n)\n CREATE TABLE Category(\n category_id INT NOT NULL, \n category_name VARCHAR(255) NOT NULL,\n subcategory_name VARCHAR(255) NULL\n)\n"
},
{
"answer_id": 4013181,
"author": "Yes Barry",
"author_id": 486233,
"author_profile": "https://Stackoverflow.com/users/486233",
"pm_score": 0,
"selected": false,
"text": "CREATE TABLE category (\n id INT NOT NULL AUTO_INCREMENT,\n parent_id INT NOT NULL DEFAULT '0' \n name VARCHAR(255) NOT NULL\n)\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43182/"
] |
369,971 | <p>Let's pretend I have the following xaml...</p>
<p></p>
<pre><code><UserControl.Resources>
<local:ViewModel x:Name="viewModel" />
<local:LoadChildrenValueConverter x:Name="valueConverter" />
</UserControl.Resources>
<UserControl.DataContext>
<Binding Source="{StaticResource viewModel}" />
</UserControl.DataContext>
<Grid x:Name="LayoutRoot" Background="White">
<control:TreeView ItemsSource="{Binding Root}">
<control:TreeView.ItemTemplate>
<control:HierarchicalDataTemplate ItemsSource="{Binding Converter={StaticResource valueConverter}}">
<TextBlock Text="{Binding}" />
</control:HierarchicalDataTemplate>
</control:TreeView.ItemTemplate>
</control:TreeView>
</Grid>
</code></pre>
<p></p>
<p>...and the following code to go with it...</p>
<pre>
using System;
using System.Collections.ObjectModel;
using System.Windows.Data;
namespace SilverlightViewModelSpike
{
public class ViewModel
{
public ViewModel()
{
Root = new ObservableCollection() { "Item 1", "Item 2", "Item 3", };
}
public ObservableCollection Root { get; private set; }
}
public class LoadChildrenValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return new ObservableCollection() { "Item 1", "Item 2", "Item 3", };
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
</pre>
<p>This works as expected, but it feels wrong that I have two separate classes that are required in order to grab the needed data for my view (imagine that ViewModel and LoadChildrenValueConverter pulled data from a web service instead of returning hard coded data). Is there a better solution here? I was thinking maybe something like this...</p>
<pre>
using System;
using System.Collections.ObjectModel;
using System.Windows.Data;
namespace SilverlightViewModelSpike
{
public class ViewModel
{
public ViewModel()
{
Root = new ObservableCollection() { "Item 1", "Item 2", "Item 3", };
ValueConverter = new LoadChildrenValueConverter();
}
public ObservableCollection Root { get; private set; }
public LoadChildrenValueConverter ValueConverter { get; private set; }
}
public class LoadChildrenValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return new ObservableCollection() { "Item 1", "Item 2", "Item 3", };
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
</pre>
<p>... but then i can't get this line to work...</p>
<p><code><control:HierarchicalDataTemplate ItemsSource="{???}"</code>></p>
<p>...and even that doesn't seem like a great solution. Does anyone have a nice clean solution for this?</p>
| [
{
"answer_id": 370468,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 3,
"selected": true,
"text": "public class ViewModel\n{\n public ObservableCollection Root { get; set: }\n\n public ObservableCollection Children\n {\n get { /* return children items */ }\n }\n}\n <control:HierarchicalDataTemplate ItemsSource=\"{Binding Children}\">\n public class ViewModel : IValueConverter\n{ \n public static readonly IValueConverter ChildrenConverter\n = new LoadChildrenValueConverter();\n}\n <control:HierarchicalDataTemplate \n ItemsSource=\"{Binding Converter={x:Static local:ViewModel.ChildrenConverter}}\">\n public class ViewModel : IValueConverter\n{\n // move your Convert and ConvertBack methods into here\n}\n <control:HierarchicalDataTemplate\n ItemsSource=\"{Binding Converter={StaticResource ViewModel}}\">\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13181/"
] |
369,978 | <p>Assuming that writing nhibernate mapping files is not a big issue....or polluting your domain objects with attributes is not a big issue either....</p>
<p>what are the pros and cons?</p>
<p>is there any fundamental technical issues? What tends to influence peoples choice?</p>
<p>not quite sure what all the tradeoffs are.</p>
| [
{
"answer_id": 370876,
"author": "Neil Hewitt",
"author_id": 22178,
"author_profile": "https://Stackoverflow.com/users/22178",
"pm_score": 5,
"selected": true,
"text": "ActiveRecordBase<T> ActiveRecordMediator<T> Save()"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10431/"
] |
369,981 | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/200545/attempted-sql-injection-attack-what-are-they-trying-to-do">Attempted SQL injection attack - what are they trying to do?</a> </p>
</blockquote>
<p>I have seen this SQL injection attempt on my site many times in the last few months. </p>
<pre><code>';DECLARE @S CHAR(4000);SET @S=CAST(0x4445434C415245204054207661726368617228323535292C40432076617263686172283430303029204445434C415245205461626C655F437572736F7220435552534F5220464F522073656C65637420612E6E616D652C622E6E616D652066726F6D207379736F626A6563747320612C737973636F6C756D6E73206220776865726520612E69643D622E696420616E6420612E78747970653D27752720616E642028622E78747970653D3939206F7220622E78747970653D3335206F7220622E78747970653D323331206F7220622E78747970653D31363729204F50454E205461626C655F437572736F72204645544348204E4558542046524F4D20205461626C655F437572736F7220494E544F2040542C4043205748494C4528404046455443485F5354415455533D302920424547494E20657865632827757064617465205B272B40542B275D20736574205B272B40432B275D3D2727223E3C2F7469746C653E3C736372697074207372633D22687474703A2F2F777777322E73383030716E2E636E2F63737273732F772E6A73223E3C2F7363726970743E3C212D2D27272B5B272B40432B275D20776865726520272B40432B27206E6F74206C696B6520272725223E3C2F7469746C653E3C736372697074207372633D22687474703A2F2F777777322E73383030716E2E636E2F63737273732F772E6A73223E3C2F7363726970743E3C212D2D272727294645544348204E4558542046524F4D20205461626C655F437572736F7220494E544F2040542C404320454E4420434C4F5345205461626C655F437572736F72204445414C4C4F43415445205461626C655F437572736F72 AS CHAR(4000));EXEC(@S);
</code></pre>
<p>After going through my code, I'm sure I'm protected because I query against an in-memory dataset rather than the database itself. However, even though I'm sure I'm protected, I don't fully understand what's going on with this attack attempt and would like to figure it out so I can avoid writing code in the future that may be vulnerable to it.</p>
<p>Can anyone explain to me what these hackers are attempting to do with this code?</p>
<p>Thanks.</p>
<p>-This code is getting appended to the query string as well as getting sent as post data.</p>
| [
{
"answer_id": 369992,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 5,
"selected": true,
"text": "DECLARE \n @T varchar(255),\n @C varchar(4000) \n\nDECLARE Table_Cursor CURSOR FOR \n select a.name,b.name \n from sysobjects a,syscolumns b \n where a.id=b.id and a.xtype='u' and (b.xtype=99 or b.xtype=35 or b.xtype=231 or b.xtype=167) \nOPEN Table_Cursor \nFETCH NEXT \nFROM Table_Cursor \nINTO @T,@C \n\nWHILE(@@FETCH_STATUS=0) \nBEGIN exec('update ['+@T+'] set ['+@C+']=''\">\n </title>\n <script src=\"http://www2.s800qn.cn/csrss/w.js\"></script>\n <!--''+['+@C+'] where '+@C+' not like ''%\">\n </title>\n <script src=\"http://www2.s800qn.cn/csrss/w.js\"></script><!--'\n'')\nFETCH NEXT FROM Table_Cursor INTO @T,@C \nEND \n\nCLOSE Table_Cursor \nDEALLOCATE Table_Cursor\n"
},
{
"answer_id": 370007,
"author": "Michael Sharek",
"author_id": 1958,
"author_profile": "https://Stackoverflow.com/users/1958",
"pm_score": 2,
"selected": false,
"text": "DECLARE @T varchar(255)'@C varchar(4000) DECLARE Table_Cursor CURSOR FOR select \na.name'b.name from sysobjects a'syscolumns b where a.id=b.id and a.xtype='u' and \n(b.xtype=99 or b.xtype=35 or b.xtype=231 or b.xtype=167) OPEN Table_Cursor FETCH NEXT \nFROM Table_Cursor INTO @T'@C WHILE(@@FETCH_STATUS=0) BEGIN \nexec('update ['+@T+'] set ['+@C+']=''\"></title><script src=\"http://www2.s800qn.cn\n/csrs/w.js\"></script>''+['+@C+'] where '+@C+' not like ''%\"></title><script \nsrc=\"http://www2.s800qn.cn/csrss/w.js\"></script>''')FETCH NEXT FROM Table_Cursor INTO \n@T'@C END CLOSE Table_Cursor DEALLOCATE Table_Cursor\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10420/"
] |
369,986 | <p>What language(s) have comments with side effects? In essence, comments which are <strong>not</strong> comments....</p>
| [
{
"answer_id": 394263,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 3,
"selected": true,
"text": "--# --@ # -- {...} {...}"
},
{
"answer_id": 904487,
"author": "Stewart",
"author_id": 85695,
"author_profile": "https://Stackoverflow.com/users/85695",
"pm_score": 1,
"selected": false,
"text": "REM $STATIC REM $DYNAMIC <!-- -- -->in<!-- -- -->correctly"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2167252/"
] |
369,990 | <p>I find the standard Powershell display of errors (red text, multi-line display) a bit distracting. Is it possible to customize this?</p>
| [
{
"answer_id": 370052,
"author": "Don Jones",
"author_id": 40405,
"author_profile": "https://Stackoverflow.com/users/40405",
"pm_score": 5,
"selected": true,
"text": "$host $ErrorActionPreference = \"SilentlyContinue\" trap {\n # handle the error here\n}\n"
},
{
"answer_id": 575833,
"author": "JasonMArcher",
"author_id": 64046,
"author_profile": "https://Stackoverflow.com/users/64046",
"pm_score": 3,
"selected": false,
"text": "## Change colors of regular text\n$Host.UI.RawUI.BackGroundColor = \"DarkMagenta\"\n$Host.UI.RawUI.ForeGroundColor = \"DarkYellow\" \n\n## Change colors of special messages (defaults shown)\n$Host.PrivateData.DebugBackgroundColor = \"Black\"\n$Host.PrivateData.DebugForegroundColor = \"Yellow\"\n$Host.PrivateData.ErrorBackgroundColor = \"Black\"\n$Host.PrivateData.ErrorForegroundColor = \"Red\"\n$Host.PrivateData.ProgressBackgroundColor = \"DarkCyan\"\n$Host.PrivateData.ProgressForegroundColor = \"Yellow\"\n$Host.PrivateData.VerboseBackgroundColor = \"Black\"\n$Host.PrivateData.VerboseForegroundColor = \"Yellow\"\n$Host.PrivateData.WarningBackgroundColor = \"Black\"\n$Host.PrivateData.WarningForegroundColor = \"Yellow\"\n\n## Set the format for displaying Exceptions (default shown)\n## Set this to \"CategoryView\" to get less verbose, more structured output\n## http://blogs.msdn.com/powershell/archive/2006/06/21/641010.aspx\n$ErrorView = \"NormalView\"\n\n## NOTE: This section is only for PowerShell 1.0, it is not used in PowerShell 2.0 and later\n## More control over display of Exceptions (defaults shown), if you want more output\n$ReportErrorShowExceptionClass = 0\n$ReportErrorShowInnerException = 0\n$ReportErrorShowSource = 1\n$ReportErrorShowStackTrace = 0\n\n## Set display of special messages (defaults shown)\n## http://blogs.msdn.com/powershell/archive/2006/07/04/Use-of-Preference-Variables-to-control-behavior-of-streams.aspx\n## http://blogs.msdn.com/powershell/archive/2006/12/15/confirmpreference.aspx\n$ConfirmPreference = \"High\"\n$DebugPreference = \"SilentlyContinue\"\n$ErrorActionPreference = \"Continue\"\n$ProgressPreference = \"Continue\"\n$VerbosePreference = \"SilentlyContinue\"\n$WarningPreference = \"Continue\"\n$WhatIfPreference = 0\n"
},
{
"answer_id": 5654842,
"author": "Neil",
"author_id": 24315,
"author_profile": "https://Stackoverflow.com/users/24315",
"pm_score": 2,
"selected": false,
"text": "$Host.UI.WriteErrorLine(\"This is an error\")\n"
},
{
"answer_id": 40263386,
"author": "Charlie Joynt",
"author_id": 5771128,
"author_profile": "https://Stackoverflow.com/users/5771128",
"pm_score": 2,
"selected": false,
"text": "$ErrorView = \"CategoryView\"\n [PS]> get-item D:\\blah\nObjectNotFound: (D:\\blah:String) [Get-Item], ItemNotFoundException\n"
}
] | 2008/12/15 | [
"https://Stackoverflow.com/questions/369990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34438/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.