qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
66,363
<p>I need to find out the <strong>external</strong> IP of the computer a C# application is running on. </p> <p>In the application I have a connection (via .NET remoting) to a server. Is there a good way to get the address of the client on the server side?</p> <p><em>(I have edited the question, to be a little more clear. I'm apologize to all kind people who did their best to respond to the question, when I perhaps was a little too vague)</em></p> <p><strong>Solution:</strong><br> I found a way that worked great for me. By implementing a custom IServerChannelSinkProvider and IServerChannelSink where I have access to CommonTransportKeys.IPAddress, it's easy to add the client ip on the CallContext.</p> <pre><code>public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestmessage, ITransportHeaders requestHeaders, System.IO.Stream requestStream, out IMessage responseMessage, out ITransportHeaders responseHeaders, out System.IO.Stream responseStream) { try { // Get the IP address and add it to the call context. IPAddress ipAddr = (IPAddress)requestHeaders[CommonTransportKeys.IPAddress]; CallContext.SetData("ClientIP", ipAddr); } catch (Exception) { } sinkStack.Push(this, null); ServerProcessing srvProc = _NextSink.ProcessMessage(sinkStack, requestmessage, requestHeaders, requestStream, out responseMessage, out responseHeaders, out responseStream); return srvProc; } </code></pre> <p>And then later (when I get a request from a client) just get the IP from the CallContext like this.</p> <pre><code>public string GetClientIP() { // Get the client IP from the call context. object data = CallContext.GetData("ClientIP"); // If the data is null or not a string, then return an empty string. if (data == null || !(data is IPAddress)) return string.Empty; // Return the data as a string. return ((IPAddress)data).ToString(); } </code></pre> <p>I can now send the IP back to the client.</p>
[ { "answer_id": 66407, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": 3, "selected": false, "text": "<?php\necho 'Your Public IP is: ' . $_SERVER['REMOTE_ADDR'];\n?>\n" }, { "answer_id": 66408, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 3, "selected": false, "text": "IPHostEntry IPHost = Dns.GetHostEntry(Dns.GetHostName());\nstring externalIP = IPHost.AddressList[0].ToString();\n" }, { "answer_id": 66415, "author": "Alex M", "author_id": 9652, "author_profile": "https://Stackoverflow.com/users/9652", "pm_score": -1, "selected": false, "text": "192.168.x.x" }, { "answer_id": 67658, "author": "configurator", "author_id": 9536, "author_profile": "https://Stackoverflow.com/users/9536", "pm_score": 1, "selected": false, "text": "System.Net.Sockets.TcpClient client.Client.RemoteEndPoint System.Net.EndPoint System.Net.IPEndPoint Address using (System.Net.Sockets.TcpClient client = whatever) {\n System.Net.EndPoint ep = client.Client.RemoteEndPoint;\n System.Net.IPEndPoint ip = (System.Net.IPEndPoint)ep;\n DoSomethingWith(ip.Address);\n}\n" }, { "answer_id": 928106, "author": "Justin Tanner", "author_id": 609, "author_profile": "https://Stackoverflow.com/users/609", "pm_score": 2, "selected": false, "text": "CallContext // try to set the call context\nLogicalCallContext lcc = (LogicalCallContext)requestMessage.Properties[\"__CallContext\"];\nif (lcc != null)\n{\n lcc.SetData(\"ClientIP\", ipAddr);\n}\n GetClientIP()" }, { "answer_id": 1319527, "author": "Patrik Svensson", "author_id": 936, "author_profile": "https://Stackoverflow.com/users/936", "pm_score": 4, "selected": true, "text": "public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, \n IMessage requestmessage, ITransportHeaders requestHeaders, \n System.IO.Stream requestStream, out IMessage responseMessage, \n out ITransportHeaders responseHeaders, out System.IO.Stream responseStream)\n{\n try\n {\n // Get the IP address and add it to the call context.\n IPAddress ipAddr = (IPAddress)requestHeaders[CommonTransportKeys.IPAddress];\n CallContext.SetData(\"ClientIP\", ipAddr);\n }\n catch (Exception)\n {\n }\n\n sinkStack.Push(this, null);\n ServerProcessing srvProc = _NextSink.ProcessMessage(sinkStack, requestmessage, requestHeaders,\n requestStream, out responseMessage, out responseHeaders, out responseStream);\n\n return srvProc;\n}\n public string GetClientIP()\n{\n // Get the client IP from the call context.\n object data = CallContext.GetData(\"ClientIP\");\n\n // If the data is null or not a string, then return an empty string.\n if (data == null || !(data is IPAddress))\n return string.Empty;\n\n // Return the data as a string.\n return ((IPAddress)data).ToString();\n}\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66363", "https://Stackoverflow.com", "https://Stackoverflow.com/users/936/" ]
66,382
<p>In the ContainsIngredients method in the following code, is it possible to cache the <em>p.Ingredients</em> value instead of explicitly referencing it several times? This is a fairly trivial example that I just cooked up for illustrative purposes, but the code I'm working on references values deep inside <em>p</em> eg. <em>p.InnerObject.ExpensiveMethod().Value</em></p> <p>edit: I'm using the PredicateBuilder from <a href="http://www.albahari.com/nutshell/predicatebuilder.html" rel="nofollow noreferrer">http://www.albahari.com/nutshell/predicatebuilder.html</a></p> <pre><code>public class IngredientBag { private readonly Dictionary&lt;string, string&gt; _ingredients = new Dictionary&lt;string, string&gt;(); public void Add(string type, string name) { _ingredients.Add(type, name); } public string Get(string type) { return _ingredients[type]; } public bool Contains(string type) { return _ingredients.ContainsKey(type); } } public class Potion { public IngredientBag Ingredients { get; private set;} public string Name {get; private set;} public Potion(string name) : this(name, null) { } public Potion(string name, IngredientBag ingredients) { Name = name; Ingredients = ingredients; } public static Expression&lt;Func&lt;Potion, bool&gt;&gt; ContainsIngredients(string ingredientType, params string[] ingredients) { var predicate = PredicateBuilder.False&lt;Potion&gt;(); // Here, I'm accessing p.Ingredients several times in one // expression. Is there any way to cache this value and // reference the cached value in the expression? foreach (var ingredient in ingredients) { var temp = ingredient; predicate = predicate.Or ( p =&gt; p.Ingredients != null &amp;&amp; p.Ingredients.Contains(ingredientType) &amp;&amp; p.Ingredients.Get(ingredientType).Contains(temp)); } return predicate; } } [STAThread] static void Main() { var potions = new List&lt;Potion&gt; { new Potion("Invisibility", new IngredientBag()), new Potion("Bonus"), new Potion("Speed", new IngredientBag()), new Potion("Strength", new IngredientBag()), new Potion("Dummy Potion") }; potions[0].Ingredients.Add("solid", "Eye of Newt"); potions[0].Ingredients.Add("liquid", "Gall of Peacock"); potions[0].Ingredients.Add("gas", "Breath of Spider"); potions[2].Ingredients.Add("solid", "Hair of Toad"); potions[2].Ingredients.Add("gas", "Peacock's anguish"); potions[3].Ingredients.Add("liquid", "Peacock Sweat"); potions[3].Ingredients.Add("gas", "Newt's aura"); var predicate = Potion.ContainsIngredients("solid", "Newt", "Toad") .Or(Potion.ContainsIngredients("gas", "Spider", "Scorpion")); foreach (var result in from p in potions where(predicate).Compile()(p) select p) { Console.WriteLine(result.Name); } } </code></pre>
[ { "answer_id": 66710, "author": "Fake Jim", "author_id": 6199, "author_profile": "https://Stackoverflow.com/users/6199", "pm_score": 3, "selected": true, "text": "private static bool IsIngredientPresent(IngredientBag i, string ingredientType, string ingredient)\n{\n return i != null && i.Contains(ingredientType) && i.Get(ingredientType).Contains(ingredient);\n}\n\npublic static Expression<Func<Potion, bool>>\n ContainsIngredients(string ingredientType, params string[] ingredients)\n{\n var predicate = PredicateBuilder.False<Potion>();\n // Here, I'm accessing p.Ingredients several times in one \n // expression. Is there any way to cache this value and\n // reference the cached value in the expression?\n foreach (var ingredient in ingredients)\n {\n var temp = ingredient;\n predicate = predicate.Or(\n p => IsIngredientPresent(p.Ingredients, ingredientType, temp));\n }\n\n return predicate;\n}\n" }, { "answer_id": 66749, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "p.Ingredients" }, { "answer_id": 67309, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 0, "selected": false, "text": " public class IngredientBag\n {\n private Dictionary<string, string> _ingredients = \nnew Dictionary<string, string>();\n public void Add(string type, string name)\n {\n _ingredients[type] = name;\n }\n public string Get(string type)\n {\n return _ingredients.ContainsKey(type) ? _ingredients[type] : null;\n }\n public bool Has(string type, string name)\n {\n return name == null ? false : this.Get(type) == name;\n }\n }\n\n public Potion(string name) : this(name, new IngredientBag()) { }\n Dictionary<string, List<string>> ingredients;\n from p in Potions\nwhere ingredients.Any(i => i.Value.Any(v => p.IngredientBag.Has(i.Key, v))\nselect p;\n" }, { "answer_id": 67617, "author": "Steve Cooper", "author_id": 6722, "author_profile": "https://Stackoverflow.com/users/6722", "pm_score": 3, "selected": false, "text": "static Func<T> Remember<T>(Func<T> GetExpensiveValue)\n{\n bool isCached= false;\n T cachedResult = default(T);\n\n return () =>\n {\n if (!isCached)\n {\n cachedResult = GetExpensiveValue();\n isCached = true;\n }\n return cachedResult;\n\n };\n}\n // here's something that takes ages to calculate\n Func<string> MyExpensiveMethod = () => \n { \n System.Threading.Thread.Sleep(5000); \n return \"that took ages!\"; \n };\n\n // and heres a function call that only calculates it the once.\n Func<string> CachedMethod = Remember(() => MyExpensiveMethod());\n\n // only the first line takes five seconds; \n // the second and third calls are instant.\n Console.WriteLine(CachedMethod());\n Console.WriteLine(CachedMethod());\n Console.WriteLine(CachedMethod());\n" }, { "answer_id": 69701, "author": "Fake Jim", "author_id": 6199, "author_profile": "https://Stackoverflow.com/users/6199", "pm_score": 1, "selected": false, "text": "private static bool TestWith<T>(T cached, Func<T, bool> predicate)\n{\n return predicate(cached);\n}\n\npublic static Expression<Func<Potion, bool>>\n ContainsIngredients(string ingredientType, params string[] ingredients)\n{\n var predicate = PredicateBuilder.False<Potion>();\n // Here, I'm accessing p.Ingredients several times in one \n // expression. Is there any way to cache this value and\n // reference the cached value in the expression?\n foreach (var ingredient in ingredients)\n {\n var temp = ingredient;\n predicate = predicate.Or (\n p => TestWith(p.Ingredients,\n i => i != null &&\n i.Contains(ingredientType) &&\n i.Get(ingredientType).Contains(temp));\n }\n\n return predicate;\n}\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9825/" ]
66,385
<p>What is a recommended architecture for providing storage for a dynamic logical database schema?</p> <p>To clarify: Where a system is required to provide storage for a model whose schema may be extended or altered by its users once in production, what are some good technologies, database models or storage engines that will allow this? </p> <p>A few possibilities to illustrate:</p> <ul> <li>Creating/altering database objects via dynamically generated DML</li> <li>Creating tables with large numbers of sparse physical columns and using only those required for the 'overlaid' logical schema</li> <li>Creating a 'long, narrow' table that stores dynamic column values as rows that then need to be pivoted to create a 'short, wide' rowset containing all the values for a specific entity</li> <li>Using a BigTable/SimpleDB PropertyBag type system</li> </ul> <p>Any answers based on real world experience would be greatly appreciated</p>
[ { "answer_id": 66458, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 2, "selected": false, "text": "CREATE TABLE data (\n id INTEGER NOT NULL AUTO_INCREMENT,\n key VARCHAR(255),\n data TEXT,\n\n PRIMARY KEY (id)\n);\n" }, { "answer_id": 22207828, "author": "Oliver Konig", "author_id": 2290188, "author_profile": "https://Stackoverflow.com/users/2290188", "pm_score": 2, "selected": false, "text": "select id, password from user where email_address = \"[email protected]\"\n select id, password from user where email_address = \"[email protected]\"\n select \n parent_id, -- user id\n data -- password\nfrom \n items \nwhere \n spec_id = 3 -- make sure this is a 'password' item\n and \n parent_id in \n ( -- get the 'user' item to which this 'password' item belongs\n select \n id \n from \n items \n where \n spec_id = 1 -- make sure this is a 'user' item\n and \n id in \n ( -- fetch all item id's with the desired 'email_address' child item\n select \n parent_id -- id of the parent item of the 'email_address' item\n from \n items \n where \n spec_id = 2 -- make sure this is a 'email_address' item\n and\n data = \"[email protected]\" -- with the desired data value\n )\n )\n select \n parent_id, \n data \nfrom \n items \nwhere \n spec_id = (select id from specs where name = \"password\") \n and \n parent_id in (\n select \n id \n from \n items \n where \n spec_id = (select id from specs where name = \"user\") \n and \n id in (\n select \n parent_id \n from \n items \n where \n spec_id = (select id from specs where name = \"email_address\") \n and \n data = \"[email protected]\"\n )\n )\n" }, { "answer_id": 46202802, "author": "FloverOwe", "author_id": 6885037, "author_profile": "https://Stackoverflow.com/users/6885037", "pm_score": 1, "selected": false, "text": "<employee lastname=\"Li\" firstname=\"Joe\" salary=\"120000\" id=\"318\"/>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6199/" ]
66,402
<p>I need to calculate <code>Math.exp()</code> from java very frequently, is it possible to get a native version to run faster than <strong>java</strong>'s <code>Math.exp()</code>??</p> <p>I tried just jni + C, but it's slower than just plain <strong>java</strong>.</p>
[ { "answer_id": 66439, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 3, "selected": false, "text": "Math.exp()" }, { "answer_id": 424985, "author": "martinus", "author_id": 48181, "author_profile": "https://Stackoverflow.com/users/48181", "pm_score": 4, "selected": false, "text": "public static double exp(double val) {\n final long tmp = (long) (1512775 * val + (1072693248 - 60801));\n return Double.longBitsToDouble(tmp << 32);\n}\n" }, { "answer_id": 23963586, "author": "Renaud", "author_id": 125617, "author_profile": "https://Stackoverflow.com/users/125617", "pm_score": 2, "selected": false, "text": "FastMath.exp(double x) Math.exp() 0.75s for Math.exp sum=1.7182816693332244E7\n 0.40s for FastMath.exp sum=1.7182816693332244E7\n Lookup intVal = exp(int(x))\n Lookup fracVal = exp(int(x-int(x) / 1024.0) * 1024.0 );\n Compute z as the exponential of the remaining bits by a polynomial minus one\n exp(x) = intVal * fracVal * (1 + z)\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9774/" ]
66,420
<p>When using Google Chrome, I want to debug some JavaScript code. How can I do that?</p>
[ { "answer_id": 66431, "author": "Omer van Kloeten", "author_id": 4979, "author_profile": "https://Stackoverflow.com/users/4979", "pm_score": 9, "selected": false, "text": "debugger;\n" }, { "answer_id": 16038207, "author": "anand", "author_id": 635231, "author_profile": "https://Stackoverflow.com/users/635231", "pm_score": -1, "selected": false, "text": "console.log(data_to_be_displayed)" }, { "answer_id": 33366397, "author": "Venkat", "author_id": 5395773, "author_profile": "https://Stackoverflow.com/users/5395773", "pm_score": 2, "selected": false, "text": "press" }, { "answer_id": 54809391, "author": "Nestor Urquiza", "author_id": 399959, "author_profile": "https://Stackoverflow.com/users/399959", "pm_score": 0, "selected": false, "text": "chrome://inspect" }, { "answer_id": 58896583, "author": "Johan Stiven Hernandez Osorio", "author_id": 9401601, "author_profile": "https://Stackoverflow.com/users/9401601", "pm_score": 0, "selected": false, "text": "F12" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9587/" ]
66,422
<p>I need to rotate an image at 12 midnight every day from a group of 5-10 images. How can I go about doing this with JavaScript or jQuery or even PHP?</p>
[ { "answer_id": 66453, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": 1, "selected": false, "text": "<?php\nswitch(date('w'))\n {\n case '1':\n //Monday\n break;\n case '2':\n //Tuesday:\n break;\n...\n}\n?>\n" }, { "answer_id": 66494, "author": "DamienG", "author_id": 5720, "author_profile": "https://Stackoverflow.com/users/5720", "pm_score": 3, "selected": false, "text": "var images = new Array(\"image1.gif\", \"image2.jpg\", \"sky.jpg\", \"city.png\");\nvar dateDiff = new Date() - new Date(2008,01,01);\nvar imageIndex = Math.Round(dateDiff/1000/60/60/24) % images.length;\ndocument.GetElementById('imageId').setAttribute('src', images[imageIndex]);\n" }, { "answer_id": 66502, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 0, "selected": false, "text": "<img>" }, { "answer_id": 66545, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "var date = new Date();\nvar day = date.getDate(); // thats the day of month, use getDays() for day of week\n\ndocument.getElementById('someImage').src = '/images/foo/bar_' + (day % 10) + '.gif';\n" }, { "answer_id": 66558, "author": "Lucas Oman", "author_id": 6726, "author_profile": "https://Stackoverflow.com/users/6726", "pm_score": 1, "selected": false, "text": "<?php\n// starting date for rotation\n$startDate = '2008-09-15';\n// array of image filenames\n$images = array('file1.jpg','file2.jpg',...);\n\n$stamp = strtotime($startDate);\n$days = (time() - $stamp) / (60*60*24);\n$imageFilename = $images[$days % count($images)]\n?>\n\n<img src=\"<?php echo $imageFilename; ?>\"/>\n" }, { "answer_id": 66560, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 1, "selected": false, "text": "let number_of_files = 5\n\nrename current.jpg to number_of_files.jpg\n\nfor (x = 2 to number_of_files)\n rename x.jpg to (x-1).jpg\n\nrename 1.jpg to current.jpg\n <img src=\"path/to/current.jpg\" />\n" }, { "answer_id": 66576, "author": "Jimmy", "author_id": 4435, "author_profile": "https://Stackoverflow.com/users/4435", "pm_score": 0, "selected": false, "text": "$imgs = array(\"kitten.jpg\", \"puppy.gif\",\"Bob_Dole.png\"); \n$day_index = 365 * date(\"Y\") + date(\"Z\")\n\n...\n\n<img src=\"<? $imgs[$day_index % count($imgs)] ?>\" />\n" }, { "answer_id": 66725, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "var d=new Date();\nvar utc = d.getTime() + (d.getTimezoneOffset() * 60000);\nvar offset = -10; // set this to your locale's UTC offset\nvar desiredTime = utc + (3600000*offset);\nnew dd = new Date(desiredTime); \n$('rotatingimage').setProperty('src', dd.getDay() + '.jpg'); \n" }, { "answer_id": 68281, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 0, "selected": false, "text": "function getImageOfTheDay() {\n $myDir = \"path/to/images/\";\n\n // get a unique value for the day/year.\n // 15th Jan 2008 -> 10152008. 3 Feb -> 10342008, 31 Dec -> 13662008\n $day = sprintf(\"1%03d%d\", date('z'), date('Y'));\n\n // you could of course get gifs/pngs as well.\n // i'm just doing this for simplicity\n $jpgs = glob($myDir . \"*.jpg\");\n mt_srand($day);\n return $jpgs[mt_rand(0, count($jpgs) - 1)];\n}\n function getImageOfTheDay() {\n $myDir = \"path/to/images/\";\n $day = sprintf(\"1%03d%d\", date('z'), date('Y'));\n $jpgs = glob($myDir . \"*.jpg\");\n return $jpgs[$day % count($jpgs)];\n}\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9750/" ]
66,423
<p>I have a servlet that is used for many different actions, used in the <a href="http://java.sun.com/blueprints/patterns/FrontController.html" rel="noreferrer">Front Controller pattern</a>. Does anyone know if it is possible to tell if the data posted back to it is enctype="multipart/form-data"? I can't read the request parameters until I decide this, so I can't dispatch the request to the proper controller.</p> <p>Any ideas?</p>
[ { "answer_id": 66481, "author": "Loren Segal", "author_id": 6436, "author_profile": "https://Stackoverflow.com/users/6436", "pm_score": 5, "selected": true, "text": "Content-type multipart/form-data" }, { "answer_id": 66509, "author": "Kyle Boon", "author_id": 1486, "author_profile": "https://Stackoverflow.com/users/1486", "pm_score": 3, "selected": false, "text": "if (request.getContentType() != null && \n request.getContentType().toLowerCase().indexOf(\"multipart/form-data\") > -1 ) \n{\n << code block >>\n} \n" }, { "answer_id": 579519, "author": "Darren Hicks", "author_id": 59075, "author_profile": "https://Stackoverflow.com/users/59075", "pm_score": 4, "selected": false, "text": "if (request.getContentType() != null && request.getContentType().toLowerCase().indexOf(\"multipart/form-data\") > -1 ) {\n// Multipart logic here\n}\n" }, { "answer_id": 56460683, "author": "zb226", "author_id": 1529709, "author_profile": "https://Stackoverflow.com/users/1529709", "pm_score": 1, "selected": false, "text": "if (request != null \n && request.getContentType() != null \n && request.getContentType().toLowerCase(Locale.ENGLISH).startsWith(\"multipart/\")) {\n ...\n}\n org.apache.commons.lang3.StringUtils if (StringUtils.startsWithIgnoreCase(request.getContentType(), \"multipart/\")) { \n ... \n}\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4257/" ]
66,438
<p>I'm writing a mobile phone game using j2me. In this game, I am using multiple Canvas objects. For example, the game menu is a Canvas object, and the actual game is a Canvas object too. I've noticed that, on some devices, when I switch from one Canvas to another, e.g from the main menu to the game, the screen momentarily "flickers". I'm using my own double buffered Canvas.</p> <p>Is there anyway to avoid this?</p>
[ { "answer_id": 66742, "author": "Vivek", "author_id": 7418, "author_profile": "https://Stackoverflow.com/users/7418", "pm_score": 0, "selected": false, "text": "public class MyScreen extends Canvas {\n private Image osb;\n private Graphics osg;\n //...\n\n public MyScreen()\n {\n // if device is not double buffered\n // use image as a offscreen buffer\n if (!isDoubleBuffered())\n {\n osb = Image.createImage(screenWidth, screenHeight);\n osg = osb.getGraphics();\n osg.setFont(defaultFont);\n }\n }\n\n protected void paint(Graphics graphics)\n {\n if (!isDoubleBuffered())\n {\n // do your painting on off screen buffer first\n renderWorld(osg);\n\n // once done paint it at image on the real screen\n graphics.drawImage(osb, 0, 0, Tools.GRAPHICS_TOP_LEFT);\n }\n else\n {\n osg = graphics;\n renderWorld(graphics);\n }\n }\n}\n" }, { "answer_id": 68854, "author": "JaanusSiim", "author_id": 706, "author_profile": "https://Stackoverflow.com/users/706", "pm_score": 3, "selected": false, "text": "protected void paint(final Graphics g) {\n if(menu) {\n paintMenu(g);\n } else if (game) {\n paintGame(g);\n }\n}\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9771/" ]
66,446
<p>I am trying to achieve better performance for my Java SWT application, and I just found out it is possible to use OpenGL in SWT. It seems there are more than one Java binding for OpenGL. Which one do you prefer?</p> <p>Note that I have never used OpenGL before, and that the application needs to work on Windows, Linux and Mac OS X.</p>
[ { "answer_id": 68392, "author": "shoosh", "author_id": 9611, "author_profile": "https://Stackoverflow.com/users/9611", "pm_score": 3, "selected": false, "text": "import org.eclipse.swt.*;\nimport org.eclipse.swt.layout.*;\nimport org.eclipse.swt.widgets.*;\n\nimport javax.media.opengl.*;\nimport javax.media.opengl.glu.*;\n\nimport org.eclipse.swt.awt.SWT_AWT;\nimport org.eclipse.swt.events.*;\n\npublic class Main implements GLEventListener\n{\n public static void main(String[] args) \n {\n Display display = new Display();\n Main main = new Main();\n main.runMain(display);\n display.dispose();\n}\n\nvoid runMain(Display display)\n{\n final Shell shell = new Shell(display);\n shell.setText(\"Q*bert 3D - OpenGL Exercise\");\n GridLayout gridLayout = new GridLayout();\n gridLayout.marginHeight = 0;\n gridLayout.marginWidth = 0;\n\n shell.setLayout(gridLayout);\n\n // this allows us to set particular properties for the GLCanvas\n GLCapabilities glCapabilities = new GLCapabilities();\n\n glCapabilities.setDoubleBuffered(true);\n glCapabilities.setHardwareAccelerated(true);\n\n // instantiate the canvas\n final GLCanvas canvas = new GLCanvas(glCapabilities);\n\n // we can't use the default Composite because using the AWT bridge\n // requires that it have the property of SWT.EMBEDDED\n Composite composite = new Composite(shell, SWT.EMBEDDED);\n GridData ld = new GridData(GridData.FILL_BOTH);\n composite.setLayoutData(ld);\n\n // set the internal layout so our canvas fills the whole control\n FillLayout clayout = new FillLayout();\n composite.setLayout(clayout);\n\n // create the special frame bridge to AWT\n java.awt.Frame glFrame = SWT_AWT.new_Frame(composite);\n // we need the listener so we get the GL events\n canvas.addGLEventListener(this);\n\n // finally, add our canvas as a child of the frame\n glFrame.add(canvas);\n\n // show it all\n shell.open();\n // the event loop.\n while (!shell.isDisposed ()) {\n if (!display.readAndDispatch ()) display.sleep ();\n }\n}\n" }, { "answer_id": 4200153, "author": "Wade Walker", "author_id": 207245, "author_profile": "https://Stackoverflow.com/users/207245", "pm_score": 1, "selected": false, "text": "package name.wadewalker.onetriangle;\n\nimport org.eclipse.swt.SWT;\nimport org.eclipse.swt.events.PaintEvent;\nimport org.eclipse.swt.events.PaintListener;\nimport org.eclipse.swt.graphics.Rectangle;\nimport org.eclipse.swt.layout.FillLayout;\nimport org.eclipse.swt.opengl.GLCanvas;\nimport org.eclipse.swt.opengl.GLData;\nimport org.eclipse.swt.widgets.Composite;\nimport org.eclipse.swt.widgets.Display;\nimport org.eclipse.swt.widgets.Event;\nimport org.eclipse.swt.widgets.Listener;\nimport org.eclipse.swt.widgets.Shell;\n\nimport javax.media.opengl.GL;\nimport javax.media.opengl.GLProfile;\nimport javax.media.opengl.GL2;\nimport javax.media.opengl.GLContext;\nimport javax.media.opengl.GLDrawableFactory;\nimport javax.media.opengl.glu.GLU;\n\npublic class OneTriangle {\n\n public static void main(String [] args) {\n GLProfile.initSingleton( true );\n\n GLProfile glprofile = GLProfile.get( GLProfile.GL2 );\n\n Display display = new Display();\n Shell shell = new Shell( display );\n shell.setLayout( new FillLayout() );\n Composite composite = new Composite( shell, SWT.NONE );\n composite.setLayout( new FillLayout() );\n\n GLData gldata = new GLData();\n gldata.doubleBuffer = true;\n // need SWT.NO_BACKGROUND to prevent SWT from clearing the window\n // at the wrong times (we use glClear for this instead)\n final GLCanvas glcanvas = new GLCanvas( composite, SWT.NO_BACKGROUND, gldata );\n glcanvas.setCurrent();\n final GLContext glcontext = GLDrawableFactory.getFactory( glprofile ).createExternalGLContext();\n\n // fix the viewport when the user resizes the window\n glcanvas.addListener( SWT.Resize, new Listener() {\n public void handleEvent(Event event) {\n setup( glcanvas, glcontext );\n }\n });\n\n // draw the triangle when the OS tells us that any part of the window needs drawing\n glcanvas.addPaintListener( new PaintListener() {\n public void paintControl( PaintEvent paintevent ) {\n render( glcanvas, glcontext );\n }\n });\n\n shell.setText( \"OneTriangle\" );\n shell.setSize( 640, 480 );\n shell.open();\n\n while( !shell.isDisposed() ) {\n if( !display.readAndDispatch() )\n display.sleep();\n }\n\n glcanvas.dispose();\n display.dispose();\n }\n\n private static void setup( GLCanvas glcanvas, GLContext glcontext ) {\n Rectangle rectangle = glcanvas.getClientArea();\n\n glcanvas.setCurrent();\n glcontext.makeCurrent();\n\n GL2 gl = glcontext.getGL().getGL2();\n gl.glMatrixMode( GL2.GL_PROJECTION );\n gl.glLoadIdentity();\n\n // coordinate system origin at lower left with width and height same as the window\n GLU glu = new GLU();\n glu.gluOrtho2D( 0.0f, rectangle.width, 0.0f, rectangle.height );\n\n gl.glMatrixMode( GL2.GL_MODELVIEW );\n gl.glLoadIdentity();\n\n gl.glViewport( 0, 0, rectangle.width, rectangle.height );\n glcontext.release(); \n }\n\n private static void render( GLCanvas glcanvas, GLContext glcontext ) {\n Rectangle rectangle = glcanvas.getClientArea();\n\n glcanvas.setCurrent();\n glcontext.makeCurrent();\n\n GL2 gl = glcontext.getGL().getGL2();\n gl.glClear( GL.GL_COLOR_BUFFER_BIT );\n\n // draw a triangle filling the window\n gl.glLoadIdentity();\n gl.glBegin( GL.GL_TRIANGLES );\n gl.glColor3f( 1, 0, 0 );\n gl.glVertex2f( 0, 0 );\n gl.glColor3f( 0, 1, 0 );\n gl.glVertex2f( rectangle.width, 0 );\n gl.glColor3f( 0, 0, 1 );\n gl.glVertex2f( rectangle.width / 2, rectangle.height );\n gl.glEnd();\n\n glcanvas.swapBuffers();\n glcontext.release(); \n }\n}\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66446", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9843/" ]
66,455
<p>For most GUI's I've used, when a control that contains text gets the focus, the entire contents of the control are selected. This means if you just start typing, you completely replace the former contents.</p> <p>Example: You have spin control that is initialized with the value zero. You tab to it and type "1" The value in the control is now 1.</p> <p>With Swing, this doesn't happen. The text in the control is not selected and the carat appears at one end or another of the existing text. Continuing the above example:</p> <p>With a Swing JSpinner, when you tab to the spin control, the carat is at the left. You type "1" and the value in the control is now 10.</p> <p>This drives me, (and my users) up a wall, and I'd like to change it. Even more important, I'd like to change it globally so the new behavior applies to JTextField, JPasswordField, JFormattedTextField, JTextArea, JComboBox, JSpinner, and so on. The only way I have found to do this to add a FocusAdapter to each control and override the focusGained() method to Do The Right Thing[tm].</p> <p>There's gotta be an easier, and less fragile way. Please?</p> <p>EDIT: One additional piece of information for this particular case. The form I am working with was generated using Idea's form designer. That means I normally don't actually write the code to create the components. It is possible to tell Idea that you want to create them yourself, but that's a hassle I'd like to avoid.</p> <p>Motto: All good programmers are basically lazy.</p>
[ { "answer_id": 66645, "author": "rcreswick", "author_id": 3446, "author_profile": "https://Stackoverflow.com/users/3446", "pm_score": 2, "selected": false, "text": "public class AutoClearingTextField extends JTextField {\n final FocusListener AUTO_CLEARING_LISTENER = new FocusListener(){\n @Override\n public void focusLost(FocusEvent e) {\n //onFocusLost(e);\n }\n\n @Override\n public void focusGained(FocusEvent e) {\n selectAll();\n }\n };\n\n public AutoClearingTextField(String string) {\n super(string);\n addListener();\n }\n\n private void addListener() {\n addFocusListener(AUTO_CLEARING_LISTENER); \n }\n}\n" }, { "answer_id": 75244, "author": "shemnon", "author_id": 8020, "author_profile": "https://Stackoverflow.com/users/8020", "pm_score": 2, "selected": false, "text": "public class SelectAllListener implements FocusListener {\n private static INSTANCE = new SelectAllListener();\n\n public void focusLost(FocusEvent e) { }\n\n public void focusGained(FocusEvent e) {\n if (e.getSource() instanceof JTextComponent) { \n ((JTextComponent)e.getSource()).selectAll();\n }\n };\n\n public static void addSelectAllListener(JTextComponent tc) {\n tc.addFocusListener(INSTANCE);\n }\n\n public static void removeSelectAllListener(JTextComponent tc) {\n tc.removeFocusListener(INSTANCE);\n }\n}\n public static void addSelectAllListener(JSpinner spin) {\n if (spin.getEditor() instanceof JTextComponent) {\n addSelectAllListener((JTextComponent)spin.getEditor());\n }\n}\n\npublic static void addSelectAllListener(JComboBox combo) {\n JComponent editor = combo.getEditor().getEditorComponent();\n if (editor instanceof JTextComponent) {\n addSelectAllListener((JTextComponent)editor);\n }\n}\n" }, { "answer_id": 86170, "author": "Dale Wilson", "author_id": 391806, "author_profile": "https://Stackoverflow.com/users/391806", "pm_score": 2, "selected": true, "text": "void addTextFocusSelect(JComponent component){\n if(component instanceof JTextComponent){\n component.addFocusListener(new FocusAdapter() {\n @Override\n public void focusGained(FocusEvent event) {\n super.focusGained(event);\n JTextComponent component = (JTextComponent)event.getComponent();\n // a trick I found on JavaRanch.com\n // Without this, some components don't honor selectAll\n component.setText(component.getText());\n component.selectAll();\n }\n });\n\n }\n else\n {\n for(Component child: component.getComponents()){\n if(child instanceof JComponent){\n addTextFocusSelect((JComponent) child);\n }\n }\n }\n}\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/391806/" ]
66,475
<p>I've got a multiline textBox that I would like to have a label on the form displaying the current line and column position of, as Visual Studio does.</p> <p>I know I can get the line # with GetLineFromCharIndex, but how can I get the column # on that line?</p> <p>(I really want the Cursor Position on that line, not 'column', per se)</p>
[ { "answer_id": 66561, "author": "Omer van Kloeten", "author_id": 4979, "author_profile": "https://Stackoverflow.com/users/4979", "pm_score": 2, "selected": false, "text": "textBox.SelectionStart -\ntextBox.GetFirstCharIndexFromLine(textBox.GetLineFromCharIndex(textBox.SelectionStart))\n" }, { "answer_id": 66595, "author": "DamienG", "author_id": 5720, "author_profile": "https://Stackoverflow.com/users/5720", "pm_score": 5, "selected": true, "text": "int line = textbox.GetLineFromCharIndex(textbox.SelectionStart);\nint column = textbox.SelectionStart - textbox.GetFirstCharIndexFromLine(line);\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9857/" ]
66,505
<p>I hit this problem all the time. Suppose I am making a command line interface (Java or C#, the problem is the same I think, I will show C# here).</p> <ol> <li>I define an interface ICommand</li> <li>I create an abstract base class CommandBase which implements ICommand, to contain common code.</li> <li>I create several implementation classes, each extending the base class (and by extension the interface).</li> </ol> <p>Now - suppose that the interface specifies that all commands implement the Name property and the Execute method...</p> <p>For Name each of my instance classes must return a string that is the name of that command. That string ("HELP", "PRINT" etc) is static to the class concerned. What I would love to be able to do is define:</p> <p>public abstract static const string Name;</p> <p>However (sadly) you cannot define static members in an interface.</p> <p>I have struggled with this issue for years now (pretty much any place I have a family of similar classes) and so will post my own 3 possible solutions below for your votes. However since none of them is ideal I am hoping someone will post a more elegant solution.</p> <hr> <p>UPDATE:</p> <ol> <li>I can't get the code formatting to work properly (Safari/Mac?). Apologies.</li> <li><p>The example I am using is trivial. In real life there are sometimes dozens of implementing classes and several fields of this semi-static type (ie static to the implementing class).</p></li> <li><p>I forgot to mention - ideally I want to be able to query this information statically:</p> <p>string name = CommandHelp.Name;</p></li> </ol> <p>2 of my 3 proposed solutions require that the class be instantiated before you can find out this static information which is ugly.</p>
[ { "answer_id": 66546, "author": "Ewan Makepeace", "author_id": 9731, "author_profile": "https://Stackoverflow.com/users/9731", "pm_score": 0, "selected": false, "text": "public string Name \n{\n get {return COMMAND_NAME;}\n}\n" }, { "answer_id": 66557, "author": "Thomas Danecker", "author_id": 9632, "author_profile": "https://Stackoverflow.com/users/9632", "pm_score": 2, "selected": false, "text": "[Command(\"HELP\")]\nclass HelpCommand : ICommand\n{\n}\n" }, { "answer_id": 66602, "author": "Marcio Aguiar", "author_id": 4213, "author_profile": "https://Stackoverflow.com/users/4213", "pm_score": 1, "selected": false, "text": "public interface ICommand {\n String getName();\n}\n\npublic class RealCommand implements ICommand {\n public String getName() {\n return \"name\";\n }\n}\n" }, { "answer_id": 66611, "author": "Sunny Milenov", "author_id": 8220, "author_profile": "https://Stackoverflow.com/users/8220", "pm_score": 0, "selected": false, "text": "abstract class:\n\nprivate const string nameConstant = \"ABSTRACT\";\n\npublic string Name\n{\n get {return this.GetName();}\n}\n\nprotected virtual string GetName()\n{\n return MyAbstractClass.nameConstant;\n}\n\n----\n\nclass ChildClass : MyAbstractClass\n{\n private const string nameConstant = \"ChildClass\";\n\n protected override string GetName()\n {\n return ChildClass.nameConstant;\n }\n}\n" }, { "answer_id": 66618, "author": "Ewan Makepeace", "author_id": 9731, "author_profile": "https://Stackoverflow.com/users/9731", "pm_score": 0, "selected": false, "text": "public string Name\n{ \n get {return Name;}\n}\n public abstract class CommandBase(string commandName) : ICommand\n{\n name = commandName;\n}\n public class CommandHelp : CommandBase(COMMAND_NAME) {}\n" }, { "answer_id": 66631, "author": "Staale", "author_id": 3355, "author_profile": "https://Stackoverflow.com/users/3355", "pm_score": 0, "selected": false, "text": "interface A { abstract static NAME }\nclass B { NAME = \"HELP\" }\nclass C { NAME = \"PRINT\" }\n void test(A a) {\n a.NAME;\n}\n public enum Command {\n HELP { execute() }, PRINT { execute() };\n abstract void execute();\n}\n" }, { "answer_id": 66679, "author": "Jeromy Irvine", "author_id": 8223, "author_profile": "https://Stackoverflow.com/users/8223", "pm_score": 2, "selected": false, "text": "public abstract class MyBaseClass\n{\n public abstract string Name { get; protected set; }\n}\n\npublic class MyClass : MyBaseClass\n{\n public override string Name\n {\n get { return \"CommandName\"; }\n protected set { }\n }\n}\n" }, { "answer_id": 227578, "author": "Hallgrim", "author_id": 15454, "author_profile": "https://Stackoverflow.com/users/15454", "pm_score": 0, "selected": false, "text": "abstract class Command {\n abstract CommandInfo getInfo();\n}\n\nclass CommandInfo {\n string Name;\n string Description;\n Foo Bar;\n}\n\nclass RunCommand {\n static CommandInfo Info = new CommandInfo() { Name = \"Run\", Foo = new Foo(42) };\n\n override commandInfo getInfo() { return Info; }\n}\n RunCommand.Info.Name;\n getInfo().Name;\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9731/" ]
66,518
<p>I need to flip an image so that a character faces in the right direction. This needs to be done "on the fly' as they say. </p> <p>The issue I am having is that with Gif images, I seem to lose the transparency. (The background goes white)</p> <p>Below is the code: (Alternatively someone could send me to a good example)</p> <pre><code>$img = imagecreatefromgif("./unit.gif"); $size_x = imagesx($img); $size_y = imagesy($img); $temp = imagecreatetruecolor($size_x, $size_y); imagecolortransparent($img, imagecolorallocate($img, 0, 0, 0)); imagealphablending($img, false); imagesavealpha($img, true); $x = imagecopyresampled($temp, $img, 0, 0, ($size_x-1), 0, $size_x, $size_y, 0-$size_x, $size_y); if ($x) { $img = $temp; } else { die("Unable to flip image"); } header("Content-type: image/gif"); imagegif($img); imagedestroy($img); </code></pre>
[ { "answer_id": 66574, "author": "Alex M", "author_id": 9652, "author_profile": "https://Stackoverflow.com/users/9652", "pm_score": 1, "selected": false, "text": "mogrify -flop" }, { "answer_id": 66586, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 3, "selected": true, "text": "imagecolortransparent($img, imagecolorallocate($img, 0, 0, 0));\nimagealphablending($img, false);\nimagesavealpha($img, true);\n imagecolortransparent($temp, imagecolorallocate($img, 0, 0, 0));\nimagealphablending($temp, false);\nimagesavealpha($temp, true);\n" }, { "answer_id": 66765, "author": "Markus", "author_id": 2490, "author_profile": "https://Stackoverflow.com/users/2490", "pm_score": 2, "selected": false, "text": "$size_x = imagesx($img);\n$size_y = imagesy($img);\n\n$temp = imagecreatetruecolor($size_x, $size_y);\n\nimagecolortransparent($temp, imagecolorallocate($temp, 0, 0, 0));\nimagealphablending($temp, false);\nimagesavealpha($temp, true);\n$x = imagecopyresampled($temp, $img, 0, 0, ($size_x-1), 0, $size_x, $size_y, 0-$size_x, $size_y);\nif ($x) {\n $img = $temp;\n}\nelse {\n die(\"Unable to flip image\");\n}\n\nheader(\"Content-type: image/gif\");\nimagegif($img);\nimagedestroy($img);\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2490/" ]
66,528
<p>I have the following Java 6 code:</p> <pre><code> Query q = em.createNativeQuery( "select T.* " + "from Trip T join Itinerary I on (T.itinerary_id=I.id) " + "where I.launchDate between :start and :end " + "or ADDDATE(I.launchDate, I.equipmentPullDayOfTrip) between :start and :end", "TripResults" ); q.setParameter( "start", range.getStart(), TemporalType.DATE ); q.setParameter( "end", range.getEnd(), TemporalType.DATE ); @SqlResultSetMapping( name="TripResults", entities={ @EntityResult( entityClass=TripEntity.class ), @EntityResult( entityClass=CommercialTripEntity.class ) } ) </code></pre> <p>I receive a syntax error on the last closing right parenthesis. Eclipse gives: "Insert EnumBody to complete block statement" and "Insert enum Identifier to complete EnumHeaderName". Similar syntax error from javac.</p> <p>What am I doing wrong?</p>
[ { "answer_id": 66697, "author": "Jim Kiley", "author_id": 7178, "author_profile": "https://Stackoverflow.com/users/7178", "pm_score": 2, "selected": true, "text": "@SqlResultSetMapping( name=\"TripResults\",\n entities={\n @EntityResult( entityClass=TripEntity.class ),\n @EntityResult( entityClass=CommercialTripEntity.class )\n }\n )\npublic class Foo {\n public void bogus() {\n Query q = em.createNativeQuery( \n \"select T.* \" +\n \"from Trip T join Itinerary I on (T.itinerary_id=I.id) \" +\n \"where I.launchDate between :start and :end \" +\n \"or ADDDATE(I.launchDate, I.equipmentPullDayOfTrip) between :start and :end\",\n \"TripResults\" );\n\n q.setParameter( \"start\", range.getStart(), TemporalType.DATE );\n q.setParameter( \"end\", range.getEnd(), TemporalType.DATE );\n }\n}\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
66,540
<p>I know that garbage collection is automated in Java. But I understood that if you call <code>System.gc()</code> in your code that the JVM may or may not decide to perform garbage collection at that point. How does this work precisely? On what basis/parameters exactly does the JVM decide to do (or not do) a GC when it sees <code>System.gc()</code>?</p> <p>Are there any examples in which case it's a good idea to put this in your code?</p>
[ { "answer_id": 66582, "author": "Patrick", "author_id": 429, "author_profile": "https://Stackoverflow.com/users/429", "pm_score": 4, "selected": false, "text": "System.gc() Map<String,<LinkedList>>" }, { "answer_id": 66601, "author": "DustinB", "author_id": 7888, "author_profile": "https://Stackoverflow.com/users/7888", "pm_score": 5, "selected": false, "text": "System.gc() System.gc()" }, { "answer_id": 66692, "author": "David Schlosnagle", "author_id": 1750, "author_profile": "https://Stackoverflow.com/users/1750", "pm_score": 4, "selected": false, "text": "System.gc() System.gc() -XX:+DisableExplicitGC" }, { "answer_id": 534040, "author": "Peter Lawrey", "author_id": 57695, "author_profile": "https://Stackoverflow.com/users/57695", "pm_score": 3, "selected": false, "text": "ByteBuffer.allocateDirect()" }, { "answer_id": 11649198, "author": "Shervin Asgari", "author_id": 37298, "author_profile": "https://Stackoverflow.com/users/37298", "pm_score": 2, "selected": false, "text": "System.gc()" }, { "answer_id": 16251925, "author": "Naveen", "author_id": 2213155, "author_profile": "https://Stackoverflow.com/users/2213155", "pm_score": 2, "selected": false, "text": "Garbage Collection Java System.gc() Runtime.getRuntime().gc() Java" }, { "answer_id": 16496206, "author": "Pierre Laporte", "author_id": 1469061, "author_profile": "https://Stackoverflow.com/users/1469061", "pm_score": 5, "selected": false, "text": "System.gc() System.gc() System.gc() System.gc() System.gc()" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
66,542
<p>How do I get started?</p>
[ { "answer_id": 1685449, "author": "Lauri Oherd", "author_id": 9615, "author_profile": "https://Stackoverflow.com/users/9615", "pm_score": 4, "selected": true, "text": "\n(ns example\n (:require [clojure.contrib.sql :as sql])\n (:import [java.sql Types]))\n\n(def devdb {:classname \"oracle.jdbc.driver.OracleDriver\"\n :subprotocol \"oracle\"\n :subname \"thin:username/password@localhost:1509:devdb\"\n :create true})\n\n(defn exec-ora-stored-proc [input-param db callback]\n (sql/with-connection db\n (with-open [stmt (.prepareCall (sql/connection) \"{call some_schema.some_package.test_proc(?, ?, ?)}\")]\n (doto stmt\n (.setInt 1 input-param)\n (.registerOutParameter 2 Types/INTEGER)\n (.registerOutParameter 3 oracle.jdbc.driver.OracleTypes/CURSOR)\n (.execute))\n (callback (. stmt getInt 2) (. stmt getObject 3)))))\n\n(exec-ora-stored-proc\n 123 ;;input param value\n devdb\n (fn [err-code res-cursor]\n (println (str \"ret_code: \" err-code))\n ;; prints returned refcursor rows\n (let [resultset (resultset-seq res-cursor)]\n (doseq [rec resultset]\n (println rec)))))\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9615/" ]
66,544
<p>I want to write a small utility to call arbitrary functions from a C shared library. User should be able to list all the exported functions similar to what objdump or nm does. I checked these utilities' source but they are intimidating. Couldn't find enough information on google, if dl library has this functionality either.</p> <p>(Clarification edit: I don't want to just call a function which is known beforehand. I will appreciate an example fragment along your answer.)</p>
[ { "answer_id": 68010, "author": "gnkdl_gansklgna", "author_id": 10470, "author_profile": "https://Stackoverflow.com/users/10470", "pm_score": -1, "selected": false, "text": "ld.so ld-linux.so dyld" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7988/" ]
66,606
<p>I'm trying to find <a href="http://httpd.apache.org/docs/2.0/programs/ab.html" rel="noreferrer">ab - Apache HTTP server benchmarking tool</a> for Ubuntu, I'm hoping there's a package I can install for it. I decided I need to do some simple load testing on my applications.</p>
[ { "answer_id": 66617, "author": "Brian Phillips", "author_id": 7230, "author_profile": "https://Stackoverflow.com/users/7230", "pm_score": 8, "selected": true, "text": "% sudo apt-get install apache2-utils ab \n% ab\nThe program 'ab' is currently not installed. You can install it by typing:\nsudo apt-get install apache2-utils\nbash: ab: command not found\n" }, { "answer_id": 1199848, "author": "0x89", "author_id": 147058, "author_profile": "https://Stackoverflow.com/users/147058", "pm_score": 4, "selected": false, "text": "$ sudo aptitude install apt-file\n$ sudo apt-file update\n$ apt-file search bin/ab\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/339/" ]
66,610
<p>For a particular project I have, no server side code is allowed. How can I create the web site in php (with includes, conditionals, etc) and then have that converted into a static html site that I can give to the client?</p> <p>Update: Thanks to everyone who suggested wget. That's what I used. I should have specified that I was on a PC, so I grabbed the windows version from here: <a href="http://gnuwin32.sourceforge.net/packages/wget.htm" rel="noreferrer">http://gnuwin32.sourceforge.net/packages/wget.htm</a>.</p>
[ { "answer_id": 66652, "author": "millenomi", "author_id": 6061, "author_profile": "https://Stackoverflow.com/users/6061", "pm_score": 0, "selected": false, "text": "find site_folder -name \\*.static.php -print -exec Staticize {} \\;\n # This replaces .static.php with .html\nTARGET_NAME=\"`dirname \"$1\"`/\"`basename \"$1\" .static.php`\".html\nphp \"$1\" > \"$TARGET_NAME\"\n" }, { "answer_id": 66667, "author": "Jake McGraw", "author_id": 302, "author_profile": "https://Stackoverflow.com/users/302", "pm_score": 6, "selected": true, "text": "wget -k -K -E -r -l 10 -p -N -F -nH http://website.com/\n" }, { "answer_id": 66712, "author": "Raynet", "author_id": 4294, "author_profile": "https://Stackoverflow.com/users/4294", "pm_score": 2, "selected": false, "text": "ob_start();\n $page_html = ob_get_contents();\nob_end_clean();\nfile_put_contents($path_where_to_save_files . $_SERVER['PHP_SELF'], $page_html);\n somepage.php?var1=hello&var2=hullo\n somepage_e7537aacdbba8ad3ff309b3de1da69e1.html\n" }, { "answer_id": 66799, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 1, "selected": false, "text": "php myFile.php > myFile.html php myFile.php?abc=1 file_get_contents() file() md5_file()" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3741/" ]
66,622
<p>I need to enumerate though generic IList&lt;> of objects. The contents of the list may change, as in being added or removed by other threads, and this will kill my enumeration with a "Collection was modified; enumeration operation may not execute."</p> <p>What is a good way of doing threadsafe foreach on a IList&lt;>? prefferably without cloning the entire list. It is not possible to clone the actual objects referenced by the list.</p>
[ { "answer_id": 66653, "author": "Jason Punyon", "author_id": 6212, "author_profile": "https://Stackoverflow.com/users/6212", "pm_score": 2, "selected": false, "text": "\nlock(collection){\n foreach (object o in collection){\n ...\n }\n}\n" }, { "answer_id": 66689, "author": "Forgotten Semicolon", "author_id": 1960, "author_profile": "https://Stackoverflow.com/users/1960", "pm_score": 2, "selected": false, "text": "ICollection MyCollection;\n// Instantiate and populate the collection\nlock(MyCollection.SyncRoot) {\n // Some operation on the collection, which is now thread safe.\n}\n" }, { "answer_id": 54828413, "author": "folmerbrem", "author_id": 3046475, "author_profile": "https://Stackoverflow.com/users/3046475", "pm_score": 1, "selected": false, "text": "foreach(var p in Points)\n{\n // work with p...\n}\n for(int i = 0; i < Points.Count; i ++)\n{\n Point p = Points[i];\n // work with p...\n}\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3263/" ]
66,636
<p>I would like to make a child class that has a method of the parent class where the method is a 'classmethod' in the child class but <strong>not</strong> in the parent class.</p> <p>Essentially, I am trying to accomplish the following:</p> <pre><code>class foo(Object): def meth1(self, val): self.value = val class bar(foo): meth1 = classmethod(foo.meth1) </code></pre>
[ { "answer_id": 66847, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 3, "selected": true, "text": "def convert_to_classmethod(method):\n return classmethod(method.im_func)\n\nclass bar(foo):\n meth1 = convert_to_classmethod(foo.meth1)\n" }, { "answer_id": 66936, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "bar1 = bar()\nbar1.meth1(\"xyz\")\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9940/" ]
66,643
<p>Is there a way to detect, from within the finally clause, that an exception is in the process of being thrown?</p> <p>See the example below:</p> <pre><code> try { // code that may or may not throw an exception } finally { SomeCleanupFunctionThatThrows(); // if currently executing an exception, exit the program, // otherwise just let the exception thrown by the function // above propagate } </code></pre> <p>or is ignoring one of the exceptions the only thing you can do?</p> <p>In C++ it doesn't even let you ignore one of the exceptions and just calls terminate(). Most other languages use the same rules as java.</p>
[ { "answer_id": 66664, "author": "zxcv", "author_id": 9628, "author_profile": "https://Stackoverflow.com/users/9628", "pm_score": -1, "selected": false, "text": "try {\n // code that may or may not throw an exception\n} catch {\n// catch block must exist.\nfinally {\n SomeCleanupFunctionThatThrows();\n// this portion is ran after catch block finishes\n}\n" }, { "answer_id": 66673, "author": "ReaperUnreal", "author_id": 4218, "author_profile": "https://Stackoverflow.com/users/4218", "pm_score": 1, "selected": false, "text": "try {\n // ...\n} finally {\n try {\n SomeCleanupFunctionThatThrows();\n } catch(Throwable t) { //or catch whatever you want here\n // exception handling code, or just ignore it\n }\n}\n" }, { "answer_id": 66705, "author": "Chris B.", "author_id": 9161, "author_profile": "https://Stackoverflow.com/users/9161", "pm_score": 5, "selected": true, "text": "boolean exceptionThrown = true;\ntry {\n mightThrowAnException();\n exceptionThrown = false;\n} finally {\n if (exceptionThrown) {\n // Whatever you want to do\n }\n}\n" }, { "answer_id": 66706, "author": "Rob Dickerson", "author_id": 7530, "author_profile": "https://Stackoverflow.com/users/7530", "pm_score": 0, "selected": false, "text": "boolean exceptionThrown = false;\ntry {\n // ...\n} catch(Throwable t) {\n exceptionThrown = true;\n // ...\n} finally {\n try {\n SomeCleanupFunctionThatThrows();\n } catch(Throwable t) { \n if(exceptionThrown) ...\n }\n}\n" }, { "answer_id": 66740, "author": "Tim Frey", "author_id": 1471, "author_profile": "https://Stackoverflow.com/users/1471", "pm_score": 3, "selected": false, "text": "try {\n doSomethingDangerous(); // can throw exception\n onSuccess();\n} catch (Exception ex) {\n onFailure();\n}\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5963/" ]
66,649
<p>I am looking for some JavaScript plugin (preferably jQuery) to be able to scroll through an image, in the same way that <a href="http://maps.google.com" rel="noreferrer">Google Maps</a> works.</p> <p>I can make the image draggable but then I see the whole image while dragging even if the parent div is <code>overflow:hidden</code>.</p> <p>Any help would be greatly appreciated!</p>
[ { "answer_id": 96641, "author": "NickFitz", "author_id": 16782, "author_profile": "https://Stackoverflow.com/users/16782", "pm_score": 0, "selected": false, "text": "clip: rect(5px, 40px, 45px, 5px);\n clip: rect(5px 40px 45px 5px);\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5838/" ]
66,671
<p>I've gotten comfy with SVN, and now I need a way to deploy my code to staging or live servers more easily. I'd also like some method for putting build info in the footer of this site to aid in testing. Site is PHP/MySQL.</p>
[ { "answer_id": 66717, "author": "Staale", "author_id": 3355, "author_profile": "https://Stackoverflow.com/users/3355", "pm_score": 2, "selected": false, "text": "svn propset svn:keywords \"Rev\" file.txt\n $Rev$\n" }, { "answer_id": 66741, "author": "Loren Segal", "author_id": 6436, "author_profile": "https://Stackoverflow.com/users/6436", "pm_score": 0, "selected": false, "text": "svn co svn up ssh [email protected] svn up /path/to/project svn export up" }, { "answer_id": 137805, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "# get the svn revision number and create a RELEASE file\nsvnvers=`svnversion .`\necho \"version: $svnvers\"\necho \"<release><development>0</development><revision>$svnvers</revision></release>\" > RELEASE\n\n# remove all .svn directories\nfind . -name .svn -exec rm -rf {} \\;\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7853/" ]
66,677
<p>I'm looking for a dead simple mailing list (unix friendly). Robustness, fine-grained configurability, "enterprise-readiness" (whatever that means) are not requirements. I just need to set up a tiny mailing list for a few friends. Rather than hack something up myself, I was wondering if anybody knows of anything already out there with a similar goal? </p> <p>I should note right now that I <strong>don't</strong> want an externally hosted mailing list -- it needs to be software I can install and run on my server. I know of many places I can host a mailing list at (Google/Yahoo groups), but it would be nice to keep the data local.</p>
[ { "answer_id": 66780, "author": "Michael Ridley", "author_id": 4838, "author_profile": "https://Stackoverflow.com/users/4838", "pm_score": 4, "selected": true, "text": "/etc/aliases /etc/aliases mylist: [email protected], [email protected], \\\n [email protected]\n newaliases" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6436/" ]
66,720
<p>I'm looking for a tool that will render a RDF graph in a reasonably useful graphic format. The primary purpose of the graphic format being inclusion into a PowerPoint slide or printing on a large plotter for management review.</p> <p>I am currently using TopBraid Composer which does a reasonably well at visualizing a single entity but doesn't seem to have a clear way of visualizing the entire graph (as a whole).</p> <p>Anyone know of any good solutions to this problem?</p> <p><img src="https://i.stack.imgur.com/2C2Q6.jpg" alt="TopBraid Composer Graph view screenshot"></p>
[ { "answer_id": 44326441, "author": "dr0i", "author_id": 1579915, "author_profile": "https://Stackoverflow.com/users/1579915", "pm_score": 2, "selected": false, "text": "$ rapper --input ntriples $fname.nt --output dot > $fname.dot\n$ dot -Tpng $fname.dot > $fname.png" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3957/" ]
66,727
<p>I have a bunch of legacy documents that are HTML-like. As in, they look like HTML, but have additional made up tags that aren't a part of HTML</p> <pre><code>&lt;strong&gt;This is an example of a &lt;pseud-template&gt;fake tag&lt;/pseud-template&gt;&lt;/strong&gt; </code></pre> <p>I need to parse these files. PHP is the only only tool available. The documents don't come close to being well formed XML. </p> <p>My original thought was to use the loadHTML methods on PHPs DOMDocument. However, these methods choke on the make up HTML tags, and will refuse to parse the string/file.</p> <pre><code>$oDom = new DomDocument(); $oDom-&gt;loadHTML("&lt;strong&gt;This is an example of a &lt;pseud-template&gt;fake tag&lt;/pseud-template&gt;&lt;/strong&gt;"); //gives us DOMDocument::loadHTML() [function.loadHTML]: Tag pseud-template invalid in Entity, line: 1 occured in .... </code></pre> <p>The only solution I've been able to come up with is to pre-process the files with string replacement functions that will remove the invalid tags and replace them with a valid HTML tag (maybe a span with an id of the tag name).</p> <p>Is there a more elegant solution? A way to let DOMDocument know about additional tags to consider as valid? Is there a different, robust HTML parsing class/object out there for PHP?</p> <p>(if it's not obvious, I don't consider regular expressions a valid solution here)</p> <p><strong>Update</strong>: The information in the fake tags is part of the goal here, so something like Tidy isn't an option. Also, I'm after something that does the some level, if not all, of well-formedness cleanup for me, which is why I was looking the DomDocument's loadHTML method in the first place.</p>
[ { "answer_id": 67115, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 1, "selected": false, "text": "DOMDocument->load()" }, { "answer_id": 69383, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 0, "selected": false, "text": "blink $code = str_replace(\"<pseudo-tag>\", \"<blink rel=\\\"pseudo-tag\\\">\", $code);\n// and then back again...\n$code = preg_replace('<blink rel=\"(.*?)\">', '<\\1>', $code);\n" }, { "answer_id": 3613335, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 4, "selected": true, "text": "libxml_use_internal_errors libxml_use_internal_errors(true);\n$doc = new DomDocument();\n$doc->loadHTML(\"<strong>This is an example of a <pseud-template>fake tag</pseud-template></strong>\");\nlibxml_use_internal_errors(false);\n libxml_get_errors" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4668/" ]
66,730
<p>I've created a python object, but I want to send signals on it. I made it inherit from gobject.GObject, but there doesn't seem to be any way to create a new signal on my object.</p>
[ { "answer_id": 66883, "author": "Sebastian Rittau", "author_id": 7779, "author_profile": "https://Stackoverflow.com/users/7779", "pm_score": 2, "selected": false, "text": "import gobject\n\nclass MyGObjectClass(gobject.GObject):\n ...\n\ngobject.signal_new(\"signal-name\", MyGObjectClass, gobject.SIGNAL_RUN_FIRST,\n None, (str, int))\n" }, { "answer_id": 67743, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": 5, "selected": true, "text": "class MyGObjectClass(gobject.GObject):\n __gsignals__ = {\n \"some-signal\": (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )),\n }\n gobject.signal_new" }, { "answer_id": 126355, "author": "Johan Dahlin", "author_id": 14337, "author_profile": "https://Stackoverflow.com/users/14337", "pm_score": 2, "selected": false, "text": "from kiwi.utils import gsignal\n\nclass MyObject(gobject.GObject):\n gsignal('signal-name')\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8453/" ]
66,743
<p>Are there any free (non-GPL) libraries for .NET that provide IMAP4 server side functionality?</p> <p>E.g. handles the socket level and message handshaking so that an IMAP4 client (such as outlook) can retrieve, read, edit and/or delete messages. </p> <p>I am not trying to connect to an IMAP4 server, I'd like the assistance to implement one.</p>
[ { "answer_id": 299845, "author": "Martin Vobr", "author_id": 16132, "author_profile": "https://Stackoverflow.com/users/16132", "pm_score": 0, "selected": false, "text": "* SMTP/POP3/IMAP4/WebMail\n* IP access filtering\n* User mailbox size limit\n* Supports XML or MSSQL databases\n* Nice GUI for administation\n* Well commented source code included\n * All basic smtp features\n* Supports multiple domains\n* Supports multiple e-address for one mailbox\n* Supports aliases(Mailing lists). Supports public and private \n (needs authentication) lists.\n* Supports email routing. eg *ivar* pattern routes all addresses containing \n ivar to specified mailbox or remote address\n* SMTP AUTH (LOGIN CRAM-MD5) (supported authentication types)\n* SMTP SIZE, PIPELINING, 8BITMIME, CHUNCKING support\n* SMTP custom message filters\n* Relay can be controlled by IP access or authentication\n * All basic pop3 features\n* APOP command for secure authentication\n* POP3 AUTH (LOGIN CRAM-MD5) (supported authentication types)\n* POP3 remote accounts\n * Standalone webmail, can be used any with IMAP based mailserver\n* Supports XML or MSSQL databases\n* Multiple UI languages\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66743", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7093/" ]
66,750
<p>Here is a quick test program:</p> <pre><code> public static void main( String[] args ) { Date date = Calendar.getInstance().getTime(); System.out.println("Months:"); printDate( "MMMM", "en", date ); printDate( "MMMM", "es", date ); printDate( "MMMM", "fr", date ); printDate( "MMMM", "de", date ); System.out.println("Days:"); printDate( "EEEE", "en", date ); printDate( "EEEE", "es", date ); printDate( "EEEE", "fr", date ); printDate( "EEEE", "de", date ); } public static void printDate( String format, String locale, Date date ) { System.out.println( locale + ": " + (new SimpleDateFormat( format, new Locale( locale ) )).format( date ) ); } </code></pre> <p>The output is:</p> <p><code> Months: en: September es: septiembre fr: septembre de: September Days: en: Monday es: lunes fr: lundi de: Montag</code></p> <p>How can I control the capitalization of the names. For some reason the Spanish and French always seem to return names that start with a lowercase letter.</p>
[ { "answer_id": 45249515, "author": "Basil Bourque", "author_id": 642706, "author_profile": "https://Stackoverflow.com/users/642706", "pm_score": 3, "selected": false, "text": "getDisplayName Month.from( LocalDate.now( ZoneId.of( \"Pacific/Auckland\" ) ) ) // Get current month.\n .getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) // Localize automatically. Specify `Locale` to determine human language and cultural norms for translation. \n LocalDate.now( ZoneId.of( \"Pacific/Auckland\" ) ) // Get current date as seen by people in a certain region (time zone).\n .getDayOfWeek() // Get the day-of-week as a pre-defined `DayOfWeek` enum object.\n .getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH )\n LocalDate continent/region America/Montreal Africa/Casablanca Pacific/Auckland EST IST ZoneId z = ZoneId.of( \"Asia/Kolkata\" );\nLocalDate today = LocalDate.now( z );\n Month DayOfWeek getDisplayName TextStyle Locale Locale Month m = today.getMonth() ;\nString mNameQuébec = m.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) ; \nString mNameGermany = m.getDisplayName( TextStyle.FULL , Locale.GERMANY ) ; \n DayOfWeek dow = today.getDayOfWeek() ;\nString dowNameQuébec = dow.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) ; \nString dowNameGermany = dow.getDisplayName( TextStyle.FULL , Locale.GERMANY ) ; \n java.util.Date Calendar SimpleDateFormat Interval YearWeek YearQuarter" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9661/" ]
66,770
<p>Whenever I run rspec tests for my Rails application it takes forever and a day of overhead before it actually starts running tests. Why is rspec so slow? Is there a way to speed up Rails' initial load or single out the part of my Rails app I need (e.g. ActiveRecord stuff only) so it doesn't load absolutely everything to run a few tests?</p>
[ { "answer_id": 67678, "author": "Scott Matthewman", "author_id": 10267, "author_profile": "https://Stackoverflow.com/users/10267", "pm_score": 6, "selected": true, "text": "script/spec script/spec_server -X" }, { "answer_id": 68538, "author": "Pelle", "author_id": 10724, "author_profile": "https://Stackoverflow.com/users/10724", "pm_score": 2, "selected": false, "text": "sudo gem install pelle-rspactor\n" }, { "answer_id": 74278, "author": "Jean", "author_id": 7898, "author_profile": "https://Stackoverflow.com/users/7898", "pm_score": 2, "selected": false, "text": "rake test:recent \n rake test:rspec:recent\n" }, { "answer_id": 78867, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 2, "selected": false, "text": "rake spec db:test:prepare rake:test:units spec cd railsapp\nspec spec # run all specs without rebuilding the whole damn database\nspec spec/models # run model specs only\n\ncd spec\nspec controllers/user* # run specs for controllers that start with user\n" }, { "answer_id": 282606, "author": "Nappy", "author_id": 34652, "author_profile": "https://Stackoverflow.com/users/34652", "pm_score": 2, "selected": false, "text": "spec_server autospec autotest" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8344/" ]
66,773
<p>How can i add a line break to the text area in a html page? i use VB.net for server side coding.</p>
[ { "answer_id": 66815, "author": "Loren Segal", "author_id": 6436, "author_profile": "https://Stackoverflow.com/users/6436", "pm_score": 5, "selected": false, "text": "<textarea>Hello\n\n\nBybye</textarea>\n" }, { "answer_id": 66826, "author": "Forgotten Semicolon", "author_id": 1960, "author_profile": "https://Stackoverflow.com/users/1960", "pm_score": 2, "selected": false, "text": "\\r\\n System.Environment.NewLine" }, { "answer_id": 66827, "author": "Garry Shutler", "author_id": 6369, "author_profile": "https://Stackoverflow.com/users/6369", "pm_score": 1, "selected": false, "text": "TextArea.Text = \"Line 1\" & vbCrLf & \"Line 2\"\n" }, { "answer_id": 66842, "author": "SpoonMeiser", "author_id": 1577190, "author_profile": "https://Stackoverflow.com/users/1577190", "pm_score": 2, "selected": false, "text": "<textarea>\nThis is a text area\nline breaks are automatic\n</textarea>\n <p>\n This is some text\n</p>\n<p>\n This is some more\n</p>\n" }, { "answer_id": 70108, "author": "user11334", "author_id": 11334, "author_profile": "https://Stackoverflow.com/users/11334", "pm_score": 2, "selected": false, "text": "<br />" }, { "answer_id": 3149374, "author": "jonas", "author_id": 380063, "author_profile": "https://Stackoverflow.com/users/380063", "pm_score": 7, "selected": true, "text": "&#013;&#010;" }, { "answer_id": 51655678, "author": "Dice", "author_id": 10157982, "author_profile": "https://Stackoverflow.com/users/10157982", "pm_score": 1, "selected": false, "text": "/** PHP code */\n<?php\n $string = \"the string with linebreaks\";\n $string = strtr($string,array(\".\"=>\".\\r\\r\",\":\"=>\" : \\r\",\"-\"=>\"\\r - \"));\n?>\n .your_textarea_class {\nstyle='white-space:pre-wrap';\n}\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/747/" ]
66,800
<p>I've been using make and makefiles for many many years, and although the concept is sound, the implementation has something to be desired.</p> <p>Has anyone found any good alternatives to make that don't overcomplicate the problem?</p>
[ { "answer_id": 15550721, "author": "Hotschke", "author_id": 1057593, "author_profile": "https://Stackoverflow.com/users/1057593", "pm_score": 3, "selected": false, "text": "ninja tup redo cmake ninja ninja cmake make cmake cmake" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9593/" ]
66,810
<p>Has anybody experience in building a custom style in Qt? What I have in my mind is a complete new style that affects all kind of widgets. I have seen some examples in the web for a custom combo box. But I have no idea how much time and code it takes to build a "complete" new custom style ... maybe someone can give me a hint.</p> <p>We think of using Qt 4.3 (or even newer) ...</p>
[ { "answer_id": 499919, "author": "David Boddie", "author_id": 61047, "author_profile": "https://Stackoverflow.com/users/61047", "pm_score": 0, "selected": false, "text": " http://doc.qt.digia.com/4.4/stylesheet.html\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2012356/" ]
66,819
<p>Are there any good solutions to represent a parameterized enum in <code>C# 3.0</code>? I am looking for something like <a href="http://www.ocaml.org" rel="nofollow noreferrer">OCaml</a> or <a href="http://www.haxe.org" rel="nofollow noreferrer">Haxe</a> has. I can only think of class hierarchy with a simple enum field for easy switching for now, maybe there are better ideas?</p> <p>See Ocaml example below in one of the replies, a Haxe code follows:</p> <pre><code>enum Tree { Node(left: Tree, right: Tree); Leaf(val: Int); } </code></pre>
[ { "answer_id": 67321, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 4, "selected": true, "text": "enum Color{ Red, Green, Yellow, Blue };\nColor c = Color.Red;\n c Red Green Yellow Blue enum Cell<T>{ \n empty; \n cons( item : T, next : Cell<T> )\n}\n\nCell<int> c = <I don't know>;\n c empty cons(item, next) item T next Cell<T> new { Name='Joe'} item next switch( c ) {\n case empty : 0;\n case cons(item,next): 1 + cell_length(next);\n}\n #define Red 1 Color public interface ICell<T> {\n T Item{ get; set; }\n ICell<T>{ get; set; }\n}\n\nclass Cons<T> : ICell<T> {\n public T Item{ get; set; } /* C#3 auto-backed property */\n public Cell<T> Next{ get; set; }\n}\n\nclass EmptyCell<T> : ICell<T>{\n public T Item{ get{ return default(T); set{ /* do nothing */ }; }\n public ICell<T> Next{ get{ return null }; set{ /* do nothing */; }\n}\n List<ICell<T>> EmptyCell Next EmptyCell empty Cons EmptyCell Cons" }, { "answer_id": 68959, "author": "user10834", "author_id": 10834, "author_profile": "https://Stackoverflow.com/users/10834", "pm_score": 1, "selected": false, "text": "System.Drawing.Color" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9777/" ]
66,837
<p>Are <strong>CDATA</strong> tags ever necessary in script tags and if so when?</p> <p>In other words, when and where is this:</p> <pre><code>&lt;script type="text/javascript"&gt; //&lt;![CDATA[ ...code... //]]&gt; &lt;/script&gt; </code></pre> <p>preferable to this:</p> <pre><code>&lt;script type="text/javascript"&gt; ...code... &lt;/script&gt; </code></pre>
[ { "answer_id": 66865, "author": "Michael Ridley", "author_id": 4838, "author_profile": "https://Stackoverflow.com/users/4838", "pm_score": 10, "selected": true, "text": "i<10 a && b i&lt;10 a &amp;&amp; b" }, { "answer_id": 66900, "author": "Shadow2531", "author_id": 1697, "author_profile": "https://Stackoverflow.com/users/1697", "pm_score": 8, "selected": false, "text": "<script>\n<![CDATA[\n ...code...\n]]>\n</script>\n <script>\n ...code...\n</script>\n <script>\n//<![CDATA[\n ...code...\n//]]>\n</script>\n" }, { "answer_id": 1450633, "author": "user123444555621", "author_id": 27862, "author_profile": "https://Stackoverflow.com/users/27862", "pm_score": 7, "selected": false, "text": "<script> </script> </ <script>\nvar x = '</script>';\nalert(x)\n</script>\n CDATA var x = '<' + '/script>'; // or\nvar x = '<\\/script>';\n text/html script < & <script>\nif (a<b && c<d) {\n alert('Hooray');\n}\n</script>\n CDATA < & <![CDATA[ ]]> < & CDATA" }, { "answer_id": 2358410, "author": "Franz", "author_id": 192741, "author_profile": "https://Stackoverflow.com/users/192741", "pm_score": 5, "selected": false, "text": "< > ]]>" }, { "answer_id": 2358449, "author": "ondra", "author_id": 149901, "author_profile": "https://Stackoverflow.com/users/149901", "pm_score": 5, "selected": false, "text": "if (a &gt; b) alert('hello world');\n" }, { "answer_id": 12149260, "author": "Paul Sweatte", "author_id": 1113772, "author_profile": "https://Stackoverflow.com/users/1113772", "pm_score": 3, "selected": false, "text": "<" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/208/" ]
66,870
<p>I want a user-privileged (not root) process to launch new processes as user <code>nobody</code>. I've tried a straight call to <code>setuid</code> that fails with -1 <code>EPERM</code> on <code>Ubuntu 8.04</code>:</p> <pre><code>#include &lt;sys/types.h&gt; #include &lt;unistd.h&gt; int main() { setuid(65534); while (1); return 0; } </code></pre> <p>How should I do this instead?</p>
[ { "answer_id": 66937, "author": "squadette", "author_id": 7754, "author_profile": "https://Stackoverflow.com/users/7754", "pm_score": 5, "selected": true, "text": "/etc/sudoers sudo -u nobody chown nobody chmod +s exec(\"/home/you/bin/your-application\") your-application" }, { "answer_id": 67046, "author": "Allan Wind", "author_id": 9706, "author_profile": "https://Stackoverflow.com/users/9706", "pm_score": 0, "selected": false, "text": "calife sudo" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9947/" ]
66,875
<p>We have a case where clients seem to be eternally caching versions of applets. We're making use of the <code>&lt;param name="cache_version"&gt;</code> tag correctly within our <code>&lt;object&gt;</code> tag, or so we think. We went from a version string of <code>7.1.0.40</code> to <code>7.1.0.42</code> and this triggered a download for only about half of our clients.</p> <p>It doesn't seem to matter which version of the JRE the client is running. We've seen people have this problem on 1.4, 1.5 and 1.6.</p> <p>Does anybody have experience with explicit cache versions? Does it work more reliably (ignoring speed) to instead rely on the <code>cache_archive</code>'s "Last-Modified" and/or "Content-Length" values (as per <a href="http://java.sun.com/j2se/1.4.2/docs/guide/plugin/developer_guide/applet_caching.html" rel="noreferrer">Sun's Site</a>)?</p> <p>FYI, object block looks like this:</p> <pre><code>&lt;object&gt; &lt;param name="ARCHIVE" value="foo.jar"&gt; &lt;param name="CODE" value="com.foo.class"&gt; &lt;param name="CODEBASE" value="."&gt; &lt;param name="cache_archive" value="foo.jar"&gt; &lt;param name="cache_version" value="7.1.0.40"&gt; &lt;param name="NAME" value="FooApplet"&gt; &lt;param name="type" value="application/x-java-applet;jpi-version=1.4.2_13"&gt; &lt;param name="scriptable" value="true"&gt; &lt;param name="progressbar" value="true"/&gt; &lt;param name="boxmessage" value="Loading Web Worksheet Applet..."/&gt; &lt;/object&gt; </code></pre>
[ { "answer_id": 15113420, "author": "Ilya", "author_id": 1143825, "author_profile": "https://Stackoverflow.com/users/1143825", "pm_score": 2, "selected": false, "text": "Java Control Panel Start -> Control Panel -> Java -> Temporary Internet Files[View]\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
66,880
<p>After reading <a href="https://stackoverflow.com/questions/63668/confessions-of-your-worst-wtf-moment-what-not-to-do#63730">this answer</a>, I wonder if there's a way to get a "testing" credit card number. One that you can experiment with but that doesn't actually charge anything.</p>
[ { "answer_id": 66988, "author": "Mike", "author_id": 1115144, "author_profile": "https://Stackoverflow.com/users/1115144", "pm_score": 6, "selected": true, "text": "MasterCard: 5431111111111111\nAmex: 341111111111111\nDiscover: 6011601160116611\nAmerican Express (15 digits) 378282246310005\nAmerican Express (15 digits) 371449635398431\nAmerican Express Corporate (15 digits) 378734493671000\nDiners Club (14 digits) 30569309025904\nDiners Club (14 digits) 38520000023237\nDiscover (16 digits) 6011111111111117\nDiscover (16 digits) 6011000990139424\nJCB (16 digits) 3530111333300000\nJCB (16 digits) 3566002020360505\nMasterCard (16 digits) 5555555555554444\nMasterCard (16 digits) 5105105105105100\nVisa (16 digits) 4111111111111111\nVisa (16 digits) 4012888888881881\nVisa (13 digits) 4222222222222\n Visa: 13 or 16 numbers starting with 4\nMasterCard: 16 numbers starting with 5\nDiscover: 16 numbers starting with 6011\nAMEX: 15 numbers starting with 34 or 37\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5314/" ]
66,882
<p>Which is the simplest way to check if two integers have same sign? Is there any short bitwise trick to do this?</p>
[ { "answer_id": 66908, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 1, "selected": false, "text": "int mask = 1 << 31;\n(a & mask) ^ (b & mask) < 0;\n" }, { "answer_id": 66928, "author": "Patrick", "author_id": 429, "author_profile": "https://Stackoverflow.com/users/429", "pm_score": 3, "selected": false, "text": "bool same = ((x ^ y) >> 31) != 1;\n bool same = !((x ^ y) >> 31);\n" }, { "answer_id": 66968, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "(a ^ b) >= 0\n" }, { "answer_id": 67020, "author": "Torlack", "author_id": 5243, "author_profile": "https://Stackoverflow.com/users/5243", "pm_score": 7, "selected": true, "text": "bool SameSign(int x, int y)\n{\n return (x >= 0) ^ (y < 0);\n}\n template <typename valueType>\nbool SameSign(typename valueType x, typename valueType y)\n{\n return (x >= 0) ^ (y < 0);\n}\n" }, { "answer_id": 67041, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 1, "selected": false, "text": "#define SIGNBIT (~((unsigned int)-1 >> 1))\nif ((x & SIGNBIT) == (y & SIGNBIT))\n // signs are the same\n" }, { "answer_id": 67061, "author": "ugasoft", "author_id": 10120, "author_profile": "https://Stackoverflow.com/users/10120", "pm_score": 1, "selected": false, "text": "if(((x^y) & 0x80000000) == 0) if(x*y>0)" }, { "answer_id": 67133, "author": "OwenP", "author_id": 2547, "author_profile": "https://Stackoverflow.com/users/2547", "pm_score": 3, "selected": false, "text": "bool compare(T left, T right)\n{\n return (left < 0) == (right < 0);\n}\n" }, { "answer_id": 67498, "author": "Rik", "author_id": 5409, "author_profile": "https://Stackoverflow.com/users/5409", "pm_score": 8, "selected": false, "text": "return ((x<0) == (y<0)); \n" }, { "answer_id": 67710, "author": "user10315", "author_id": 10315, "author_profile": "https://Stackoverflow.com/users/10315", "pm_score": 2, "selected": false, "text": "inline bool same_sign(int x, int y) {\n return (x^y) >= 0;\n}\n inline bool same_sign(int x, int y) {\n return (x<0) == (y<0);\n}\n" }, { "answer_id": 6215769, "author": "CAFxX", "author_id": 414813, "author_profile": "https://Stackoverflow.com/users/414813", "pm_score": 1, "selected": false, "text": "int sameSign(int a, int b) {\n return ~(a^b) & (1<<(sizeof(int)*8-1));\n}\n template <typename T> T sameSign(T a, T b) {\n return ~(a^b) & (1<<(sizeof(T)*8-1));\n}\n" }, { "answer_id": 34031263, "author": "ashiquzzaman33", "author_id": 2317535, "author_profile": "https://Stackoverflow.com/users/2317535", "pm_score": 0, "selected": false, "text": "std::signbit(firstNumber) == std::signbit(secondNumber);\n double float char" }, { "answer_id": 67649969, "author": "Krazzy4Code", "author_id": 16000816, "author_profile": "https://Stackoverflow.com/users/16000816", "pm_score": 0, "selected": false, "text": "#include<stdio.h>\n\nint checksign(int a, int b)\n{\n return (a ^ b); \n}\n\nvoid main()\n{\n int a=-1, b = 0;\n\n if(checksign(a,b)<0)\n {\n printf(\"Integers have the opposite sign\");\n }\n else\n {\n printf(\"Integers have the same sign\");\n }\n}\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66882", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
66,885
<p>What is current state of the art for enabling OpenID login in Ruby on Rails applications? This is a community wiki with up-to-date answers to this question.</p> <h2>Authlogic</h2> <p>The most advanced authentication solution seems to be <a href="http://github.com/binarylogic/authlogic" rel="noreferrer">Authlogic</a>. It supports OpenID with <a href="http://github.com/binarylogic/authlogic_openid" rel="noreferrer">Authlogic OpenID plugin</a>. It supports Rails 4 and 3. Rails 2 is supported in the rails2 branch.</p> <p>You may want to watch <a href="http://railscasts.com/episodes/170-openid-with-authlogic" rel="noreferrer">&quot;OpenID with Authlogic&quot; railscast</a> (and the <a href="http://railscasts.com/episodes/160-authlogic" rel="noreferrer">&quot;Authlogic&quot; railscast</a>).</p> <p>There is a sample application called <a href="http://github.com/shripadk/authlogic_openid_selector_example" rel="noreferrer">Authlogic OpenID Selector Example</a>.</p> <h2>Devise</h2> <p>Devise is flexible authentication framework for Rails. It supports OpenID with <a href="https://github.com/nbudin/devise_openid_authenticatable" rel="noreferrer"><code>devise_openid_authenticatable</code></a>.</p> <h2>restful_authentication</h2> <p>Another authentication library of choice is <a href="http://github.com/technoweenie/restful-authentication" rel="noreferrer"><code>restful_authentication</code></a> Rails plugin. Seems like you also need to install <a href="http://github.com/rails/open_id_authentication" rel="noreferrer"><code>open_id_authentication</code></a> plugin.</p> <p>You may want to watch (old, circa 2007) <a href="http://railscasts.com/episodes/68-openid-authentication" rel="noreferrer">&quot;OpenID Authentication&quot; railscast</a>.</p> <h2>Ruby OpenID</h2> <p>Raw support for OpenID protocol is handled by <a href="http://github.com/openid/ruby-openid" rel="noreferrer">Ruby OpenID</a> library.</p>
[ { "answer_id": 120254, "author": "tardate", "author_id": 6329, "author_profile": "https://Stackoverflow.com/users/6329", "pm_score": 2, "selected": false, "text": "gem install ruby-openid\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66885", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7754/" ]
66,893
<p>I was looking for a tree or graph data structure in C#, but I guess there isn't one provided. <a href="http://msdn.microsoft.com/en-us/library/ms379574.aspx" rel="noreferrer">An Extensive Examination of Data Structures Using C# 2.0</a> a bit about why. Is there a convenient library which is commonly used to provide this functionality? Perhaps through a <a href="https://en.wikipedia.org/wiki/Strategy_pattern" rel="noreferrer">strategy pattern</a> to solve the issues presented in the article.</p> <p>I feel a bit silly implementing my own tree, just as I would implementing my own ArrayList.</p> <p>I just want a generic tree which can be unbalanced. Think of a directory tree. <a href="https://itu.dk/research/c5/" rel="noreferrer">C5</a> looks nifty, but their tree structures seem to be implemented as balanced red-black trees better suited to search than representing a hierarchy of nodes.</p>
[ { "answer_id": 2012855, "author": "Aaron Gage", "author_id": 226861, "author_profile": "https://Stackoverflow.com/users/226861", "pm_score": 7, "selected": false, "text": "delegate void TreeVisitor<T>(T nodeData);\n\nclass NTree<T>\n{\n private T data;\n private LinkedList<NTree<T>> children;\n\n public NTree(T data)\n {\n this.data = data;\n children = new LinkedList<NTree<T>>();\n }\n\n public void AddChild(T data)\n {\n children.AddFirst(new NTree<T>(data));\n }\n\n public NTree<T> GetChild(int i)\n {\n foreach (NTree<T> n in children)\n if (--i == 0)\n return n;\n return null;\n }\n\n public void Traverse(NTree<T> node, TreeVisitor<T> visitor)\n {\n visitor(node.data);\n foreach (NTree<T> kid in node.children)\n Traverse(kid, visitor);\n }\n}\n" }, { "answer_id": 10442244, "author": "Ronnie Overby", "author_id": 64334, "author_profile": "https://Stackoverflow.com/users/64334", "pm_score": 6, "selected": false, "text": "List<T> namespace Overby.Collections\n{\n public class TreeNode<T>\n {\n private readonly T _value;\n private readonly List<TreeNode<T>> _children = new List<TreeNode<T>>();\n\n public TreeNode(T value)\n {\n _value = value;\n }\n\n public TreeNode<T> this[int i]\n {\n get { return _children[i]; }\n }\n\n public TreeNode<T> Parent { get; private set; }\n\n public T Value { get { return _value; } }\n\n public ReadOnlyCollection<TreeNode<T>> Children\n {\n get { return _children.AsReadOnly(); }\n }\n\n public TreeNode<T> AddChild(T value)\n {\n var node = new TreeNode<T>(value) {Parent = this};\n _children.Add(node);\n return node;\n }\n\n public TreeNode<T>[] AddChildren(params T[] values)\n {\n return values.Select(AddChild).ToArray();\n }\n\n public bool RemoveChild(TreeNode<T> node)\n {\n return _children.Remove(node);\n }\n\n public void Traverse(Action<T> action)\n {\n action(Value);\n foreach (var child in _children)\n child.Traverse(action);\n }\n\n public IEnumerable<T> Flatten()\n {\n return new[] {Value}.Concat(_children.SelectMany(x => x.Flatten()));\n }\n }\n}\n" }, { "answer_id": 10593721, "author": "Jake", "author_id": 682869, "author_profile": "https://Stackoverflow.com/users/682869", "pm_score": -1, "selected": false, "text": "class Node {\n Node* parent;\n int item; // depending on your needs\n\n Node* firstChild; //pointer to left most child of node\n Node* nextSibling; //pointer to the sibling to the right\n}\n" }, { "answer_id": 13430535, "author": "Erik Nagel", "author_id": 1831850, "author_profile": "https://Stackoverflow.com/users/1831850", "pm_score": 3, "selected": false, "text": "public class GenericTree<T> where T : GenericTree<T> // recursive constraint\n{\n // no specific data declaration\n\n protected List<T> children;\n\n public GenericTree()\n {\n this.children = new List<T>();\n }\n\n public virtual void AddChild(T newChild)\n {\n this.children.Add(newChild);\n }\n\n public void Traverse(Action<int, T> visitor)\n {\n this.traverse(0, visitor);\n }\n\n protected virtual void traverse(int depth, Action<int, T> visitor)\n {\n visitor(depth, (T)this);\n foreach (T child in this.children)\n child.traverse(depth + 1, visitor);\n }\n}\n\npublic class GenericTreeNext : GenericTree<GenericTreeNext> // concrete derivation\n{\n public string Name {get; set;} // user-data example\n\n public GenericTreeNext(string name)\n {\n this.Name = name;\n }\n}\n\nstatic void Main(string[] args)\n{\n GenericTreeNext tree = new GenericTreeNext(\"Main-Harry\");\n tree.AddChild(new GenericTreeNext(\"Main-Sub-Willy\"));\n GenericTreeNext inter = new GenericTreeNext(\"Main-Inter-Willy\");\n inter.AddChild(new GenericTreeNext(\"Inter-Sub-Tom\"));\n inter.AddChild(new GenericTreeNext(\"Inter-Sub-Magda\"));\n tree.AddChild(inter);\n tree.AddChild(new GenericTreeNext(\"Main-Sub-Chantal\"));\n tree.Traverse(NodeWorker);\n}\n\nstatic void NodeWorker(int depth, GenericTreeNext node)\n{ // a little one-line string-concatenation (n-times)\n Console.WriteLine(\"{0}{1}: {2}\", String.Join(\" \", new string[depth + 1]), depth, node.Name);\n}\n" }, { "answer_id": 15101910, "author": "Berezh", "author_id": 721704, "author_profile": "https://Stackoverflow.com/users/721704", "pm_score": 2, "selected": false, "text": "public class TreeNode<TValue>\n{\n #region Properties\n public TValue Value { get; set; }\n public List<TreeNode<TValue>> Children { get; private set; }\n public bool HasChild { get { return Children.Any(); } }\n #endregion\n #region Constructor\n public TreeNode()\n {\n this.Children = new List<TreeNode<TValue>>();\n }\n public TreeNode(TValue value)\n : this()\n {\n this.Value = value;\n }\n #endregion\n #region Methods\n public void AddChild(TreeNode<TValue> treeNode)\n {\n Children.Add(treeNode);\n }\n public void AddChild(TValue value)\n {\n var treeNode = new TreeNode<TValue>(value);\n AddChild(treeNode);\n }\n #endregion\n}\n" }, { "answer_id": 18774221, "author": "Grzegorz Dev", "author_id": 1367449, "author_profile": "https://Stackoverflow.com/users/1367449", "pm_score": 6, "selected": false, "text": "public class TreeNode<T> : IEnumerable<TreeNode<T>>\n{\n\n public T Data { get; set; }\n public TreeNode<T> Parent { get; set; }\n public ICollection<TreeNode<T>> Children { get; set; }\n\n public TreeNode(T data)\n {\n this.Data = data;\n this.Children = new LinkedList<TreeNode<T>>();\n }\n\n public TreeNode<T> AddChild(T child)\n {\n TreeNode<T> childNode = new TreeNode<T>(child) { Parent = this };\n this.Children.Add(childNode);\n return childNode;\n }\n\n ... // for iterator details see below link\n}\n TreeNode<string> root = new TreeNode<string>(\"root\");\n{\n TreeNode<string> node0 = root.AddChild(\"node0\");\n TreeNode<string> node1 = root.AddChild(\"node1\");\n TreeNode<string> node2 = root.AddChild(\"node2\");\n {\n TreeNode<string> node20 = node2.AddChild(null);\n TreeNode<string> node21 = node2.AddChild(\"node21\");\n {\n TreeNode<string> node210 = node21.AddChild(\"node210\");\n TreeNode<string> node211 = node21.AddChild(\"node211\");\n }\n }\n TreeNode<string> node3 = root.AddChild(\"node3\");\n {\n TreeNode<string> node30 = node3.AddChild(\"node30\");\n }\n}\n" }, { "answer_id": 23150015, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "class BST\n{\n public class Node\n {\n public Node Left { get; set; }\n public object Data { get; set; }\n public Node Right { get; set; }\n\n public Node()\n {\n Data = null;\n }\n\n public Node(int Data)\n {\n this.Data = (object)Data;\n }\n\n public void Insert(int Data)\n {\n if (this.Data == null)\n {\n this.Data = (object)Data;\n return;\n }\n if (Data > (int)this.Data)\n {\n if (this.Right == null)\n {\n this.Right = new Node(Data);\n }\n else\n {\n this.Right.Insert(Data);\n }\n }\n if (Data <= (int)this.Data)\n {\n if (this.Left == null)\n {\n this.Left = new Node(Data);\n }\n else\n {\n this.Left.Insert(Data);\n }\n }\n }\n\n public void TraverseInOrder()\n {\n if(this.Left != null)\n this.Left.TraverseInOrder();\n Console.Write(\"{0} \", this.Data);\n if (this.Right != null)\n this.Right.TraverseInOrder();\n }\n }\n\n public Node Root { get; set; }\n public BST()\n {\n Root = new Node();\n }\n}\n" }, { "answer_id": 35033913, "author": "Meirion Hughes", "author_id": 1657476, "author_profile": "https://Stackoverflow.com/users/1657476", "pm_score": 2, "selected": false, "text": "SortedSet" }, { "answer_id": 36546817, "author": "Ian Ringrose", "author_id": 57159, "author_profile": "https://Stackoverflow.com/users/57159", "pm_score": 1, "selected": false, "text": "person parents grandchildren person person person" }, { "answer_id": 38555544, "author": "Ashkan S", "author_id": 6519111, "author_profile": "https://Stackoverflow.com/users/6519111", "pm_score": 2, "selected": false, "text": "public class TreeNode<T> : IEnumerable<TreeNode<T>>\n{\n public T Data { get; set; }\n public TreeNode<T> Parent { get; set; }\n public ICollection<TreeNode<T>> Children { get; set; }\n\n public TreeNode(T data)\n {\n this.Data = data;\n this.Children = new LinkedList<TreeNode<T>>();\n }\n\n public TreeNode<T> AddChild(T child)\n {\n TreeNode<T> childNode = new TreeNode<T>(child) { Parent = this };\n this.Children.Add(childNode);\n return childNode;\n }\n\n public IEnumerator<TreeNode<T>> GetEnumerator()\n {\n throw new NotImplementedException();\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return (IEnumerator)GetEnumerator();\n }\n}\n\npublic class TreeNodeEnum<T> : IEnumerator<TreeNode<T>>\n{\n\n int position = -1;\n public List<TreeNode<T>> Nodes { get; set; }\n\n public TreeNode<T> Current\n {\n get\n {\n try\n {\n return Nodes[position];\n }\n catch (IndexOutOfRangeException)\n {\n throw new InvalidOperationException();\n }\n }\n }\n\n object IEnumerator.Current\n {\n get\n {\n return Current;\n }\n }\n\n public TreeNodeEnum(List<TreeNode<T>> nodes)\n {\n Nodes = nodes;\n }\n\n public void Dispose()\n {\n\n }\n\n public bool MoveNext()\n {\n position++;\n return (position < Nodes.Count);\n }\n\n public void Reset()\n {\n position = -1;\n }\n}\n" }, { "answer_id": 43383944, "author": "Dmitry", "author_id": 7859994, "author_profile": "https://Stackoverflow.com/users/7859994", "pm_score": 2, "selected": false, "text": " public class NTree<T>\n {\n public T data;\n public LinkedList<NTree<T>> children;\n\n public NTree(T data)\n {\n this.data = data;\n children = new LinkedList<NTree<T>>();\n }\n\n public void AddChild(T data)\n {\n var node = new NTree<T>(data) { Parent = this };\n children.AddFirst(node);\n }\n\n public NTree<T> Parent { get; private set; }\n\n public NTree<T> GetChild(int i)\n {\n foreach (NTree<T> n in children)\n if (--i == 0)\n return n;\n return null;\n }\n\n public void Traverse(NTree<T> node, TreeVisitor<T> visitor, string t, ref NTree<T> r)\n {\n visitor(node.data, node, t, ref r);\n foreach (NTree<T> kid in node.children)\n Traverse(kid, visitor, t, ref r);\n }\n }\n\n public static void DelegateMethod(KeyValuePair<string, string> data, NTree<KeyValuePair<string, string>> node, string t, ref NTree<KeyValuePair<string, string>> r)\n {\n string a = string.Empty;\n if (node.data.Key == t)\n {\n r = node;\n return;\n }\n }\n NTree<KeyValuePair<string, string>> ret = null;\n tree.Traverse(tree, DelegateMethod, node[\"categoryId\"].InnerText, ref ret);\n" }, { "answer_id": 52014730, "author": "moien", "author_id": 5592276, "author_profile": "https://Stackoverflow.com/users/5592276", "pm_score": 3, "selected": false, "text": "class Program\n{\n static void Main(string[] args)\n {\n var tree = new Tree<string>()\n .Begin(\"Fastfood\")\n .Begin(\"Pizza\")\n .Add(\"Margherita\")\n .Add(\"Marinara\")\n .End()\n .Begin(\"Burger\")\n .Add(\"Cheese burger\")\n .Add(\"Chili burger\")\n .Add(\"Rice burger\")\n .End()\n .End();\n\n tree.Nodes.ForEach(p => PrintNode(p, 0));\n Console.ReadKey();\n }\n\n static void PrintNode<T>(TreeNode<T> node, int level)\n {\n Console.WriteLine(\"{0}{1}\", new string(' ', level * 3), node.Value);\n level++;\n node.Children.ForEach(p => PrintNode(p, level));\n }\n}\n\npublic class Tree<T>\n{\n private Stack<TreeNode<T>> m_Stack = new Stack<TreeNode<T>>();\n\n public List<TreeNode<T>> Nodes { get; } = new List<TreeNode<T>>();\n\n public Tree<T> Begin(T val)\n {\n if (m_Stack.Count == 0)\n {\n var node = new TreeNode<T>(val, null);\n Nodes.Add(node);\n m_Stack.Push(node);\n }\n else\n {\n var node = m_Stack.Peek().Add(val);\n m_Stack.Push(node);\n }\n\n return this;\n }\n\n public Tree<T> Add(T val)\n {\n m_Stack.Peek().Add(val);\n return this;\n }\n\n public Tree<T> End()\n {\n m_Stack.Pop();\n return this;\n }\n}\n\npublic class TreeNode<T>\n{\n public T Value { get; }\n public TreeNode<T> Parent { get; }\n public List<TreeNode<T>> Children { get; }\n\n public TreeNode(T val, TreeNode<T> parent)\n {\n Value = val;\n Parent = parent;\n Children = new List<TreeNode<T>>();\n }\n\n public TreeNode<T> Add(T val)\n {\n var node = new TreeNode<T>(val, this);\n Children.Add(node);\n return node;\n }\n}\n Fastfood\n Pizza\n Margherita\n Marinara\n Burger\n Cheese burger\n Chili burger\n Rice burger\n" }, { "answer_id": 64960280, "author": "Bar Nuri", "author_id": 2908786, "author_profile": "https://Stackoverflow.com/users/2908786", "pm_score": -1, "selected": false, "text": "using System;\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\n\npublic class Tree<T>\n{\n public T Data { get; set; }\n public LinkedList<Tree<T>> Children { get; set; } = new LinkedList<Tree<T>>();\n public Task Traverse(Func<T, Task> actionOnNode, int maxDegreeOfParallelism = 1) => Traverse(actionOnNode, new SemaphoreSlim(maxDegreeOfParallelism, maxDegreeOfParallelism));\n private async Task Traverse(Func<T, Task> actionOnNode, SemaphoreSlim semaphore)\n {\n await actionOnNode(Data);\n SafeRelease(semaphore);\n IEnumerable<Task> tasks = Children.Select(async input =>\n {\n await semaphore.WaitAsync().ConfigureAwait(false);\n try\n {\n await input.Traverse(actionOnNode, semaphore).ConfigureAwait(false);\n }\n finally\n {\n SafeRelease(semaphore);\n }\n });\n await Task.WhenAll(tasks);\n }\n private void SafeRelease(SemaphoreSlim semaphore)\n {\n try\n {\n semaphore.Release();\n }\n catch (Exception ex)\n {\n if (ex.Message.ToLower() != \"Adding the specified count to the semaphore would cause it to exceed its maximum count.\".ToLower())\n {\n throw;\n }\n }\n }\n\n public async Task<IEnumerable<T>> ToList()\n {\n ConcurrentBag<T> lst = new ConcurrentBag<T>();\n await Traverse(async (data) => lst.Add(data));\n return lst;\n }\n public async Task<int> Count() => (await ToList()).Count();\n}\n\n\n\n using System.Threading.Tasks;\nusing Xunit;\n\npublic class Tree_Tests\n{\n [Fact]\n public async Task Tree_ToList_Count()\n {\n Tree<int> head = new Tree<int>();\n\n Assert.NotEmpty(await head.ToList());\n Assert.True(await head.Count() == 1);\n\n // child\n var child = new Tree<int>();\n head.Children.AddFirst(child);\n Assert.True(await head.Count() == 2);\n Assert.NotEmpty(await head.ToList());\n\n // grandson\n child.Children.AddFirst(new Tree<int>());\n child.Children.AddFirst(new Tree<int>());\n Assert.True(await head.Count() == 4);\n Assert.NotEmpty(await head.ToList());\n }\n\n [Fact]\n public async Task Tree_Traverse()\n {\n Tree<int> head = new Tree<int>() { Data = 1 };\n\n // child\n var child = new Tree<int>() { Data = 2 };\n head.Children.AddFirst(child);\n\n // grandson\n child.Children.AddFirst(new Tree<int>() { Data = 3 });\n child.Children.AddLast(new Tree<int>() { Data = 4 });\n\n int counter = 0;\n await head.Traverse(async (data) => counter += data);\n Assert.True(counter == 10);\n\n counter = 0;\n await child.Traverse(async (data) => counter += data);\n Assert.True(counter == 9);\n\n counter = 0;\n await child.Children.First!.Value.Traverse(async (data) => counter += data);\n Assert.True(counter == 3);\n\n counter = 0;\n await child.Children.Last!.Value.Traverse(async (data) => counter += data);\n Assert.True(counter == 4);\n }\n}\n\n" }, { "answer_id": 72226859, "author": "ADM-IT", "author_id": 1143349, "author_profile": "https://Stackoverflow.com/users/1143349", "pm_score": -1, "selected": false, "text": "IDictionary<TChild, TParent>" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/361/" ]
66,912
<p>In a JSP page, I created a <code>&lt;h:form enctype="multipart/form-data"&gt;</code> with some elements: <code>&lt;t:inputText&gt;</code>, <code>&lt;t:inputDate&gt;</code>, etc. Also, I added some <code>&lt;t:message for="someElement"&gt;</code> And I wanted to allow the user upload several files (one at a time) within the form (using <code>&lt;t:inputFileUpload&gt;</code> ) At this point my code works fine.</p> <hr> <p>The headache comes when I try to put the form inside a <code>&lt;t:panelTabbedPane serverSideTabSwitch="false"&gt;</code> (and thus of course, inside a <code>&lt;t:panelTab&gt;</code> ) </p> <p>I copied the structure shown in the source code for TabbedPane example from <a href="http://www.irian.at/myfacesexamples/tabbedPane.jsf" rel="nofollow noreferrer">Tomahawk's examples</a>, by using the <code>&lt;f:subview&gt;</code> tag and putting the panelTab tag inside a new jsp page (using <code>&lt;jsp:include page="somePage.jsp"&gt;</code> directive)</p> <p>First at all, the <code>&lt;t:inputFileUpload&gt;</code> fails to load the file at the value assigned in the Managed Bean UploadedFile attribute <code>#{myBean.upFile}</code></p> <p>Then, <a href="http://markmail.org/message/b4nht4f6xb74noxp" rel="nofollow noreferrer" title="That has no answer when I readed it">googling for a clue</a>, I knew that <code>&lt;t:panelTabbedPane&gt;</code> generates a form called "autoform", so I was getting nested forms. Ok, I fixed that creating the <code>&lt;h:form&gt;</code> out of the <code>&lt;t:panelTabbedPane&gt;</code> and eureka! file input worked again! (the autoform doesn't generate) </p> <p>But, oh surprise! oh terrible Murphy law! All my <code>&lt;h:message&gt;</code> begins to fail. The Eclipse console's output show me that all <code>&lt;t:message&gt;</code> are looking for nonexistents elements ID's (who have their ID's in part equals to they are looking for, but at the end of the ID's their names change)</p> <p>At this point, I put a <code>&lt;t:mesagges&gt;</code> tag (note the "s" at the end) to show me all validation errors at once at the beginning of the Panel, and it works fine. So, validation errors exists and they show properly at the beginning of the Panel.</p> <p>All validation error messages generated in this page are the JSF built-in validation messages. The backing bean at this moment doesn't have any validators defined.</p> <h3>¿How can I get the <code>&lt;t:message for="xyz"&gt;</code> working properly?</h3> <hr> <p>I'm using Tomahawk-1.1.6 with myFaces-impl-1.2.3 in a eclipse Ganymede project with Geronimo as Application Server (Geronimo gives me the myFaces jar implementation while I put the tomahawk jar in the WEB-INF/lib folder of application) </p> <hr> <h2>"SOLVED": This problem is an issue reported to myFaces forum.</h2> <p>Thanks to Kyle Renfro for the soon response and information. (Good job Kyle!) <a href="https://issues.apache.org/jira/browse/MYFACES-1807?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&amp;focusedCommentId=12567158#action_12567158" rel="nofollow noreferrer">See the issue</a></p> <hr> <p><strong>EDIT 1</strong></p> <p>1.- Thanks to Kyle Renfro for his soon response. The forceID attribute used inside the input element doesn't works at first time, but doing some very tricky tweaks I could make the <code>&lt;t:message for="xyz"&gt;</code> tags work.</p> <p>What I did was:<br> 1. Having my tag <code>&lt;inputText id="name" forceId="true" required="true"&gt;</code> The <code>&lt;t:message&gt;</code> doesn't work.<br> 2. Then, after looking the error messages on eclipse console, I renamed my "id" attribute to this: &lt;inputText id="<strong>namej_id_1</strong>" forceId="true" required="true"&gt;<br> 3. Then the <code>&lt;t:message&gt;</code> worked!! but after pressing the "Submit" button of the form the second time. ¡The second time! (I suspect that something is going on at the JSF lifecycle)<br> 4. This implies that the user have to press 2 times the submit button to get the error messages on the page.<br> 5. And using the "j_id_1" phrase at the end of IDs is very weird. </p> <hr> <p><strong>EDIT 2</strong></p> <p>Ok, here comes the code, hope it not be annoying.</p> <p>1.- <strong>mainPage.jsp</strong> (here is the <code>&lt;t:panelTabbedPane&gt;</code> and <code>&lt;f:subview&gt;</code> tags) </p> <pre><code>&lt;%@ taglib prefix="f" uri="http://java.sun.com/jsf/core"%&gt; &lt;%@ taglib prefix="h" uri="http://java.sun.com/jsf/html"%&gt; &lt;%@ taglib prefix="t" uri="http://myfaces.apache.org/tomahawk"%&gt; &lt;html&gt; &lt;body&gt; &lt;f:view&gt; &lt;h:form enctype="multipart/form-data"&gt; &lt;t:panelTabbedPane serverSideTabSwitch="false" &gt; &lt;f:subview id="subview_tab_detail"&gt; &lt;jsp:include page="detail.jsp"/&gt; &lt;/f:subview&gt; &lt;/t:panelTabbedPane&gt; &lt;/h:form&gt; &lt;/f:view&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><br /> 2.- <strong>detail.jsp</strong> (here is the <code>&lt;t:panelTab&gt;</code> tag) </p> <pre><code>&lt;%@ taglib prefix="f" uri="http://java.sun.com/jsf/core"%&gt; &lt;%@ taglib prefix="h" uri="http://java.sun.com/jsf/html"%&gt; &lt;%@ taglib prefix="t" uri="http://myfaces.apache.org/tomahawk"%&gt; &lt;t:panelTab label="TAB_1"&gt; &lt;t:panelGrid columns="3"&gt; &lt;f:facet name="header"&gt; &lt;h:outputText value="CREATING A TICKET" /&gt; &lt;/f:facet&gt; &lt;t:outputLabel for="ticket_id" value="TICKET ID" /&gt; &lt;t:inputText id="ticket_id" value="#{myBean.ticketId}" required="true" /&gt; &lt;t:message for="ticket_id" /&gt; &lt;t:outputLabel for="description" value="DESCRIPTION" /&gt; &lt;t:inputText id="description" value="#{myBean.ticketDescription}" required="true" /&gt; &lt;t:message for="description" /&gt; &lt;t:outputLabel for="attachment" value="ATTACHMENTS" /&gt; &lt;t:panelGroup&gt; &lt;!-- This is for listing multiple file uploads --&gt; &lt;!-- The panelGrid binding make attachment list grow as the user inputs several files (one at a time) --&gt; &lt;t:panelGrid columns="3" binding="#{myBean.panelUpload}" /&gt; &lt;t:inputFileUpload id="attachment" value="#{myBean.upFile}" storage="file" /&gt; &lt;t:commandButton value="ADD FILE" action="#{myBean.upload}" /&gt; &lt;/t:panelGroup&gt; &lt;t:message for="attachment" /&gt; &lt;t:commandButton action="#{myBean.create}" value="CREATE TICKET" /&gt; &lt;/t:panelGrid&gt; &lt;/t:panelTab&gt; </code></pre> <hr> <p><strong>EDIT 3</strong></p> <p>On response to Kyle Renfro follow-up:</p> <blockquote> <p>Kyle says:</p> <blockquote> <p>"At the first view of the page, if you press the "CREATE TICKET" button with nothing in any of the inputTexts and no files uploaded, do the message tags work for the inputTexts? (ie. required = true) I'm just curious if the messages for the inputTexts are working but the message for the inputFileUpload is not." </p> </blockquote> </blockquote> <p>Here is the behavior found:<br> 1.- There is no validation error messages shown at all (the message tags don't work) Even when I try to test only one validation error message (for example, testing the message for the first input text) none of them shows up.<br> 2.- The eclipse console shows me these internal errors: </p> <pre><code>ERROR [HtmlMessageRendererBase] Could not render Message. Unable to find component 'ticket_id' (calling findComponent on component 'j_id_jsp_1383779881_1:subview_tab_detail:j_id_jsp_1716158401_0j_id_1:j_id_jsp_1716158401_5j_id_1'). If the provided id was correct, wrap the message and its component into an h:panelGroup or h:panelGrid. ERROR [HtmlMessageRendererBase] Could not render Message. Unable to find component 'description' (calling findComponent on component 'j_id_jsp_1383779881_1:subview_tab_detail:j_id_jsp_1716158401_0j_id_1:j_id_jsp_1716158401_8j_id_1'). If the provided id was correct, wrap the message and its component into an h:panelGroup or h:panelGrid. ERROR [HtmlMessageRendererBase] Could not render Message. Unable to find component 'attachment' (calling findComponent on component 'j_id_jsp_1383779881_1:subview_tab_detail:j_id_jsp_1716158401_0j_id_1:j_id_jsp_1716158401_14j_id_1'). If the provided id was correct, wrap the message and its component into an h:panelGroup or h:panelGrid. </code></pre> <p>Here is when I saw the <code>"j_id_1"</code> word at the generated IDs, for example, for the id "ticket_id": </p> <pre><code>j_id_jsp_1383779881_1:subview_tab_detail:j_id_jsp_1716158401_0j_id_1:j_id_jsp_1716158401_5j_id_1 </code></pre> <p>And, viewing the resulting HTML generated page, I saw that the IDs names are like this (whitout using "ForceId" atribute): </p> <pre><code>&lt;input id="j_id_jsp_1383779881_1:subview_tab_detail:j_id_jsp_1716158401_0j_id_1:ticket_idj_id_1" name="j_id_jsp_1383779881_1:subview_tab_detail:j_id_jsp_1716158401_0j_id_1:ticket_idj_id_1"&gt; </code></pre> <hr>
[ { "answer_id": 72243, "author": "Kyle Renfro", "author_id": 8187, "author_profile": "https://Stackoverflow.com/users/8187", "pm_score": 1, "selected": false, "text": "&lt;t:outputText id=\"xyz\" forceId=\"true\" value=\"#{mybean.stuff}\"/&gt;\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9818/" ]
66,919
<p>While <kbd>Ctrl</kbd><kbd>X</kbd> works fine in vim under windows, <kbd>Ctrl</kbd><kbd>A</kbd> selects all (duh).</p> <p>Is there a way to increment a number with a keystroke under windows?</p>
[ { "answer_id": 84055, "author": "TMealy", "author_id": 15954, "author_profile": "https://Stackoverflow.com/users/15954", "pm_score": 3, "selected": false, "text": "\" CTRL-A is Select all\nnoremap <C-A> gggH<C-O>G\ninoremap <C-A> <C-O>gg<C-O>gH<C-O>G\ncnoremap <C-A> <C-C>gggH<C-O>G\nonoremap <C-A> <C-C>gggH<C-O>G\nsnoremap <C-A> <C-C>gggH<C-O>G\nxnoremap <C-A> <C-C>ggVG\n \" CTRL-A is Select all\n\"noremap <C-A> gggH<C-O>G\n\"inoremap <C-A> <C-O>gg<C-O>gH<C-O>G\n\"cnoremap <C-A> <C-C>gggH<C-O>G\n\"onoremap <C-A> <C-C>gggH<C-O>G\n\"snoremap <C-A> <C-C>gggH<C-O>G\n\"xnoremap <C-A> <C-C>ggVG\n" }, { "answer_id": 3910354, "author": "Paul", "author_id": 472745, "author_profile": "https://Stackoverflow.com/users/472745", "pm_score": 2, "selected": false, "text": "noremap <C-I> <C-A>\n\n\" CTRL-A is Select all\nnoremap <C-A> gggH<C-O>G\ninoremap <C-A> <C-O>gg<C-O>gH<C-O>G\ncnoremap <C-A> <C-C>gggH<C-O>G\nonoremap <C-A> <C-C>gggH<C-O>G\nsnoremap <C-A> <C-C>gggH<C-O>G\nxnoremap <C-A> <C-C>ggVG\n" }, { "answer_id": 8620507, "author": "Taylor Price", "author_id": 3805, "author_profile": "https://Stackoverflow.com/users/3805", "pm_score": 3, "selected": false, "text": "set nocompatible\nsource $VIMRUNTIME/vimrc_example.vim\nsource $VIMRUNTIME/mswin.vim\nbehave mswin\n \" set nocompatible set compatible set compatible\nsource $VIMRUNTIME/vimrc_example.vim\n\"set nocompatible\n\"source $VIMRUNTIME/mswin.vim\n\"behave mswin\n" }, { "answer_id": 31992975, "author": "Serge Stroobandt", "author_id": 2192488, "author_profile": "https://Stackoverflow.com/users/2192488", "pm_score": 2, "selected": false, "text": "mswin.vim mswin.vim execute \"set <A-x>=\\ex\"\nnoremap <A-x> <C-A>\nsource $VIMRUNTIME/mswin.vim\nbehave mswin\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6984/" ]
66,921
<p>Short version: I want to trigger the Form_Load() event without making the form visible. This doesn't work because Show() ignores the current value of the Visible property:</p> <pre><code>tasksForm.Visible = false; tasksForm.Show(); </code></pre> <p>Long version: I have a WinForms application with two forms: main and tasks. The main form is always displayed. The user can either click a button to open the tasks form, or click some buttons that just run a task directly without opening the tasks form.</p> <p>When a user asks to run a task directly, I'd like to just call some public methods on the tasks form without showing it. Unfortunately, the task logic depends on stuff that happens in the Form_Load() event. The only way I can find to trigger Form_Load() is to call Show(). The best I've been able to do is to show the form in the minimized state:</p> <pre><code>tasksForm.WindowState = FormWindowState.Minimized; tasksForm.Show(); </code></pre> <p>I suppose the cleanest solution would be to pull the tasks logic out of the tasks form and into a controller class. Then I can use that class from the main form and from the tasks form, and only load the tasks form when I need it visible for the user. However, if it's an easy thing to load the form without displaying it, that would be a smaller change.</p>
[ { "answer_id": 66991, "author": "McKenzieG1", "author_id": 3776, "author_profile": "https://Stackoverflow.com/users/3776", "pm_score": 0, "selected": false, "text": "Load" }, { "answer_id": 67592, "author": "configurator", "author_id": 9536, "author_profile": "https://Stackoverflow.com/users/9536", "pm_score": 3, "selected": false, "text": "Form.Show(); Form.Visible = true;" }, { "answer_id": 4411493, "author": "Jeff Roe", "author_id": 253586, "author_profile": "https://Stackoverflow.com/users/253586", "pm_score": 4, "selected": false, "text": "MyForm f = new MyForm();\nIntPtr dummy = f.Handle; // forces the form Control to be created\n" }, { "answer_id": 51967639, "author": "Sodoshi", "author_id": 3820052, "author_profile": "https://Stackoverflow.com/users/3820052", "pm_score": 0, "selected": false, "text": "private volatile bool _formVisible;\nprotected override void SetVisibleCore(bool value)\n{\n base.SetVisibleCore(_formVisible);\n}\npublic void ShowForm()\n{\n _formVisible = true;\n if (InvokeRequired)\n {\n Invoke((Action) Show);\n }\n else\n {\n Show();\n }\n}\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4794/" ]
66,923
<p>So you have a String that is retrieved from an admin web UI (so it is definitely a String). How can you find out whether this string is an IP address or a hostname in Java?</p> <p>Update: I think I didn't make myself clear, I was more asking if there is anything in the Java SDK that I can use to distinguish between IPs and hostnames? Sorry for the confusion and thanks for everybody who took/will take the time to answer this.</p>
[ { "answer_id": 66944, "author": "Sam", "author_id": 9406, "author_profile": "https://Stackoverflow.com/users/9406", "pm_score": 5, "selected": true, "text": "\\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b\n" }, { "answer_id": 66947, "author": "zxcv", "author_id": 9628, "author_profile": "https://Stackoverflow.com/users/9628", "pm_score": 2, "selected": false, "text": "\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b\n 0 - 999" }, { "answer_id": 66989, "author": "jjnguy", "author_id": 2598, "author_profile": "https://Stackoverflow.com/users/2598", "pm_score": 1, "selected": false, "text": "URI validator = new URI(yourString);\n" }, { "answer_id": 67156, "author": "davenpcj", "author_id": 4777, "author_profile": "https://Stackoverflow.com/users/4777", "pm_score": 1, "selected": false, "text": "InetAddress.getByName(addr) getByName checkConnect(addr, -1) System.setSecurityManager() getByName" }, { "answer_id": 40135432, "author": "Sean F", "author_id": 6801443, "author_profile": "https://Stackoverflow.com/users/6801443", "pm_score": 1, "selected": false, "text": "static void check(HostName host) {\n try {\n host.validate();\n if(host.isAddress()) {\n System.out.println(\"address: \" + host.asAddress());\n } else {\n System.out.println(\"host name: \" + host);\n }\n } catch(HostNameException e) {\n System.out.println(e.getMessage());\n }\n}\n\npublic static void main(String[] args) {\n HostName host = new HostName(\"1.2.3.4\");\n check(host);\n host = new HostName(\"1.2.a.4\");\n check(host);\n host = new HostName(\"::1\");\n check(host);\n host = new HostName(\"[::1]\");\n check(host);\n host = new HostName(\"1.2.?.4\");\n check(host); \n}\n address: 1.2.3.4\nhost name: 1.2.a.4\naddress: ::1\naddress: ::1\n1.2.?.4 Host error: invalid character at index 4\n" }, { "answer_id": 57612280, "author": "Denis Kalinin", "author_id": 4919616, "author_profile": "https://Stackoverflow.com/users/4919616", "pm_score": 0, "selected": false, "text": "hostOrIp .getHostAddress() hostOrIp import java.net.InetAddress;\nimport java.net.UnknownHostException;\nimport java.util.Arrays;\n\npublic class IPvsHostTest {\n private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(IPvsHostTest.class);\n\n @org.junit.Test\n public void checkHostValidity() {\n Arrays.asList(\"10.10.10.10\", \"google.com\").forEach( hostname -> isHost(hostname));\n }\n private void isHost(String ip){\n try {\n InetAddress[] ips = InetAddress.getAllByName(ip);\n LOG.info(\"IP-addresses for {}\", ip);\n Arrays.asList(ips).forEach( ia -> {\n LOG.info(ia.getHostAddress());\n });\n } catch (UnknownHostException e) {\n LOG.error(\"Invalid hostname\", e);\n }\n }\n}\n\n IP-addresses for 10.10.10.10\n10.10.10.10\nIP-addresses for google.com\n64.233.164.100\n64.233.164.138\n64.233.164.139\n64.233.164.113\n64.233.164.102\n64.233.164.101\n" }, { "answer_id": 63747626, "author": "BillS", "author_id": 5415282, "author_profile": "https://Stackoverflow.com/users/5415282", "pm_score": 0, "selected": false, "text": " ...\n isDottedQuad(\"1.2.3.4\");\n isDottedQuad(\"google.com\");\n ...\n\nboolean isDottedQuad(String hostOrIP) throws UnknownHostException {\n InetAddress inet = InetAddress.getByName(hostOrIP);\n boolean b = inet.toString().startsWith(\"/\");\n System.out.println(\"Is \" + hostOrIP + \" dotted quad? \" + b + \" (\" + inet.toString() + \")\");\n return b;\n}\n Is 1.2.3.4 dotted quad? true (/1.2.3.4)\nIs google.com dotted quad? false (google.com/172.217.12.238)\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10059/" ]
66,934
<p>We are automating Excel using VB.Net, and trying to place multiple lines of text on an Excel worksheet that we can set to not print. Between these we would have printable reports. We can do this if we add textbox objects, and set the print object setting to false. (If you have another way, please direct me)</p> <p>The code to add a textbox is:</p> <pre><code>ActiveSheet.Shapes.AddTextbox(msoTextOrientationHorizontal, 145.5, 227.25, 304.5, 21#) </code></pre> <p>but the positioning is in points. We need a way to place it over a specific cell, and size it with the cell. How can we find out where to put it when we just know which cell to put it over?</p>
[ { "answer_id": 67740, "author": "dreamlax", "author_id": 10320, "author_profile": "https://Stackoverflow.com/users/10320", "pm_score": 4, "selected": true, "text": "With ActiveSheet\n .Shapes.AddTextbox msoTextOrientationHorizontal, .Cells(3,2).Left, .Cells(3,2).Top, .Cells(3,2).Width, .Cells(3,2).Height\nEnd With\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
66,964
<p>For example:</p> <blockquote> <p>This is main body of my content. I have a footnote link for this line [1]. Then, I have some more content. Some of it is interesting and it has some footnotes as well [2].</p> <p>[1] Here is my first footnote.</p> <p>[2] Another footnote.</p> </blockquote> <p>So, if I click on the "[1]" link it directs the web page to the first footnote reference and so on. How exactly do I accomplish this in HTML?</p>
[ { "answer_id": 66983, "author": "Peter Boughton", "author_id": 9360, "author_profile": "https://Stackoverflow.com/users/9360", "pm_score": 7, "selected": true, "text": "# <p>This is main body of my content. I have a footnote link for this line <a href=\"#footnote-1\">[1]</a>. Then, I have some more content. Some of it is interesting and it has some footnotes as well <a href=\"#footnote-2\">[2]</a>.</p>\n\n<p id=\"footnote-1\">[1] Here is my first footnote.</p>\n<p id=\"footnote-2\">[2] Another footnote.</p>" }, { "answer_id": 66990, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 0, "selected": false, "text": " This is main body of my content. I have a footnote link for this \nline <a href=\"#foot1\">[1]</a>. Then, I have some more content. \nSome of it is interesting and it has some footnotes as well \n<a href=\"#foot2\">[2]</a>.\n\n<div>\n<a name=\"foot1\">[1]</a> Here is my first footnote.\n</div>\n\n<div>\n<a name=\"foot2\">[2]</a> Another footnote.\n</div>\n" }, { "answer_id": 67014, "author": "Adrian Dunston", "author_id": 8344, "author_profile": "https://Stackoverflow.com/users/8344", "pm_score": 2, "selected": false, "text": " <a name=\"footnote1\">Footnote 1</a>\n <div>blah blah about stuff</div>\n <p>So you can see that the candidate lied \n <a href=\"#footnote1\">[1]</a> \n in his opening address</p>\n <p>For more on that, see \n <a href=\"mypaper.html#footnote1\">footnote 1 from my paper</a>\n , and you will be amazed.</p>\n" }, { "answer_id": 68080, "author": "Sam Hasler", "author_id": 2541, "author_profile": "https://Stackoverflow.com/users/2541", "pm_score": 4, "selected": false, "text": "This is main body of my content.\nI have a footnote link for this line\n<a id=\"footnote-1-ref\" href=\"#footnote-1\">[1]</a>.\nThen, I have some more content.\nSome of it is interesting and it has some footnotes as well\n<a id=\"footnote-2-ref\" href=\"#footnote-2\">[2]</a>.\n\n<p id=\"footnote-1\">\n 1. Here is my first footnote. <a href=\"#footnote-1-ref\">&#8617;</a> \n</p>\n<p id=\"footnote-2\">\n 2. Another footnote. <a href=\"#footnote-2-ref\">&#8617;</a>\n</p>\n This is main body of my content.\nI have a footnote link for this line\n<a id=\"footnote-1-ref\" href=\"#footnote-1\" title=\"link to footnote\">[1]</a>.\nThen, I have some more content.\nSome of it is interesting and it has some footnotes as well\n<a id=\"footnote-2-ref\" href=\"#footnote-2\" title=\"link to footnote\">[2]</a>.\n\n<p id=\"footnote-1\">\n 1. Here is my first footnote.\n <a href=\"#footnote-1-ref\" title=\"return to text\">&#8617;</a> \n</p>\n<p id=\"footnote-2\">\n 2. Another footnote.\n <a href=\"#footnote-2-ref\" title=\"return to text\">&#8617;</a>\n</p>\n" }, { "answer_id": 69127, "author": "Andrey Fedorov", "author_id": 10728, "author_profile": "https://Stackoverflow.com/users/10728", "pm_score": 1, "selected": false, "text": "function absoluteOffset(elem) {\n return elem.offsetParent && elem.offsetTop + absoluteOffset(elem.offsetParent);\n}\n window.scroll function scrollToElement(elem) {\n window.scroll(absoluteOffset(elem));\n}\n" }, { "answer_id": 38296077, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "This is main body of my content. I have a footnote link for this line <a href=\"#footnote-1\">[1]</a>. Then, I have some more content. Some of it is interesting and it has some footnotes as well <a href=\"#footnote-2\">[2]</a>.\n\n<h2>References</h2>\n<ol>\n <li id=\"footnote-1\">Here is my first footnote.</li>\n <li id=\"footnote-2\">Another footnote.</li>\n</ol>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ]
67,021
<p>I'm coding a framework along with a project which uses this framework. The project is a Bazaar repository, with the framework in a subfolder below the project.</p> <p>I want to give the framework a Bazaar repository of its own. How do I do it?</p>
[ { "answer_id": 67126, "author": "jamuraa", "author_id": 9805, "author_profile": "https://Stackoverflow.com/users/9805", "pm_score": 0, "selected": false, "text": "branch project:\n.. other files.. \nframework/a.file\nframework/b.file\nframework/c.file\n\nbranch framework: \na.file\nb.file\nc.file\n" }, { "answer_id": 138836, "author": "Jrgns", "author_id": 6681, "author_profile": "https://Stackoverflow.com/users/6681", "pm_score": 4, "selected": true, "text": "bzr split sub_folder\n" }, { "answer_id": 596656, "author": "bialix", "author_id": 65736, "author_profile": "https://Stackoverflow.com/users/65736", "pm_score": 3, "selected": false, "text": "bzr fast-export BRANCH > full-history.fi\n bzr fast-import-filter -i subfolder full-history.fi > subfolder.fi\n bzr init-repo .\nbzr fast-import subfolder.fi\n" }, { "answer_id": 6299487, "author": "freegnu", "author_id": 133000, "author_profile": "https://Stackoverflow.com/users/133000", "pm_score": 0, "selected": false, "text": "bzr init .\nbzr add .\nbzr commit\n bzr branch . mycopy\nbzr branch . myothercopy\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6681/" ]
67,029
<p>I noticed that Google maps is providing directions in my local language (hungarian) when I am using google chrome, but English language directions when I am using it from IE. </p> <p>I would like to know how chrome figures this out and how can I write code that is always returning directions on the user's language. </p>
[ { "answer_id": 67068, "author": "millenomi", "author_id": 6061, "author_profile": "https://Stackoverflow.com/users/6061", "pm_score": 3, "selected": true, "text": "HTTP" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260/" ]
67,045
<p>I am trying to convince those who set standards at my current organization that we should use jQuery rather than Prototype and/or YUI. What are some convincing advantages I can use to convince them?</p>
[ { "answer_id": 72737, "author": "Michael Thompson", "author_id": 12276, "author_profile": "https://Stackoverflow.com/users/12276", "pm_score": 3, "selected": false, "text": "$('#something').width();\n $('#something').hide().css('background', 'red').fadeIn();\n hover $('table tr').hover(function() {\n $(this).addClass('hover');\n});\n" }, { "answer_id": 8296056, "author": "Ruben Oliveira", "author_id": 1069351, "author_profile": "https://Stackoverflow.com/users/1069351", "pm_score": 2, "selected": false, "text": "<body>\n<div style=\"width: 400px; height: 400px; background-color: red\">\n<div style=\"width: 400px; height: 400px; background-color: red\">\n</div>\n\n<script type=\"text/javascript\">\n\nfunction test1 (){\ndocument.body.innerHTML = \"\"\n\nvar div = document.createElement(\"div\");\n\ndocument.body.appendChild(div);\n\n$(div).width(\"400px\").height(\"400px\").css(\"background-color\", \"red\");\n} \n\nfunction test2 (){\ndocument.body.innerHTML = \"\"\n\nvar div = document.createElement(\"div\");\n\ndocument.body.appendChild(div);\n\n$(div).width(\"400px\");\n$(div).height(\"400px\");\n$(div).css(\"background-color\", \"red\");\n}\n\nfunction test3 (){\ndocument.body.innerHTML = \"\"\n\nvar div = document.createElement(\"div\");\n\ndocument.body.appendChild(div);\n\ndiv.style.width = \"400px\";\ndiv.style.height= \"400px\";\ndiv.style.backgroundColor = \"red\";\n}\n\nfunction test4 (){\n document.body.innerHTML = \"\"\n\n var div = document.createElement(\"div\");\n\n document.body.appendChild(div);\n\n div.setAttribute(\"style\", \"width: 400px; height: 400px; background-color: red\");\n}\n\n</script>\n</body>\n <head> console.profile();\ntest2();\nconsole.profileEnd();\n\nconsole.profile();\ntest3();\nconsole.profileEnd();\n\nconsole.profile();\ntest4();\nconsole.profileEnd();\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
67,056
<p>I would like to get data from from different webpages such as addresses of restaurants or dates of different events for a given location and so on. What is the best library I can use for extracting this data from a given set of sites? </p>
[ { "answer_id": 67166, "author": "Drew Olson", "author_id": 9434, "author_profile": "https://Stackoverflow.com/users/9434", "pm_score": 3, "selected": false, "text": "require 'rubygems'\nrequire 'hpricot'\nrequire 'open-uri'\n\nsites = %w(http://www.google.com http://www.stackoverflow.com)\n\nsites.each do |site|\n doc = Hpricot(open(site))\n\n # iterate over each div in the document (or use xpath to grab whatever you want)\n (doc/\"div\").each do |div|\n # do something with divs here\n end\nend\n" }, { "answer_id": 67194, "author": "Mike", "author_id": 1115144, "author_profile": "https://Stackoverflow.com/users/1115144", "pm_score": 3, "selected": false, "text": "HtmlDocument doc = new HtmlDocument();\ndoc.Load(\"file.htm\");\nforeach(HtmlNode link in doc.DocumentElement.SelectNodes(\"//a@href\")\n{\nHtmlAttribute att = link\"href\";\natt.Value = FixLink(att);\n}\ndoc.Save(\"file.htm\");\n" }, { "answer_id": 67210, "author": "8jean", "author_id": 10011, "author_profile": "https://Stackoverflow.com/users/10011", "pm_score": 2, "selected": false, "text": "look_down() HTML::Element" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260/" ]
67,063
<p>It strikes me that Properties in C# should be use when trying to manipulate a field in the class. But when there's complex calculations or database involved, we should use a getter/setter.</p> <p>Is this correct?</p> <p>When do you use s/getter over properties?</p>
[ { "answer_id": 67186, "author": "Sean Hanley", "author_id": 7290, "author_profile": "https://Stackoverflow.com/users/7290", "pm_score": 1, "selected": false, "text": "open() flush() parse() DisplayName AutoSize DataSource" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10088/" ]
67,069
<p>So I get that most of you are frowning at me for not currently using any source control. I want to, I really do, now that I've spent some time reading the questions / answers here. I am a hobby programmer and really don't do much more than tinker, but I've been bitten a couple of times now not having the 'time machine' handy...</p> <p>I still have to decide which product I'll go with, but that's not relevant to this question.</p> <p>I'm really struggling with the flow of files under source control, so much so I'm not even sure how to pose the question sensibly.</p> <p>Currently I have a directory hierarchy where all my PHP files live in a Linux Environment. I edit them there and can hit refresh on my browser to see what happens.</p> <p>As I understand it, my files now live in a different place. When I want to edit, I check it out and edit away. But what is my substitute for F5? How do I test it? Do I have to check it back in, then hit F5? I admit to a good bit of trial and error in my work. I suspect I'm going to get tired of checking in and out real quick for the frequent small changes I tend to make. I have to be missing something, right?</p> <p>Can anyone step me through where everything lives and how I test along the way, while keeping true to the goal of having a 'time machine' handy?</p>
[ { "answer_id": 67111, "author": "Max Caceres", "author_id": 4842, "author_profile": "https://Stackoverflow.com/users/4842", "pm_score": 0, "selected": false, "text": "working copy" }, { "answer_id": 68240, "author": "willurd", "author_id": 1943957, "author_profile": "https://Stackoverflow.com/users/1943957", "pm_score": 0, "selected": false, "text": "$ which svn\n/usr/bin/svn\n $ apt-get install subversion\n $ apt-cache search subversion\n $ apt-cache search svn\n $ cd /path/to/directory/of/repositories\n$ svnadmin create my_repository\n $ cd /repos/on/your/local/machine\n$ svn co svn+ssh://www.myserver.com/path/to/directory/of/repositories/my_repository\n $ cd /repos/on/your/local/machine\n$ cd my_repository\n$ svn mkdir branches\n$ svn mkdir tags\n$ svn mkdir trunk\n$ svn commit -m \"Initial structure\"\n $ cd /repos/on/your/local/machine\n$ svn add my_new_file.ext\n$ svn add some/new/directory\n$ svn add some/directory/*\n$ svn add some/directory/*.ext\n $ cd /repos/on/your/local/machine\n$ svn status\n $ cd /repos/on/your/local/machine\n$ svn up\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1444/" ]
67,082
<p>What is Windows' best I/O event notification facility? </p> <p>By best I mean something that ...</p> <ol> <li>doesn't have a limit on number of input file descriptors</li> <li>works on all file descriptors (disk files, sockets, ...)</li> <li>provides various notification modes (edge triggered, limit triggered)</li> </ol>
[ { "answer_id": 67594, "author": "Chris Smith", "author_id": 9073, "author_profile": "https://Stackoverflow.com/users/9073", "pm_score": 7, "selected": true, "text": "OVERLAPPED WaitForMultipleObjects MAXIMUM_WAIT_OBJECTS ReadFileEx WriteFileEx SleepEx WaitFor{Single|Multiple}ObjectsEx Alertable TRUE" }, { "answer_id": 16034678, "author": "schlamar", "author_id": 851737, "author_profile": "https://Stackoverflow.com/users/851737", "pm_score": 3, "selected": false, "text": "libuv" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9107/" ]
67,093
<p>The MySQL manual at <a href="http://web.archive.org/web/20160504181056/https://dev.mysql.com/doc/refman/5.1/en/rename-database.html" rel="noreferrer">MySQL</a> covers this.</p> <p>Usually I just dump the database and reimport it with a new name. This is not an option for very big databases. Apparently <code>RENAME {DATABASE | SCHEMA} db_name TO new_db_name;</code> <a href="http://web.archive.org/web/20160504181056/https://dev.mysql.com/doc/refman/5.1/en/rename-database.html" rel="noreferrer">does bad things, exists only in a handful of versions, and is a bad idea overall</a>.</p> <p>This needs to work with <a href="http://en.wikipedia.org/wiki/InnoDB" rel="noreferrer">InnoDB</a>, which stores things very differently than <a href="http://en.wikipedia.org/wiki/MyISAM" rel="noreferrer">MyISAM</a>.</p>
[ { "answer_id": 67187, "author": "DeeCee", "author_id": 5895, "author_profile": "https://Stackoverflow.com/users/5895", "pm_score": 5, "selected": false, "text": "cd /var/lib/mysql/\n /etc/init.d/mysql stop\n mv old-name new-name\n cd database/\n\nmv old-name.frm new-name.frm\n\nmv old-name.MYD new-name.MYD\n\nmv old-name.MYI new-name.MYI\n /etc/init.d/mysql start\n" }, { "answer_id": 362408, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": ":: ***************************************************************************\n:: FILE: RENAME_MYSQLDB.BAT\n:: ***************************************************************************\n:: DESCRIPTION\n:: This is a Windows /MS-DOS batch file that automates renaming a MySQL database \n:: by using MySQLDump, MySQLAdmin, and MySQL to perform the required tasks.\n:: The MySQL\\bin folder needs to be in your environment path or the working directory.\n::\n:: WARNING: The script will delete the original database, but only if it successfully\n:: created the new copy. However, read the disclaimer below before using.\n::\n:: DISCLAIMER\n:: This script is provided without any express or implied warranties whatsoever.\n:: The user must assume the risk of using the script.\n::\n:: You are free to use, modify, and distribute this script without exception.\n:: ***************************************************************************\n\n:INITIALIZE\n@ECHO OFF\nIF [%2]==[] GOTO HELP\nIF [%3]==[] (SET RDB_ARGS=--user=root) ELSE (SET RDB_ARGS=%3 %4 %5 %6 %7 %8 %9)\nSET RDB_OLDDB=%1\nSET RDB_NEWDB=%2\nSET RDB_DUMPFILE=%RDB_OLDDB%_dump.sql\nGOTO START\n\n:START\nSET RDB_STEP=1\nECHO Dumping \"%RDB_OLDDB%\"...\nmysqldump %RDB_ARGS% %RDB_OLDDB% > %RDB_DUMPFILE%\nIF %ERRORLEVEL% NEQ 0 GOTO ERROR_ABORT\nSET RDB_STEP=2\nECHO Creating database \"%RDB_NEWDB%\"...\nmysqladmin %RDB_ARGS% create %RDB_NEWDB%\nIF %ERRORLEVEL% NEQ 0 GOTO ERROR_ABORT\nSET RDB_STEP=3\nECHO Loading dump into \"%RDB_NEWDB%\"...\nmysql %RDB_ARGS% %RDB_NEWDB% < %RDB_DUMPFILE%\nIF %ERRORLEVEL% NEQ 0 GOTO ERROR_ABORT\nSET RDB_STEP=4\nECHO Dropping database \"%RDB_OLDDB%\"...\nmysqladmin %RDB_ARGS% drop %RDB_OLDDB% --force\nIF %ERRORLEVEL% NEQ 0 GOTO ERROR_ABORT\nSET RDB_STEP=5\nECHO Deleting dump...\nDEL %RDB_DUMPFILE%\nIF %ERRORLEVEL% NEQ 0 GOTO ERROR_ABORT\nECHO Renamed database \"%RDB_OLDDB%\" to \"%RDB_NEWDB%\".\nGOTO END\n\n:ERROR_ABORT\nIF %RDB_STEP% GEQ 3 mysqladmin %RDB_ARGS% drop %NEWDB% --force\nIF %RDB_STEP% GEQ 1 IF EXIST %RDB_DUMPFILE% DEL %RDB_DUMPFILE%\nECHO Unable to rename database \"%RDB_OLDDB%\" to \"%RDB_NEWDB%\".\nGOTO END\n\n:HELP\nECHO Renames a MySQL database.\nECHO Usage: %0 database new_database [OPTIONS]\nECHO Options: Any valid options shared by MySQL, MySQLAdmin and MySQLDump.\nECHO --user=root is used if no options are specified.\nGOTO END \n\n:END\nSET RDB_OLDDB=\nSET RDB_NEWDB=\nSET RDB_ARGS=\nSET RDB_DUMP=\nSET RDB_STEP=\n" }, { "answer_id": 1072988, "author": "hendrasaputra", "author_id": 76045, "author_profile": "https://Stackoverflow.com/users/76045", "pm_score": 9, "selected": false, "text": "mysqldump -u username -p -v olddatabase > olddbdump.sql\nmysqladmin -u username -p create newdatabase\nmysql -u username -p newdatabase < olddbdump.sql\n mysqladmin -u username -p create newdatabase\nmysqldump -u username -v olddatabase -p | mysql -u username -p -D newdatabase\n" }, { "answer_id": 2298602, "author": "Thorsten", "author_id": 277222, "author_profile": "https://Stackoverflow.com/users/277222", "pm_score": 11, "selected": true, "text": "RENAME TABLE old_db.table TO new_db.table;\n mysql -u username -ppassword old_db -sNe 'show tables' | while read table; \\ \n do mysql -u username -ppassword -sNe \"rename table old_db.$table to new_db.$table\"; done\n for table in `mysql -u root -ppassword -s -N -e \"use old_db;show tables from old_db;\"`; do mysql -u root -ppassword -s -N -e \"use old_db;rename table old_db.$table to new_db.$table;\"; done;\n -p -u username -ppassword Trigger in wrong schema mysqldump old_db | mysql new_db mysqldump -R old_db | mysql new_db" }, { "answer_id": 2788771, "author": "Amr Mostafa", "author_id": 43597, "author_profile": "https://Stackoverflow.com/users/43597", "pm_score": 4, "selected": false, "text": "RENAME TABLE old_db.table TO new_db.table;\n" }, { "answer_id": 3152013, "author": "nicky", "author_id": 380366, "author_profile": "https://Stackoverflow.com/users/380366", "pm_score": -1, "selected": false, "text": "mydatab_online user user timestamp ip file timestamp ip ip file file user user timestamp ip file /temp" }, { "answer_id": 3853838, "author": "mathew", "author_id": 465634, "author_profile": "https://Stackoverflow.com/users/465634", "pm_score": -1, "selected": false, "text": "mysql" }, { "answer_id": 3917812, "author": "Morgan Christiansson", "author_id": 34516, "author_profile": "https://Stackoverflow.com/users/34516", "pm_score": 2, "selected": false, "text": "mk-find --dblike OLD_DATABASE --print --exec \"RENAME TABLE %D.%N TO NEW_DATABASE.%N\"\n" }, { "answer_id": 4044140, "author": "eaykin", "author_id": 143179, "author_profile": "https://Stackoverflow.com/users/143179", "pm_score": 4, "selected": false, "text": "$ mysqldump -u root -p olddb >~/olddb.sql\n$ mysql -u root -p\nmysql> create database newdb;\nmysql> use newdb\nmysql> source ~/olddb.sql\nmysql> drop database olddb;\n" }, { "answer_id": 7674554, "author": "Nadav Benedek", "author_id": 900919, "author_profile": "https://Stackoverflow.com/users/900919", "pm_score": 2, "selected": false, "text": "@echo off\nset olddb=olddbname\nset newdb=newdbname\nSET count=1\nSET act=mysql -uroot -e \"select table_name from information_schema.tables where table_schema='%olddb%'\"\nmysql -uroot -e \"create database %newdb%\"\necho %act%\n FOR /f \"tokens=*\" %%G IN ('%act%') DO (\n REM echo %count%:%%G\n echo mysql -uroot -e \"RENAME TABLE %olddb%.%%G to %newdb%.%%G\"\n mysql -uroot -e \"RENAME TABLE %olddb%.%%G to %newdb%.%%G\"\n set /a count+=1\n )\nmysql -uroot -e \"drop database %olddb%\"\n" }, { "answer_id": 8276073, "author": "ErichBSchulz", "author_id": 894487, "author_profile": "https://Stackoverflow.com/users/894487", "pm_score": 7, "selected": false, "text": "GROUP_CONCAT SELECT CONCAT('RENAME TABLE $1.', table_name, ' TO $2.', table_name, '; ')\nFROM information_schema.TABLES \nWHERE table_schema='$1';\n SELECT GROUP_CONCAT('RENAME TABLE $1.', table_name, ' TO $2.', table_name SEPARATOR '; ')\nFROM information_schema.TABLES \nWHERE table_schema='$1';\n GROUP_CONCAT SET SESSION group_concat_max_len = 100000000;" }, { "answer_id": 8872770, "author": "raphie", "author_id": 424543, "author_profile": "https://Stackoverflow.com/users/424543", "pm_score": 8, "selected": false, "text": "RENAME TO ALTER TABLE `schema_name`.`table_name` \nRENAME TO `schema_name`.`new_table_name` ;\n ALTER TABLE `schema_name`.`table_name` RENAME TO `schema_name`.`new_table_name` ;\n" }, { "answer_id": 9721378, "author": "gerrit damen", "author_id": 1271733, "author_profile": "https://Stackoverflow.com/users/1271733", "pm_score": 3, "selected": false, "text": "#!/usr/bin/env bash\n\nmysql -e \"CREATE DATABASE $2 DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;\"\nfor i in $(mysql -Ns $1 -e \"show tables\");do\n echo \"$1.$i -> $2.$i\"\n mysql -e \"rename TABLE $1.$i to $2.$i\"\ndone\nmysql -e \"DROP DATABASE $1\"\n" }, { "answer_id": 9763752, "author": "coffeefiend", "author_id": 1265141, "author_profile": "https://Stackoverflow.com/users/1265141", "pm_score": 2, "selected": false, "text": "history -d $((HISTCMD-1)) && mysql -udb_user -p'db_password' -Dold_schema -ABNnqre'SHOW TABLES;' | sed -e's/.*/RENAME TABLE old_schema.`&` TO new_schema.`&`;/' | mysql -udb_user -p'db_password' -Dnew_schema\n db_user" }, { "answer_id": 11908987, "author": "Marciano", "author_id": 1059937, "author_profile": "https://Stackoverflow.com/users/1059937", "pm_score": 6, "selected": false, "text": "RENAME DATABASE SELECT CONCAT('RENAME TABLE ',table_schema,'.`',table_name,\n '` TO ','new_schema.`',table_name,'`;')\n FROM information_schema.TABLES\n WHERE table_schema LIKE 'old_schema';\n" }, { "answer_id": 11979761, "author": "xelber", "author_id": 1478008, "author_profile": "https://Stackoverflow.com/users/1478008", "pm_score": 2, "selected": false, "text": "ALTER DATABASE RENAME DATABASE RENAME {DATABASE | SCHEMA} db_name TO new_db_name;\n" }, { "answer_id": 14287770, "author": "Milosz", "author_id": 1042595, "author_profile": "https://Stackoverflow.com/users/1042595", "pm_score": 2, "selected": false, "text": "DELIMITER //\nDROP PROCEDURE IF EXISTS `rename_database`;\nCREATE PROCEDURE `rename_database` (IN `old_name` VARCHAR(20), IN `new_name` VARCHAR(20))\nBEGIN\n DECLARE `current_table_name` VARCHAR(20);\n DECLARE `done` INT DEFAULT 0;\n DECLARE `table_name_cursor` CURSOR FOR SELECT `table_name` FROM `information_schema`.`tables` WHERE (`table_schema` = `old_name`);\n DECLARE CONTINUE HANDLER FOR NOT FOUND SET `done` = 1;\n\n SET @sql_string = CONCAT('CREATE DATABASE IF NOT EXISTS `', `new_name` , '`;');\n PREPARE `statement` FROM @sql_string;\n EXECUTE `statement`;\n DEALLOCATE PREPARE `statement`;\n\n OPEN `table_name_cursor`;\n REPEAT\n FETCH `table_name_cursor` INTO `current_table_name`;\n IF NOT `done` THEN\n\n SET @sql_string = CONCAT('RENAME TABLE `', `old_name`, '`.`', `current_table_name`, '` TO `', `new_name`, '`.`', `current_table_name`, '`;');\n PREPARE `statement` FROM @sql_string;\n EXECUTE `statement`;\n DEALLOCATE PREPARE `statement`;\n\n END IF;\n UNTIL `done` END REPEAT;\n CLOSE `table_name_cursor`;\n\n SET @sql_string = CONCAT('DROP DATABASE `', `old_name`, '`;');\n PREPARE `statement` FROM @sql_string;\n EXECUTE `statement`;\n DEALLOCATE PREPARE `statement`;\nEND//\nDELIMITER ;\n @sql_string" }, { "answer_id": 14745363, "author": "Grijesh Chauhan", "author_id": 1673391, "author_profile": "https://Stackoverflow.com/users/1673391", "pm_score": 5, "selected": false, "text": "#!/bin/bash\nset -e # terminate execution on command failure\n\nmysqlconn=\"mysql -u root -proot\"\nolddb=$1\nnewdb=$2\n$mysqlconn -e \"CREATE DATABASE $newdb\"\nparams=$($mysqlconn -N -e \"SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES \\\n WHERE table_schema='$olddb'\")\nfor name in $params; do\n $mysqlconn -e \"RENAME TABLE $olddb.$name to $newdb.$name\";\ndone;\n$mysqlconn -e \"DROP DATABASE $olddb\"\n $ sh rename_database.sh oldname newname\n" }, { "answer_id": 18350130, "author": "murtaza.webdev", "author_id": 2024056, "author_profile": "https://Stackoverflow.com/users/2024056", "pm_score": 2, "selected": false, "text": "select database \n\n goto operations tab\n\n in that rename Database to :\n\n type your new database name and click go\n" }, { "answer_id": 21429390, "author": "Sathish D", "author_id": 925144, "author_profile": "https://Stackoverflow.com/users/925144", "pm_score": 4, "selected": false, "text": " mysqldump emp > emp.out\n mysql -e \"CREATE DATABASE employees;\"\n mysql employees < emp.out \n mysql -e \"DROP DATABASE emp;\"\n If there are views, triggers, functions, stored procedures in the schema, those will need to be recreated too Dump the triggers, events and stored routines in a separate file. $ mysqldump <old_schema_name> -d -t -R -E > stored_routines_triggers_events.out\n information_schema.TABLES mysql> select TABLE_NAME from information_schema.tables where \n table_schema='<old_schema_name>' and TABLE_TYPE='BASE TABLE';\n information_schema.TABLES mysql> select TABLE_NAME from information_schema.tables where \n table_schema='<old_schema_name>' and TABLE_TYPE='VIEW';\n $ mysqldump <database> <view1> <view2> … > views.out\n mysql> DROP TRIGGER <trigger_name>;\n...\n mysql> RENAME TABLE <old_schema>.table_name TO <new_schema>.table_name;\n...\n$ mysql <new_schema> < views.out\n$ mysql <new_schema> < stored_routines_triggers_events.out\n [root@dba~]# /tmp/rename_db\nrename_db <server> <database> <new_database>\n mysql> show databases;\n+--------------------+\n| Database |\n+--------------------+\n| information_schema |\n| emp |\n| mysql |\n| performance_schema |\n| test |\n+--------------------+\n\n\n[root@dba ~]# time /tmp/rename_db localhost emp emp_test\ncreate database emp_test DEFAULT CHARACTER SET latin1\ndrop trigger salary_trigger\nrename table emp.__emp_new to emp_test.__emp_new\nrename table emp._emp_new to emp_test._emp_new\nrename table emp.departments to emp_test.departments\nrename table emp.dept to emp_test.dept\nrename table emp.dept_emp to emp_test.dept_emp\nrename table emp.dept_manager to emp_test.dept_manager\nrename table emp.emp to emp_test.emp\nrename table emp.employees to emp_test.employees\nrename table emp.salaries_temp to emp_test.salaries_temp\nrename table emp.titles to emp_test.titles\nloading views\nloading triggers, routines and events\nDropping database emp\n\nreal 0m0.643s\nuser 0m0.053s\nsys 0m0.131s\n\n\nmysql> show databases;\n+--------------------+\n| Database |\n+--------------------+\n| information_schema |\n| emp_test |\n| mysql |\n| performance_schema |\n| test |\n+--------------------+\n #!/bin/bash\n# Copyright 2013 Percona LLC and/or its affiliates\nset -e\nif [ -z \"$3\" ]; then\n echo \"rename_db <server> <database> <new_database>\"\n exit 1\nfi\ndb_exists=`mysql -h $1 -e \"show databases like '$3'\" -sss`\nif [ -n \"$db_exists\" ]; then\n echo \"ERROR: New database already exists $3\"\n exit 1\nfi\nTIMESTAMP=`date +%s`\ncharacter_set=`mysql -h $1 -e \"show create database $2\\G\" -sss | grep ^Create | awk -F'CHARACTER SET ' '{print $2}' | awk '{print $1}'`\nTABLES=`mysql -h $1 -e \"select TABLE_NAME from information_schema.tables where table_schema='$2' and TABLE_TYPE='BASE TABLE'\" -sss`\nSTATUS=$?\nif [ \"$STATUS\" != 0 ] || [ -z \"$TABLES\" ]; then\n echo \"Error retrieving tables from $2\"\n exit 1\nfi\necho \"create database $3 DEFAULT CHARACTER SET $character_set\"\nmysql -h $1 -e \"create database $3 DEFAULT CHARACTER SET $character_set\"\nTRIGGERS=`mysql -h $1 $2 -e \"show triggers\\G\" | grep Trigger: | awk '{print $2}'`\nVIEWS=`mysql -h $1 -e \"select TABLE_NAME from information_schema.tables where table_schema='$2' and TABLE_TYPE='VIEW'\" -sss`\nif [ -n \"$VIEWS\" ]; then\n mysqldump -h $1 $2 $VIEWS > /tmp/${2}_views${TIMESTAMP}.dump\nfi\nmysqldump -h $1 $2 -d -t -R -E > /tmp/${2}_triggers${TIMESTAMP}.dump\nfor TRIGGER in $TRIGGERS; do\n echo \"drop trigger $TRIGGER\"\n mysql -h $1 $2 -e \"drop trigger $TRIGGER\"\ndone\nfor TABLE in $TABLES; do\n echo \"rename table $2.$TABLE to $3.$TABLE\"\n mysql -h $1 $2 -e \"SET FOREIGN_KEY_CHECKS=0; rename table $2.$TABLE to $3.$TABLE\"\ndone\nif [ -n \"$VIEWS\" ]; then\n echo \"loading views\"\n mysql -h $1 $3 < /tmp/${2}_views${TIMESTAMP}.dump\nfi\necho \"loading triggers, routines and events\"\nmysql -h $1 $3 < /tmp/${2}_triggers${TIMESTAMP}.dump\nTABLES=`mysql -h $1 -e \"select TABLE_NAME from information_schema.tables where table_schema='$2' and TABLE_TYPE='BASE TABLE'\" -sss`\nif [ -z \"$TABLES\" ]; then\n echo \"Dropping database $2\"\n mysql -h $1 $2 -e \"drop database $2\"\nfi\nif [ `mysql -h $1 -e \"select count(*) from mysql.columns_priv where db='$2'\" -sss` -gt 0 ]; then\n COLUMNS_PRIV=\" UPDATE mysql.columns_priv set db='$3' WHERE db='$2';\"\nfi\nif [ `mysql -h $1 -e \"select count(*) from mysql.procs_priv where db='$2'\" -sss` -gt 0 ]; then\n PROCS_PRIV=\" UPDATE mysql.procs_priv set db='$3' WHERE db='$2';\"\nfi\nif [ `mysql -h $1 -e \"select count(*) from mysql.tables_priv where db='$2'\" -sss` -gt 0 ]; then\n TABLES_PRIV=\" UPDATE mysql.tables_priv set db='$3' WHERE db='$2';\"\nfi\nif [ `mysql -h $1 -e \"select count(*) from mysql.db where db='$2'\" -sss` -gt 0 ]; then\n DB_PRIV=\" UPDATE mysql.db set db='$3' WHERE db='$2';\"\nfi\nif [ -n \"$COLUMNS_PRIV\" ] || [ -n \"$PROCS_PRIV\" ] || [ -n \"$TABLES_PRIV\" ] || [ -n \"$DB_PRIV\" ]; then\n echo \"IF YOU WANT TO RENAME the GRANTS YOU NEED TO RUN ALL OUTPUT BELOW:\"\n if [ -n \"$COLUMNS_PRIV\" ]; then echo \"$COLUMNS_PRIV\"; fi\n if [ -n \"$PROCS_PRIV\" ]; then echo \"$PROCS_PRIV\"; fi\n if [ -n \"$TABLES_PRIV\" ]; then echo \"$TABLES_PRIV\"; fi\n if [ -n \"$DB_PRIV\" ]; then echo \"$DB_PRIV\"; fi\n echo \" flush privileges;\"\nfi\n" }, { "answer_id": 25250493, "author": "yantaq", "author_id": 554060, "author_profile": "https://Stackoverflow.com/users/554060", "pm_score": 2, "selected": false, "text": "SELECT DISTINCT CONCAT('RENAME TABLE ', t.table_schema,'.', t.table_name, ' TO ', \nt.table_schema, \"_archive\", '.', t.table_name, ';' ) as Rename_SQL \nFROM information_schema.tables t\nWHERE table_schema='your_db_name' ;\n" }, { "answer_id": 32140744, "author": "gadelat", "author_id": 524965, "author_profile": "https://Stackoverflow.com/users/524965", "pm_score": 1, "selected": false, "text": "#!/usr/bin/env perl\n\nuse List::MoreUtils 'first_index'; #apt package liblist-moreutils-perl\nuse strict;\nuse warnings;\n\n\nmy $views_sql;\n\nwhile (<>) {\n $views_sql .= $_ if $views_sql or index($_, 'Final view structure') != -1;\n print $_ if !$views_sql;\n}\n\nmy @views_regex_result = ($views_sql =~ /(\\-\\- Final view structure.+?\\n\\-\\-\\n\\n.+?\\n\\n)/msg);\nmy @views = (join(\"\", @views_regex_result) =~ /\\-\\- Final view structure for view `(.+?)`/g);\nmy $new_views_section = \"\";\nwhile (@views) {\n foreach my $view (@views_regex_result) {\n my $view_body = ($view =~ /\\/\\*.+?VIEW .+ AS (select .+)\\*\\/;/g )[0];\n my $found = 0;\n foreach my $view (@views) {\n if ($view_body =~ /(from|join)[ \\(]+`$view`/) {\n $found = $view;\n last;\n }\n }\n if (!$found) {\n print $view;\n my $name_of_view_which_was_not_found = ($view =~ /\\-\\- Final view structure for view `(.+?)`/g)[0];\n my $index = first_index { $_ eq $name_of_view_which_was_not_found } @views;\n if ($index != -1) {\n splice(@views, $index, 1);\n splice(@views_regex_result, $index, 1);\n }\n }\n }\n}\n mysqldump -u username -v olddatabase -p | ./mysqldump_view_reorder.pl | mysql -u username -p -D newdatabase" }, { "answer_id": 34794989, "author": "Steve Chambers", "author_id": 1063716, "author_profile": "https://Stackoverflow.com/users/1063716", "pm_score": 4, "selected": false, "text": "mysqladmin -uroot -pmypassword create newdbname\nmysqldump -uroot -pmypassword --routines olddbname | mysql -uroot -pmypassword newdbname\nmysqladmin -uroot -pmypassword drop olddbname\n" }, { "answer_id": 37379876, "author": "Tim Duncklee", "author_id": 1163122, "author_profile": "https://Stackoverflow.com/users/1163122", "pm_score": -1, "selected": false, "text": "$oldDbName = \"oldDBName\";\n$newDbName = \"newDBName\";\n$oldDB = new mysqli(\"localhost\", \"user\", \"pass\", $oldDbName);\nif($oldDB->connect_errno){\n echo \"Failed to connect to MySQL: (\" . $oldDB->connect_errno . \") \" . $oldDB->connect_error;\n exit;\n}\n$newDBQuery = \"CREATE DATABASE IF NOT EXISTS {$newDbName}\";\n$oldDB->query($newDBQuery);\n$newDB = new mysqli(\"localhost\", \"user\", \"pass\");\nif($newDB->connect_errno){\n echo \"Failed to connect to MySQL: (\" . $newDB->connect_errno . \") \" . $newDB->connect_error;\n exit;\n}\n\n$tableQuery = \"SHOW TABLES\";\n$tableResult = $oldDB->query($tableQuery);\n$renameQuery = \"RENAME TABLE\\n\";\nwhile($table = $tableResult->fetch_array()){\n $tableName = $table[\"Tables_in_{$oldDbName}\"];\n $renameQuery .= \"{$oldDbName}.{$tableName} TO {$newDbName}.{$tableName},\";\n}\n$renameQuery = substr($renameQuery, 0, strlen($renameQuery) - 1);\n$newDB->query($renameQuery);\n" }, { "answer_id": 42125897, "author": "ryantm", "author_id": 823, "author_profile": "https://Stackoverflow.com/users/823", "pm_score": 4, "selected": false, "text": "#!/bin/bash\n# Copyright 2013 Percona LLC and/or its affiliates\n# @see https://www.percona.com/blog/2013/12/24/renaming-database-schema-mysql/\nset -e\nif [ -z \"$3\" ]; then\n echo \"rename_db <server> <database> <new_database>\"\n exit 1\nfi\ndb_exists=`mysql -h $1 -e \"show databases like '$3'\" -sss`\nif [ -n \"$db_exists\" ]; then\n echo \"ERROR: New database already exists $3\"\n exit 1\nfi\nTIMESTAMP=`date +%s`\ncharacter_set=`mysql -h $1 -e \"SELECT default_character_set_name FROM information_schema.SCHEMATA WHERE schema_name = '$2'\" -sss`\nTABLES=`mysql -h $1 -e \"select TABLE_NAME from information_schema.tables where table_schema='$2' and TABLE_TYPE='BASE TABLE'\" -sss`\nSTATUS=$?\nif [ \"$STATUS\" != 0 ] || [ -z \"$TABLES\" ]; then\n echo \"Error retrieving tables from $2\"\n exit 1\nfi\necho \"create database $3 DEFAULT CHARACTER SET $character_set\"\nmysql -h $1 -e \"create database $3 DEFAULT CHARACTER SET $character_set\"\nTRIGGERS=`mysql -h $1 $2 -e \"show triggers\\G\" | grep Trigger: | awk '{print $2}'`\nVIEWS=`mysql -h $1 -e \"select TABLE_NAME from information_schema.tables where table_schema='$2' and TABLE_TYPE='VIEW'\" -sss`\nif [ -n \"$VIEWS\" ]; then\n mysqldump -h $1 $2 $VIEWS > /tmp/${2}_views${TIMESTAMP}.dump\nfi\nmysqldump -h $1 $2 -d -t -R -E > /tmp/${2}_triggers${TIMESTAMP}.dump\nfor TRIGGER in $TRIGGERS; do\n echo \"drop trigger $TRIGGER\"\n mysql -h $1 $2 -e \"drop trigger $TRIGGER\"\ndone\nfor TABLE in $TABLES; do\n echo \"rename table $2.$TABLE to $3.$TABLE\"\n mysql -h $1 $2 -e \"SET FOREIGN_KEY_CHECKS=0; rename table $2.$TABLE to $3.$TABLE\"\ndone\nif [ -n \"$VIEWS\" ]; then\n echo \"loading views\"\n mysql -h $1 $3 < /tmp/${2}_views${TIMESTAMP}.dump\nfi\necho \"loading triggers, routines and events\"\nmysql -h $1 $3 < /tmp/${2}_triggers${TIMESTAMP}.dump\nTABLES=`mysql -h $1 -e \"select TABLE_NAME from information_schema.tables where table_schema='$2' and TABLE_TYPE='BASE TABLE'\" -sss`\nif [ -z \"$TABLES\" ]; then\n echo \"Dropping database $2\"\n mysql -h $1 $2 -e \"drop database $2\"\nfi\nif [ `mysql -h $1 -e \"select count(*) from mysql.columns_priv where db='$2'\" -sss` -gt 0 ]; then\n COLUMNS_PRIV=\" UPDATE mysql.columns_priv set db='$3' WHERE db='$2';\"\nfi\nif [ `mysql -h $1 -e \"select count(*) from mysql.procs_priv where db='$2'\" -sss` -gt 0 ]; then\n PROCS_PRIV=\" UPDATE mysql.procs_priv set db='$3' WHERE db='$2';\"\nfi\nif [ `mysql -h $1 -e \"select count(*) from mysql.tables_priv where db='$2'\" -sss` -gt 0 ]; then\n TABLES_PRIV=\" UPDATE mysql.tables_priv set db='$3' WHERE db='$2';\"\nfi\nif [ `mysql -h $1 -e \"select count(*) from mysql.db where db='$2'\" -sss` -gt 0 ]; then\n DB_PRIV=\" UPDATE mysql.db set db='$3' WHERE db='$2';\"\nfi\nif [ -n \"$COLUMNS_PRIV\" ] || [ -n \"$PROCS_PRIV\" ] || [ -n \"$TABLES_PRIV\" ] || [ -n \"$DB_PRIV\" ]; then\n echo \"IF YOU WANT TO RENAME the GRANTS YOU NEED TO RUN ALL OUTPUT BELOW:\"\n if [ -n \"$COLUMNS_PRIV\" ]; then echo \"$COLUMNS_PRIV\"; fi\n if [ -n \"$PROCS_PRIV\" ]; then echo \"$PROCS_PRIV\"; fi\n if [ -n \"$TABLES_PRIV\" ]; then echo \"$TABLES_PRIV\"; fi\n if [ -n \"$DB_PRIV\" ]; then echo \"$DB_PRIV\"; fi\n echo \" flush privileges;\"\nfi\n rename_db chmod +x rename_db ./rename_db localhost old_db new_db" }, { "answer_id": 44889494, "author": "RotS", "author_id": 5053266, "author_profile": "https://Stackoverflow.com/users/5053266", "pm_score": 0, "selected": false, "text": "sed -i -- \"s|old_name_database1|new_name_database1|g\" my_dump.sql\nsed -i -- \"s|old_name_database2|new_name_database2|g\" my_dump.sql\n...\n" }, { "answer_id": 46347714, "author": "Tuncay Göncüoğlu", "author_id": 1372570, "author_profile": "https://Stackoverflow.com/users/1372570", "pm_score": 3, "selected": false, "text": "create database NewDatabaseName like OldDatabaseName;\n create NewDatabaseName.tablename like OldDatabaseName.tablename;\ninsert into NewDataBaseName.tablename select * from OldDatabaseName.tablename;\n drop database OldDatabaseName;\n" }, { "answer_id": 46558670, "author": "Roee Gavirel", "author_id": 672689, "author_profile": "https://Stackoverflow.com/users/672689", "pm_score": 3, "selected": false, "text": "Sequel Pro Database Rename database..." }, { "answer_id": 51368516, "author": "overals", "author_id": 4066372, "author_profile": "https://Stackoverflow.com/users/4066372", "pm_score": -1, "selected": false, "text": "ALTER DATABASE `oldName` MODIFY NAME = `newName`;\n" }, { "answer_id": 62927756, "author": "nafischonchol", "author_id": 10127054, "author_profile": "https://Stackoverflow.com/users/10127054", "pm_score": 0, "selected": false, "text": "UPDATE `db`SET Db = 'new_db_name' where Db = 'old_db_name';\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/556/" ]
67,103
<p>I have an application that uses NHibernate as its ORM and sometimes it experiences performance issues due to how the data is being accessed by it. What kind of things can be done to improve the performance of NHibernate? (Please limit to one recommendation per answer)</p>
[ { "answer_id": 238788, "author": "David P", "author_id": 13145, "author_profile": "https://Stackoverflow.com/users/13145", "pm_score": 5, "selected": false, "text": " public class NHibernateSessionManager\n {\n private readonly ISessionFactory _sessionFactory;\n\n public static readonly NHibernateSessionManager Instance = new NHibernateSessionManager();\n\n private NHibernateSessionManager()\n {\n if (_sessionFactory == null)\n {\n System.Diagnostics.Debug.WriteLine(\"Factory was null - creating one\");\n _sessionFactory = (new Configuration().Configure().BuildSessionFactory());\n }\n }\n\n public ISession GetSession()\n {\n return _sessionFactory.OpenSession();\n }\n\n public void Initialize()\n {\n ISession disposeMe = Instance.GetSession();\n }\n }\n protected void Application_Start()\n{\n NHibernateSessionManager.Instance.Initialize();\n}\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ]
67,117
<p>Are there any documented techniques for speeding up mySQL dumps and imports?</p> <p>This would include my.cnf settings, using ramdisks, etc. </p> <p>Looking only for documented techniques, preferably with benchmarks showing potential speed-up.</p>
[ { "answer_id": 73067, "author": "Aleksandar Ivanisevic", "author_id": 12537, "author_profile": "https://Stackoverflow.com/users/12537", "pm_score": 4, "selected": false, "text": "innodb_flush_log_at_trx_commit = 2\n my.cnf 1" }, { "answer_id": 1112246, "author": "gahooa", "author_id": 64004, "author_profile": "https://Stackoverflow.com/users/64004", "pm_score": 3, "selected": false, "text": "--opt" }, { "answer_id": 2666356, "author": "Ztyx", "author_id": 260805, "author_profile": "https://Stackoverflow.com/users/260805", "pm_score": 3, "selected": false, "text": "-C --compress mysqldump --quick mysqldump --disable-keys" }, { "answer_id": 2666363, "author": "Ztyx", "author_id": 260805, "author_profile": "https://Stackoverflow.com/users/260805", "pm_score": 1, "selected": false, "text": "mysqlhotcopy" }, { "answer_id": 8346162, "author": "Jeff Hiltz", "author_id": 13471, "author_profile": "https://Stackoverflow.com/users/13471", "pm_score": 5, "selected": false, "text": "innodb_buffer_pool_size" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/556/" ]
67,141
<p>Does anybody here have positive experience of working with MS SQL Server 2005 from Rails 2.x?</p> <p>Our developers use Mac OS X, and our production runs on Linux. For legacy reasons we should use MS SQL Server 2005.</p> <p>We're using ruby-odbc and are running into various problems, too depressing to list here. I get an impression that we're doing something wrong. </p> <p>I'm talking about the no-compromise usage, that is, with migrations and all.</p> <p>Thank you,</p>
[ { "answer_id": 99768, "author": "hectorsq", "author_id": 14755, "author_profile": "https://Stackoverflow.com/users/14755", "pm_score": 2, "selected": false, "text": "gem install activerecord-sqlserver-adapter\n--source=http://gems.rubyonrails.org\n development:\nadapter: sqlserver\ndatabase: your_database_name\nhost: your_sqlserver_host\nusername: your_sqlserver_user\npassword: your_sqlserver_password\n" }, { "answer_id": 185827, "author": "Benjamin Atkin", "author_id": 3461, "author_profile": "https://Stackoverflow.com/users/3461", "pm_score": 3, "selected": false, "text": "jruby -S gem install rails jruby -S gem install activerecord-jdbcmssql-adapter jruby -S rails hello jruby script/console" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7754/" ]
67,151
<p>How can I go about hosting flash content inside a WPF form and still use transparency/alpha on my WPF window? Hosting a WinForms flash controls does not allow this.</p>
[ { "answer_id": 22435069, "author": "Ailayna Entarria", "author_id": 2424285, "author_profile": "https://Stackoverflow.com/users/2424285", "pm_score": -1, "selected": false, "text": " private void Window_Loaded(object sender, RoutedEventArgs e)\n { \n MyHelper.ExtendFrame(this, new Thickness(-1)); \n this.MyBrowser.Navigate(@\"C:\\Happy\\Download\\flash\\PlayWithMEGame.swf\"); \n }\n public class MyHelper\n{\n public static bool ExtendFrame(Window window, Thickness margin)\n {\n IntPtr hwnd = new WindowInteropHelper(window).Handle;\n window.Background = Brushes.Transparent;\n HwndSource.FromHwnd(hwnd).CompositionTarget.BackgroundColor = Colors.Transparent;\n MARGINS margins = new MARGINS(margin);\n DwmExtendFrameIntoClientArea(hwnd, ref margins);\n return true;\n }\n [DllImport(\"dwmapi.dll\", PreserveSig = false)]\n static extern void DwmExtendFrameIntoClientArea(IntPtr hwnd, ref MARGINS margins);\n}\n\n struct MARGINS\n {\n public MARGINS(Thickness t)\n {\n Left = (int)t.Left;\n Right = (int)t.Right;\n Top = (int)t.Top;\n Bottom = (int)t.Bottom;\n }\n public int Left;\n public int Right;\n public int Top;\n public int Bottom;\n }\n using System.Runtime.InteropServices;\nusing System.Windows.Interop;\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10119/" ]
67,154
<p>I am working on a cocoa software and in order to keep the GUI responsive during a massive data import (Core Data) I need to run the import outside the main thread.</p> <p>Is it safe to access those objects even if I created them in the main thread without using locks <strong>if</strong> I don't explicitly access those objects while the thread is running.</p>
[ { "answer_id": 67271, "author": "Doug T.", "author_id": 8123, "author_profile": "https://Stackoverflow.com/users/8123", "pm_score": 0, "selected": false, "text": "void CreateObject()\n{\n Object* sharedObj = new Object();\n PassObjectToUsingThread( sharedObj); // this function would be system dependent\n}\n" }, { "answer_id": 67965, "author": "Barry Wark", "author_id": 2140, "author_profile": "https://Stackoverflow.com/users/2140", "pm_score": 1, "selected": false, "text": "[NSManagedObject initWithEntity:insertIntoManagedObjectContext:]" }, { "answer_id": 68237, "author": "Chris Hanson", "author_id": 714, "author_profile": "https://Stackoverflow.com/users/714", "pm_score": 3, "selected": true, "text": "-[NSManagedObjectContext refreshObject:mergeChanges:]" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67154", "https://Stackoverflow.com", "https://Stackoverflow.com/users/407138/" ]
67,174
<p>Does anybody know a "technique" to discover memory leaks caused by smart pointers? I am currently working on a large project written in <strong>C++</strong> that heavily uses smart pointers with reference counting. Obviously we have some memory leaks caused by smart pointers, that are still referenced somewhere in the code, so that their memory does not get free'd. It's very hard to find the line of code with the "needless" reference, that causes the corresponding object not to be free'd (although it's not of use any longer).</p> <p>I found some advice in the web, that proposed to collect call stacks of the increment/decrement operations of the reference counter. This gives me a good hint, which piece of code has caused the reference counter to get increased or decreased.</p> <p>But what I need is some kind of algorithm that groups the corresponding "increase/decrease call stacks" together. After removing these pairs of call stacks, I hopefully have (at least) one "increase call stack" left over, that shows me the piece of code with the "needless" reference, that caused the corresponding object not to be freed. Now it will be no big deal to fix the leak!</p> <p>But has anybody an idea for an "algorithm" that does the grouping?</p> <p>Development takes place under <strong>Windows XP</strong>.</p> <p>(I hope someone understood, what I tried to explain ...)</p> <p>EDIt: I am talking about leaks caused by circular references.</p>
[ { "answer_id": 67251, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 1, "selected": false, "text": "def allocation?(line)\n # determine if this line is a log line indicating allocation/deallocation\nend\n\ndef unique_stack(line)\n # return a string that is equal for pairs of allocation/deallocation\nend\n\nallocations = []\nfile = File.new \"the-log.log\"\nfile.each_line { |line|\n # custom function to determine if line is an alloc/dealloc\n if allocation? line\n # custom function to get unique stack trace where the return value\n # is the same for a alloc and dealloc\n allocations[allocations.length] = unique_stack line\n end\n}\n\nallocations.sort!\n\n# go through and remove pairs of allocations that equal,\n# ideally 1 will be remaining....\nindex = 0\n\nwhile index < allocations.size - 1\n if allocations[index] == allocations[index + 1]\n allocations.delete_at index\n else\n index = index + 1\n end\nend\n\nallocations.each { |line|\n puts line\n}\n" }, { "answer_id": 189328, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 2, "selected": false, "text": "set<CRefCounted*> this CRefCounted* virtual set<CRefCounted*> CRefCounted::get_children()" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2012356/" ]
67,209
<p>How do you customize the Copy/Paste behavior in Visual Studio 2008?</p> <p>For example I create a new <code>&lt;div id="MyDiv"&gt;&lt;/div&gt;</code> and then copy and paste it in the same file.</p> <p>VisualStudio pastes <code>&lt;div id="Div1"&gt;&lt;/div&gt;</code> instead of the original text I copied.</p> <p>It is even more frustrating when I'm trying to copy a group of related div's that I would like to copy/paste several times and only change one part of the id.</p> <p>Is there a setting I can tweak to change the copy/paste behavior?</p>
[ { "answer_id": 65760519, "author": "Geospatial", "author_id": 10039873, "author_profile": "https://Stackoverflow.com/users/10039873", "pm_score": 1, "selected": false, "text": "Tools > Text Editor > ASP.NET Web Forms Format HTML on paste" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3747/" ]
67,219
<p>When I use the PrintOut method to print a Worksheet object to a printer, the "Printing" dialog (showing filename, destination printer, pages printed and a Cancel button) is displayed even though I have set DisplayAlerts = False. The code below works in an Excel macro but the same thing happens if I use this code in a VB or VB.Net application (with the reference changes required to use the Excel object).</p> <pre><code>Public Sub TestPrint() Dim vSheet As Worksheet Application.ScreenUpdating = False Application.DisplayAlerts = False Set vSheet = ActiveSheet vSheet.PrintOut Preview:=False Application.DisplayAlerts = True Application.ScreenUpdating = True End Sub </code></pre> <p>EDIT: The answer below sheds more light on this (that it may be a Windows dialog and not an Excel dialog) but does not answer my question. Does anyone know how to prevent it from being displayed?</p> <p>EDIT: Thank you for your extra research, Kevin. It looks very much like this is what I need. Just not sure I want to blindly accept API code like that. Does anyone else have any knowledge about these API calls and that they're doing what the author purports?</p>
[ { "answer_id": 12731485, "author": "Raghbir Singh", "author_id": 1720679, "author_profile": "https://Stackoverflow.com/users/1720679", "pm_score": 2, "selected": false, "text": "sub test()\n\n activesheet.printout preview:= false\n\nend sub\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7209/" ]
67,244
<p>How do I determine using TSQL what roles are granted execute permissions on a specific stored procedure? Is there a system stored procedure or a system view I can use?</p>
[ { "answer_id": 67417, "author": "palehorse", "author_id": 312, "author_profile": "https://Stackoverflow.com/users/312", "pm_score": 0, "selected": false, "text": "SELECT\ngrantee_principal.name AS [Grantee],\nCASE grantee_principal.type WHEN 'R' THEN 3 WHEN 'A' THEN 4 ELSE 2 END - CASE 'database' WHEN 'database' THEN 0 ELSE 2 END AS [GranteeType]\nFROM\nsys.all_objects AS sp\nINNER JOIN sys.database_permissions AS prmssn ON prmssn.major_id=sp.object_id AND prmssn.minor_id=0 AND prmssn.class=1\nINNER JOIN sys.database_principals AS grantee_principal ON grantee_principal.principal_id = prmssn.grantee_principal_id\nWHERE\n(sp.type = N'P' OR sp.type = N'RF' OR sp.type='PC')and(sp.name=N'myProcedure' and SCHEMA_N\n" }, { "answer_id": 70078, "author": "Jonathan", "author_id": 6910, "author_profile": "https://Stackoverflow.com/users/6910", "pm_score": 1, "selected": false, "text": "SELECT convert(varchar(100),\n 'GRANT ' +\n CASE WHEN actadd & 32 = 32 THEN 'EXECUTE'\n ELSE\n CASE WHEN actadd & 1 = 1 THEN 'SELECT' + CASE WHEN actadd & (8|2|16) > 0 THEN ', ' ELSE '' END ELSE '' END +\n CASE WHEN actadd & 8 = 8 THEN 'INSERT' + CASE WHEN actadd & (2|16) > 0 THEN ', ' ELSE '' END ELSE '' END +\n CASE WHEN actadd & 2 = 2 THEN 'UPDATE' + CASE WHEN actadd & (16) > 0 THEN ', ' ELSE '' END ELSE '' END +\n CASE WHEN actadd & 16 = 16 THEN 'DELETE' ELSE '' END\n END + ' ON [' + o.name + '] TO [' + u.name + ']') AS '--Permissions--'\nFROM syspermissions p\nINNER JOIN sysusers u ON u.uid = p.grantee\nINNER JOIN sysobjects o ON p.id = o.id\nWHERE o.type <> 'S'\nAND o.name NOT LIKE 'dt%'\n--AND o.name = '<specific procedure/table>'\n--AND u.name = '<specific user>'\nORDER BY u.name, o.name \n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ]
67,273
<p>How do you iterate through every file/directory recursively in standard C++?</p>
[ { "answer_id": 67286, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 2, "selected": false, "text": "open() readdir()" }, { "answer_id": 67307, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 8, "selected": true, "text": "bool find_file( const path & dir_path, // in this directory,\n const std::string & file_name, // search for this name,\n path & path_found ) // placing path here if found\n{\n if ( !exists( dir_path ) ) return false;\n directory_iterator end_itr; // default construction yields past-the-end\n for ( directory_iterator itr( dir_path );\n itr != end_itr;\n ++itr )\n {\n if ( is_directory(itr->status()) )\n {\n if ( find_file( itr->path(), file_name, path_found ) ) return true;\n }\n else if ( itr->leaf() == file_name ) // see below\n {\n path_found = itr->path();\n return true;\n }\n }\n return false;\n}\n" }, { "answer_id": 67336, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 6, "selected": false, "text": "#include <windows.h>\n#include <string>\n#include <vector>\n#include <stack>\n#include <iostream>\n\nusing namespace std;\n\nbool ListFiles(wstring path, wstring mask, vector<wstring>& files) {\n HANDLE hFind = INVALID_HANDLE_VALUE;\n WIN32_FIND_DATA ffd;\n wstring spec;\n stack<wstring> directories;\n\n directories.push(path);\n files.clear();\n\n while (!directories.empty()) {\n path = directories.top();\n spec = path + L\"\\\\\" + mask;\n directories.pop();\n\n hFind = FindFirstFile(spec.c_str(), &ffd);\n if (hFind == INVALID_HANDLE_VALUE) {\n return false;\n } \n\n do {\n if (wcscmp(ffd.cFileName, L\".\") != 0 && \n wcscmp(ffd.cFileName, L\"..\") != 0) {\n if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {\n directories.push(path + L\"\\\\\" + ffd.cFileName);\n }\n else {\n files.push_back(path + L\"\\\\\" + ffd.cFileName);\n }\n }\n } while (FindNextFile(hFind, &ffd) != 0);\n\n if (GetLastError() != ERROR_NO_MORE_FILES) {\n FindClose(hFind);\n return false;\n }\n\n FindClose(hFind);\n hFind = INVALID_HANDLE_VALUE;\n }\n\n return true;\n}\n\nint main(int argc, char* argv[])\n{\n vector<wstring> files;\n\n if (ListFiles(L\"F:\\\\cvsrepos\", L\"*\", files)) {\n for (vector<wstring>::iterator it = files.begin(); \n it != files.end(); \n ++it) {\n wcout << it->c_str() << endl;\n }\n }\n return 0;\n}\n" }, { "answer_id": 1471012, "author": "tonymontana", "author_id": 396949, "author_profile": "https://Stackoverflow.com/users/396949", "pm_score": 4, "selected": false, "text": "wxDir Traverse() GetAllFiles() GetFirst() GetNext() QDir #include <qapplication.h>\n#include <qdir.h>\n#include <iostream>\n\nint main( int argc, char **argv )\n{\n QApplication a( argc, argv );\n QDir currentDir = QDir::current();\n\n currentDir.setFilter( QDir::Dirs );\n QStringList entries = currentDir.entryList();\n for( QStringList::ConstIterator entry=entries.begin(); entry!=entries.end(); ++entry) \n {\n std::cout << *entry << std::endl;\n }\n return 0;\n}\n" }, { "answer_id": 12240511, "author": "Alex", "author_id": 385489, "author_profile": "https://Stackoverflow.com/users/385489", "pm_score": 5, "selected": false, "text": "#include <stdio.h>\n#include <dirent.h>\n\nint listdir(const char *path) {\n struct dirent *entry;\n DIR *dp;\n\n dp = opendir(path);\n if (dp == NULL) {\n perror(\"opendir: Path does not exist or could not be read.\");\n return -1;\n }\n\n while ((entry = readdir(dp)))\n puts(entry->d_name);\n\n closedir(dp);\n return 0;\n}\n" }, { "answer_id": 19453043, "author": "Matthieu G", "author_id": 759349, "author_profile": "https://Stackoverflow.com/users/759349", "pm_score": 5, "selected": false, "text": "for #include <boost/filesystem.hpp>\n\nusing namespace boost::filesystem; \nstruct recursive_directory_range\n{\n typedef recursive_directory_iterator iterator;\n recursive_directory_range(path p) : p_(p) {}\n\n iterator begin() { return recursive_directory_iterator(p_); }\n iterator end() { return recursive_directory_iterator(); }\n\n path p_;\n};\n\nfor (auto it : recursive_directory_range(dir_path))\n{\n std::cout << it << std::endl;\n}\n" }, { "answer_id": 19963262, "author": "leif", "author_id": 679354, "author_profile": "https://Stackoverflow.com/users/679354", "pm_score": 3, "selected": false, "text": "ftw(3) nftw(3)" }, { "answer_id": 23475480, "author": "DikobrAz", "author_id": 1008902, "author_profile": "https://Stackoverflow.com/users/1008902", "pm_score": 3, "selected": false, "text": "#include \"boost/filesystem.hpp\"\n#include <iostream>\n\nusing namespace boost::filesystem;\n\nrecursive_directory_iterator end;\nfor (recursive_directory_iterator it(\"./\"); it != end; ++it) {\n std::cout << *it << std::endl; \n}\n" }, { "answer_id": 32889434, "author": "Adi Shavit", "author_id": 135862, "author_profile": "https://Stackoverflow.com/users/135862", "pm_score": 7, "selected": false, "text": "<filesystem> for #include <filesystem>\n\nusing recursive_directory_iterator = std::filesystem::recursive_directory_iterator;\n...\nfor (const auto& dirEntry : recursive_directory_iterator(myPath))\n std::cout << dirEntry << std::endl;\n std::filesystem <filesystem>" }, { "answer_id": 42866915, "author": "ndrewxie", "author_id": 7077165, "author_profile": "https://Stackoverflow.com/users/7077165", "pm_score": 3, "selected": false, "text": "#ifdef WINDOWS //define WINDOWS in your code to compile for windows\n#endif\n #ifdef POSIX //unix, linux, etc.\n#include <stdio.h>\n#include <dirent.h>\n\nint listdir(const char *path) {\n struct dirent *entry;\n DIR *dp;\n\n dp = opendir(path);\n if (dp == NULL) {\n perror(\"opendir: Path does not exist or could not be read.\");\n return -1;\n }\n\n while ((entry = readdir(dp)))\n puts(entry->d_name);\n\n closedir(dp);\n return 0;\n}\n#endif\n#ifdef WINDOWS\n#include <windows.h>\n#include <string>\n#include <vector>\n#include <stack>\n#include <iostream>\n\nusing namespace std;\n\nbool ListFiles(wstring path, wstring mask, vector<wstring>& files) {\n HANDLE hFind = INVALID_HANDLE_VALUE;\n WIN32_FIND_DATA ffd;\n wstring spec;\n stack<wstring> directories;\n\n directories.push(path);\n files.clear();\n\n while (!directories.empty()) {\n path = directories.top();\n spec = path + L\"\\\\\" + mask;\n directories.pop();\n\n hFind = FindFirstFile(spec.c_str(), &ffd);\n if (hFind == INVALID_HANDLE_VALUE) {\n return false;\n } \n\n do {\n if (wcscmp(ffd.cFileName, L\".\") != 0 && \n wcscmp(ffd.cFileName, L\"..\") != 0) {\n if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {\n directories.push(path + L\"\\\\\" + ffd.cFileName);\n }\n else {\n files.push_back(path + L\"\\\\\" + ffd.cFileName);\n }\n }\n } while (FindNextFile(hFind, &ffd) != 0);\n\n if (GetLastError() != ERROR_NO_MORE_FILES) {\n FindClose(hFind);\n return false;\n }\n\n FindClose(hFind);\n hFind = INVALID_HANDLE_VALUE;\n }\n\n return true;\n}\n#endif\n//so on and so forth.\n" }, { "answer_id": 56376599, "author": "abhiarora", "author_id": 5735010, "author_profile": "https://Stackoverflow.com/users/5735010", "pm_score": 3, "selected": false, "text": "C++ Filesystem library boost.filesystem LegacyInputIterator directory_entry is_regular_file is_directory is_socket is_symlink path() file extension filename root name Ubuntu #include <iostream>\n#include <string>\n#include <filesystem>\n\nvoid listFiles(std::string path)\n{\n for (auto& dirEntry: std::filesystem::recursive_directory_iterator(path)) {\n if (!dirEntry.is_regular_file()) {\n std::cout << \"Directory: \" << dirEntry.path() << std::endl;\n continue;\n }\n std::filesystem::path file = dirEntry.path();\n std::cout << \"Filename: \" << file.filename() << \" extension: \" << file.extension() << std::endl;\n\n }\n}\n\nint main()\n{\n listFiles(\"./\");\n return 0;\n}\n" }, { "answer_id": 62057783, "author": "pooya13", "author_id": 3847255, "author_profile": "https://Stackoverflow.com/users/3847255", "pm_score": 4, "selected": false, "text": "std::filesystem::recursive_directory_iterator is_symlink size_t directory_size(const std::filesystem::path& directory)\n{\n size_t size{ 0 };\n for (const auto& entry : std::filesystem::recursive_directory_iterator(directory))\n {\n if (entry.is_regular_file() && !entry.is_symlink())\n {\n size += entry.file_size();\n }\n }\n return size;\n}\n" }, { "answer_id": 63006457, "author": "Milind Deore", "author_id": 3994228, "author_profile": "https://Stackoverflow.com/users/3994228", "pm_score": 0, "selected": false, "text": "ftw fts . .. .bashrc #include <ftw.h>\n#include <stdio.h>\n#include <sys/stat.h>\n#include <string.h>\n\n \nint list(const char *name, const struct stat *status, int type)\n{\n if (type == FTW_NS)\n {\n return 0;\n }\n\n if (type == FTW_F)\n {\n printf(\"0%3o\\t%s\\n\", status->st_mode&0777, name);\n }\n\n if (type == FTW_D && strcmp(\".\", name) != 0)\n {\n printf(\"0%3o\\t%s/\\n\", status->st_mode&0777, name);\n }\n return 0;\n}\n\nint main(int argc, char *argv[])\n{\n if(argc == 1)\n {\n ftw(\".\", list, 1);\n }\n else\n {\n ftw(argv[1], list, 1);\n }\n\n return 0;\n}\n 0755 ./Shivaji/\n0644 ./Shivaji/20200516_204454.png\n0644 ./Shivaji/20200527_160408.png\n0644 ./Shivaji/20200527_160352.png\n0644 ./Shivaji/20200520_174754.png\n0644 ./Shivaji/20200520_180103.png\n0755 ./Saif/\n0644 ./Saif/Snapchat-1751229005.jpg\n0644 ./Saif/Snapchat-1356123194.jpg\n0644 ./Saif/Snapchat-613911286.jpg\n0644 ./Saif/Snapchat-107742096.jpg\n0755 ./Milind/\n0644 ./Milind/IMG_1828.JPG\n0644 ./Milind/IMG_1839.JPG\n0644 ./Milind/IMG_1825.JPG\n0644 ./Milind/IMG_1831.JPG\n0644 ./Milind/IMG_1840.JPG\n *.jpg, *.jpeg, *.png fnmatch #include <ftw.h>\n #include <stdio.h>\n #include <sys/stat.h>\n #include <iostream>\n #include <fnmatch.h>\n\n static const char *filters[] = {\n \"*.jpg\", \"*.jpeg\", \"*.png\"\n };\n\n int list(const char *name, const struct stat *status, int type)\n {\n if (type == FTW_NS)\n {\n return 0;\n }\n\n if (type == FTW_F)\n {\n int i;\n for (i = 0; i < sizeof(filters) / sizeof(filters[0]); i++) {\n /* if the filename matches the filter, */\n if (fnmatch(filters[i], name, FNM_CASEFOLD) == 0) {\n printf(\"0%3o\\t%s\\n\", status->st_mode&0777, name);\n break;\n }\n }\n }\n\n if (type == FTW_D && strcmp(\".\", name) != 0)\n {\n //printf(\"0%3o\\t%s/\\n\", status->st_mode&0777, name);\n }\n return 0;\n }\n\n int main(int argc, char *argv[])\n {\n if(argc == 1)\n {\n ftw(\".\", list, 1);\n }\n else\n {\n ftw(argv[1], list, 1);\n }\n\n return 0;\n }\n" }, { "answer_id": 64443732, "author": "Bensuperpc", "author_id": 10152334, "author_profile": "https://Stackoverflow.com/users/10152334", "pm_score": 2, "selected": false, "text": "#include <filesystem>\n#include <iostream>\n#include <vector>\nnamespace fs = std::filesystem;\n\nint main()\n{\n std::ios_base::sync_with_stdio(false);\n for (const auto &entry : fs::recursive_directory_iterator(\".\")) {\n if (entry.path().extension() == \".png\") {\n std::cout << entry.path().string() << std::endl;\n \n }\n }\n return 0;\n}\n" }, { "answer_id": 65090772, "author": "Hu Xixi", "author_id": 7121726, "author_profile": "https://Stackoverflow.com/users/7121726", "pm_score": 0, "selected": false, "text": "experimental/filesystem #include <io.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <windows.h>\nvoid getFiles_w(string path, vector<string>& files) {\n intptr_t hFile = 0; \n struct _finddata_t fileinfo; \n string p; \n if ((hFile = _findfirst(p.assign(path).append(\"\\\\*\").c_str(), &fileinfo)) != -1) {\n do {\n if ((fileinfo.attrib & _A_SUBDIR)) {\n if (strcmp(fileinfo.name, \".\") != 0 && strcmp(fileinfo.name, \"..\") != 0)\n getFiles(p.assign(path).append(\"/\").append(fileinfo.name), files);\n }\n else {\n files.push_back(p.assign(path).append(\"/\").append(fileinfo.name));\n }\n } while (_findnext(hFile, &fileinfo) == 0);\n }\n}\n #include <experimental/filesystem>\nbool getFiles(std::experimental::filesystem::path path, vector<string>& filenames) {\n namespace stdfs = std::experimental::filesystem;\n // http://en.cppreference.com/w/cpp/experimental/fs/directory_iterator\n const stdfs::directory_iterator end{} ;\n \n for (stdfs::directory_iterator iter{path}; iter != end ; ++iter) {\n // http://en.cppreference.com/w/cpp/experimental/fs/is_regular_file \n if (!stdfs::is_regular_file(*iter)) { // comment out if all names (names of directories tc.) are required \n if (getFiles(iter->path(), filenames)) \n return true;\n }\n else {\n filenames.push_back(iter->path().string()) ;\n cout << iter->path().string() << endl; \n }\n }\n return false;\n}\n -lstdc++fs g++" }, { "answer_id": 66687906, "author": "Mou", "author_id": 4292371, "author_profile": "https://Stackoverflow.com/users/4292371", "pm_score": 0, "selected": false, "text": "bool Parser::queryDIR(string dir_name) {\n vector<string> sameLayerFiles;\n bool ret = false;\n string dir = \"\";\n //employee wide char\n dir = dir_name + \"\\\\*.*\";;\n //employee WIN File API\n WIN32_FIND_DATA fd;\n WIN32_FIND_DATA fd_dir;\n HANDLE hFind = ::FindFirstFile(getWC(dir.c_str()), &fd);\n HANDLE hFind_dir = ::FindFirstFile(getWC(dir.c_str()), &fd_dir);\n string str_subdir;\n string str_tmp;\n //recursive call for diving into sub-directories\n do {\n if ((fd_dir.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ) {\n //ignore trival file node\n while(true) {\n FindNextFile(hFind_dir, &fd_dir);\n str_tmp = wc2str(fd_dir.cFileName);\n if (str_tmp.compare(\".\") && str_tmp.compare(\"..\")){\n break;\n }\n }\n if ((fd_dir.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ) {\n str_subdir = wc2str(fd_dir.cFileName);\n ret = queryDIR(dir_name + \"\\\\\" + str_subdir);\n }\n }\n } while(::FindNextFile(hFind_dir, &fd_dir));\n\n //iterate same layer files\n do { \n if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {\n str_tmp = wc2str(fd.cFileName);\n string fname = dir_name + \"\\\\\" + str_tmp;\n sameLayerFiles.push_back(fname);\n }\n } while(::FindNextFile(hFind, &fd)); \n\n for (std::vector<string>::iterator it=sameLayerFiles.begin(); it!=sameLayerFiles.end(); it++) {\n std::cout << \"iterated file:\" << *it << \"...\" << std::endl;\n //Doing something with every file here\n }\n return true; \n}\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10184/" ]
67,275
<p>I am trying to read a single file from a <code>java.util.zip.ZipInputStream</code>, and copy it into a <code>java.io.ByteArrayOutputStream</code> (so that I can then create a <code>java.io.ByteArrayInputStream</code> and hand that to a 3rd party library that will end up closing the stream, and I don't want my <code>ZipInputStream</code> getting closed).</p> <p>I'm probably missing something basic here, but I never enter the while loop here:</p> <pre><code>ByteArrayOutputStream streamBuilder = new ByteArrayOutputStream(); int bytesRead; byte[] tempBuffer = new byte[8192*2]; try { while ((bytesRead = zipStream.read(tempBuffer)) != -1) { streamBuilder.write(tempBuffer, 0, bytesRead); } } catch (IOException e) { // ... } </code></pre> <p>What am I missing that will allow me to copy the stream?</p> <p><strong>Edit:</strong></p> <p>I should have mentioned earlier that this <code>ZipInputStream</code> is not coming from a file, so I don't think I can use a <code>ZipFile</code>. It is coming from a file uploaded through a servlet.</p> <p>Also, I have already called <code>getNextEntry()</code> on the <code>ZipInputStream</code> before getting to this snippet of code. If I don't try copying the file into another <code>InputStream</code> (via the <code>OutputStream</code> mentioned above), and just pass the <code>ZipInputStream</code> to my 3rd party library, the library closes the stream, and I can't do anything more, like dealing with the remaining files in the stream.</p>
[ { "answer_id": 67377, "author": "Boris Bokowski", "author_id": 10114, "author_profile": "https://Stackoverflow.com/users/10114", "pm_score": 0, "selected": false, "text": " zipStream = zipFile.getInputStream(zipEntry)\n" }, { "answer_id": 67403, "author": "ScArcher2", "author_id": 1310, "author_profile": "https://Stackoverflow.com/users/1310", "pm_score": 2, "selected": false, "text": "IOUtils.copy(zipStream, byteArrayOutputStream);\n" }, { "answer_id": 67719, "author": "Benedikt Waldvogel", "author_id": 4308, "author_profile": "https://Stackoverflow.com/users/4308", "pm_score": 3, "selected": false, "text": "FileInputStream ZipInputStream in = new ZipInputStream(new FileInputStream(...)); ByteArrayOutputStream out = new ByteArrayOutputStream();\ntry (ZipFile zipFile = new ZipFile(\"foo.zip\")) {\n ZipEntry zipEntry = zipFile.getEntry(\"fileInTheZip.txt\");\n\n try (InputStream in = zipFile.getInputStream(zipEntry)) {\n IOUtils.copy(in, out);\n }\n}\n" }, { "answer_id": 67765, "author": "helios", "author_id": 9686, "author_profile": "https://Stackoverflow.com/users/9686", "pm_score": 0, "selected": false, "text": " zipStream = zipFile.getInputStream(zipEntry)\n" }, { "answer_id": 69177, "author": "jt.", "author_id": 4362, "author_profile": "https://Stackoverflow.com/users/4362", "pm_score": 2, "selected": false, "text": "thirdPartyLib.handleZipData(new CloseIgnoringInputStream(zipStream));\n\n\nclass CloseIgnoringInputStream extends InputStream\n{\n private ZipInputStream stream;\n\n public CloseIgnoringInputStream(ZipInputStream inStream)\n {\n stream = inStream;\n }\n\n public int read() throws IOException {\n return stream.read();\n }\n\n public void close()\n {\n //ignore\n }\n\n public void reallyClose() throws IOException\n {\n stream.close();\n }\n}\n" }, { "answer_id": 69489, "author": "Kevin Day", "author_id": 10973, "author_profile": "https://Stackoverflow.com/users/10973", "pm_score": 4, "selected": true, "text": "zipStream.read(tempBuffer)\n" }, { "answer_id": 2093184, "author": "Dmytro ", "author_id": 253962, "author_profile": "https://Stackoverflow.com/users/253962", "pm_score": 0, "selected": false, "text": "private static byte[] getZipArchiveContent(File zipName) throws WorkflowServiceBusinessException {\n\n BufferedInputStream buffer = null;\n FileInputStream fileStream = null;\n ByteArrayOutputStream byteOut = null;\n byte data[] = new byte[BUFFER];\n\n try {\n try {\n fileStream = new FileInputStream(zipName);\n buffer = new BufferedInputStream(fileStream);\n byteOut = new ByteArrayOutputStream();\n\n int count;\n while((count = buffer.read(data, 0, BUFFER)) != -1) {\n byteOut.write(data, 0, count);\n }\n } catch(Exception e) {\n throw new WorkflowServiceBusinessException(e.getMessage(), e);\n } finally {\n if(null != fileStream) {\n fileStream.close();\n }\n if(null != buffer) {\n buffer.close();\n }\n if(null != byteOut) {\n byteOut.close();\n }\n }\n } catch(Exception e) {\n throw new WorkflowServiceBusinessException(e.getMessage(), e);\n }\n return byteOut.toByteArray();\n\n }\n" }, { "answer_id": 9999404, "author": "Juan Ignacio", "author_id": 1311188, "author_profile": "https://Stackoverflow.com/users/1311188", "pm_score": 2, "selected": false, "text": " ByteArrayOutputStream streamBuilder = new ByteArrayOutputStream();\n int bytesRead;\n byte[] tempBuffer = new byte[8192*2];\n ZipEntry entry = (ZipEntry) zipStream.getNextEntry();\n try {\n while ( (bytesRead = zipStream.read(tempBuffer)) != -1 ){\n streamBuilder.write(tempBuffer, 0, bytesRead);\n }\n } catch (IOException e) {\n ...\n }\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4257/" ]
67,299
<p>I am working to integrate unit testing into the development process on the team I work on and there are some sceptics. What are some good ways to convince the sceptical developers on the team of the value of Unit Testing? In my specific case we would be adding Unit Tests as we add functionality or fixed bugs. Unfortunately our code base does not lend itself to easy testing.</p>
[ { "answer_id": 107137, "author": "Andy Lester", "author_id": 8454, "author_profile": "https://Stackoverflow.com/users/8454", "pm_score": 1, "selected": false, "text": "use_ok( 'Foo' );\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67299", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9431/" ]
67,300
<p>If you use the standard tab control in .NET for your tab pages and you try to change the look and feel a little bit then you are able to change the back color of the tab pages but not for the tab control. The property is available, you could set it but it has no effect. If you change the back color of the pages and not of the tab control it looks... uhm quite ugly.</p> <p>I know Microsoft doesn't want it to be set. <a href="http://msdn.microsoft.com/en/library/w4sc610z(VS.80).aspx" rel="nofollow noreferrer">MSDN</a>: '<i>This property supports the .NET Framework infrastructure and is not intended to be used directly from your code. This member is not meaningful for this control.</i>' A control property just for color which supports the .NET infrastructure? ...hard to believe.</p> <p>I hoped over the years Microsoft would change it but they did not. I created my own TabControl class which overrides the paint method to fix this. But is this really the best solution?</p> <p>What is the reason for not supporting BackColor for this control? What is your solution to fix this? Is there a better solution than overriding the paint method?</p>
[ { "answer_id": 268271, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "...\n\nDim r As Rectangle = tabControl1.GetTabRect(tabControl1.TabPages.Count-1)\nDim rf As RectangleF = New RectangleF(r.X + r.Width, r.Y - 5, tabControl1.Width - (r.X + r.Width), r.Height + 5)\nDim b As Brush = New SolidBrush(Color.White)\ne.Graphics.FillRectangle(b, rf)\n\n...\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9470/" ]
67,354
<p>I have an iframe. The content is wider than the width I am setting so the iframe gets a horizontal scroll bar. I can't increase the width of the iframe so I want to just remove the scroll bar. I tried setting the scroll property to "no" but that kills both scroll bars and I want the vertical one. I tried setting overflow-x to "hidden" and that killed the horizontal scroll bar in ff but not in IE. sad for me.</p>
[ { "answer_id": 67568, "author": "Rich Adams", "author_id": 10018, "author_profile": "https://Stackoverflow.com/users/10018", "pm_score": 3, "selected": false, "text": "<html>\n <head>\n <title>iframe test</title>\n\n <style> \n #aTest { \n width: 120px;\n height: 50px;\n padding: 0;\n border: inset 1px #000;\n overflow: auto;\n }\n\n #aTest iframe {\n width: 100px;\n height: 1000px;\n border: none;\n }\n </style>\n </head>\n <body>\n <div id=\"aTest\">\n <iframe src=\"whatever.html\" scrolling=\"no\" frameborder=\"0\"></iframe>\n </div>\n </body>\n</html>\n" }, { "answer_id": 67576, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 5, "selected": false, "text": "<iframe> overflow-x: hidden <html>" }, { "answer_id": 68347, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 0, "selected": false, "text": "<iframe style=\"overflow:hidden;\" src=\"about:blank\"/>\n <iframe frameBorder=\"0\" style=\"overflow:hidden;\" src=\"about:blank\"/>\n" }, { "answer_id": 472081, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": true, "text": "scrolling=\"yes\" horizontalscrolling=\"no\" verticalscrolling=\"yes\"\n" }, { "answer_id": 2165789, "author": "Lou", "author_id": 262211, "author_profile": "https://Stackoverflow.com/users/262211", "pm_score": 0, "selected": false, "text": " <!-- This DIV is a special hack to hide the horizontal scrollbar in IE iframes -->\n<!--[if IE]>\n<div id=\"ieIframeHorScrollbarHider\" style=\"position:absolute; width: 768px; height: 20px; top: 850px; left: 376px; background-color: black; display: none;\">\n</div>\n<![endif]-->\n<script type=\"text/javascript\">\n if (document.getElementById(\"idOfIframe\") != null && document.getElementById(\"ieIframeHorScrollbarHider\") != null)\n {\n document.getElementById(\"ieIframeHorScrollbarHider\").style.display = \"block\";\n }\n</script>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5234/" ]
67,370
<p>I'm programming WCF using the ChannelFactory which expects a type in order to call the CreateChannel method. For example: </p> <pre><code>IProxy proxy = ChannelFactory&lt;IProxy&gt;.CreateChannel(...); </code></pre> <p>In my case I'm doing routing so I don't know what type my channel factory will be using. I can parse a message header to determine the type but I hit a brick wall there because even if I have an instance of Type I can't pass that where ChannelFactory expects a generic type. </p> <p>Another way of restating this problem in very simple terms would be that I'm attempting to do something like this:</p> <pre><code>string listtype = Console.ReadLine(); // say "System.Int32" Type t = Type.GetType( listtype); List&lt;t&gt; myIntegers = new List&lt;&gt;(); // does not compile, expects a "type" List&lt;typeof(t)&gt; myIntegers = new List&lt;typeof(t)&gt;(); // interesting - type must resolve at compile time? </code></pre> <p>Is there an approach to this I can leverage within C#?</p>
[ { "answer_id": 67530, "author": "IDisposable", "author_id": 2076, "author_profile": "https://Stackoverflow.com/users/2076", "pm_score": 6, "selected": true, "text": "string elementTypeName = Console.ReadLine();\nType elementType = Type.GetType(elementTypeName);\nType[] types = new Type[] { elementType };\n\nType listType = typeof(List<>);\nType genericType = listType.MakeGenericType(types);\nIProxy proxy = (IProxy)Activator.CreateInstance(genericType);\n" }, { "answer_id": 67619, "author": "tomasr", "author_id": 10292, "author_profile": "https://Stackoverflow.com/users/10292", "pm_score": 2, "selected": false, "text": "ChannelFactory<IOutputChannel> factory = new ChannelFactory<IOutputChannel>(binding, endpoint);\nIOutputChannel channel = factory.CreateChannel();\n...\nchannel.SendMessage(myRawMessage);\n" }, { "answer_id": 67782, "author": "Bill", "author_id": 9887, "author_profile": "https://Stackoverflow.com/users/9887", "pm_score": 3, "selected": false, "text": "string typeName = ...;\nType proxyType = Type.GetType(typeName);\n\nType type = typeof (ChannelFactory<>).MakeGenericType(proxyType);\n\nobject target = Activator.CreateInstance(type);\n\nMethodInfo methodInfo = type.GetMethod(\"CreateChannel\", new Type[] {});\n\nreturn methodInfo.Invoke(target, new object[0]);\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/64/" ]
67,410
<p><code>GNU sed version 4.1.5</code> seems to fail with International chars. Here is my input file:</p> <pre><code>Gras Och Stenar Trad - From Moja to Minneapolis DVD [G2007DVD] 7812 | X &lt;br&gt; Gras Och Stenar Trad - From Möja to Minneapolis DVD [G2007DVD] 7812 | Y </code></pre> <p>(Note the umlaut in the second line.)</p> <p>And when I do</p> <pre><code>sed 's/.*| //' &lt; in </code></pre> <p>I would expect to see only the <code>X</code> and <code>Y</code>, as I've asked to remove ALL chars up to the <code>'|'</code> and space beyond it. Instead, I get:</p> <pre><code>X&lt;br&gt; Gras Och Stenar Trad - From M? Y </code></pre> <p>I know I can use tr to remove the International chars. first, but is there a way to just use sed?</p>
[ { "answer_id": 67470, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "sed perl perl -pe 's/.*\\| //' x\n" }, { "answer_id": 67575, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": 6, "selected": true, "text": "in $ LANG=de_DE.UTF-8 sed 's/.*| //' < in\nX\nY\n$ LANG=de_DE.iso88591 sed 's/.*| //' < in\nX \nY\n in $ LANG=de_DE.UTF-8 sed 's/.*| //' < in\nX\nGras Och Stenar Trad - From MöY\n$ LANG=de_DE.iso88591 sed 's/.*| //' < in\nX \nY\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10251/" ]
67,418
<p>I have a "watcher" module that is currently using global hierarchies inside it. I need to instantiate a second instance of this with a second global hierarchy.</p> <p>Currently:</p> <pre><code>module watcher; wire sig = `HIER.sig; wire bar = `HIER.foo.bar; ... endmodule watcher w; // instantiation </code></pre> <p>Desired:</p> <pre><code>module watcher(input base_hier); wire sig = base_hier.sig; wire bar = base_hier.foo.bar; ... endmodule watcher w1(`HIER1); // instantiation watcher w2(`HIER2); // second instantiation, except with a different hierarchy </code></pre> <p>My best idea is to use vpp (the Verilog preprocessor) to brute-force generate two virtually-identical modules (one with each hierarchy), but is there a more elegant way?</p>
[ { "answer_id": 68376, "author": "DMC", "author_id": 3148, "author_profile": "https://Stackoverflow.com/users/3148", "pm_score": 3, "selected": false, "text": "module watcher(sig, bar);\n input sig;\n input bar;\n...\nendmodule\n\nwatcher w1(`HIER1.sig, `HIER1.foo.bar); // instantiation\nwatcher w2(`HIER2.sig, `HIER2.foo.bar); // second instantiation, except with a different hierarchy\n `define WATCHER_INST(NAME, HIER) watcher NAME(HIER.sig, HIER.foo.sig)\n\n`WATCHER_INST(w1, `HIER1);\n`WATCHER_INST(w2, `HIER2);\n" }, { "answer_id": 899614, "author": "d3jones", "author_id": 111215, "author_profile": "https://Stackoverflow.com/users/111215", "pm_score": 2, "selected": false, "text": "bind bind top.my.hier my_module instance_name(.*);\nbind top.my_other.hier my_module instance_name(.*);\n bind remote_module my_module instance_name(.*);\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8598/" ]
67,421
<p>I've built one, but I'm convinced it's wrong.</p> <p>I had a table for customer details, and another table with the each date staying (i.e. a week's holiday would have seven records).</p> <p>Is there a better way?</p> <p>I code in PHP with MySQL</p>
[ { "answer_id": 67472, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 0, "selected": false, "text": "stay.check_in_time_scheduled\nstay.check_in_time_actual\nstay.check_out_time_scheduled\nstay.check_out_time_actual\n" }, { "answer_id": 71183, "author": "J.D. Fitz.Gerald", "author_id": 11542, "author_profile": "https://Stackoverflow.com/users/11542", "pm_score": 2, "selected": false, "text": "Bookings (id, main-guest-id, arrivaltime, departime,...)\n\nBookingGuests (id, guest-id)\n\nBookingGuestNights (date, room, rate)\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
67,426
<p>I'm fairly new to the STL, so I was wondering whether there are any dynamically sortable containers? At the moment my current thinking is to use a vector in conjunction with the various sort algorithms, but I'm not sure whether there's a more appropriate selection given the (presumably) linear complexity of inserting entries into a sorted vector.</p> <p>To clarify "dynamically", I am looking for a container that I can modify the sorting order at runtime - e.g. sort it in an ascending order, then later re-sort in a descending order.</p>
[ { "answer_id": 67437, "author": "Torlack", "author_id": 5243, "author_profile": "https://Stackoverflow.com/users/5243", "pm_score": 2, "selected": false, "text": "std::set" }, { "answer_id": 67460, "author": "Doug T.", "author_id": 8123, "author_profile": "https://Stackoverflow.com/users/8123", "pm_score": 4, "selected": false, "text": "std::map<keyType, valueType>\n std::set<valueType>\n std::multiset<valueType>\n" }, { "answer_id": 67683, "author": "hazzen", "author_id": 5066, "author_profile": "https://Stackoverflow.com/users/5066", "pm_score": 2, "selected": false, "text": "stl set/multiset vector sort vector set/multiset rbegin() rend() begin() end() vector set/multiset" }, { "answer_id": 67991, "author": "JProgrammer", "author_id": 1675, "author_profile": "https://Stackoverflow.com/users/1675", "pm_score": 1, "selected": false, "text": "set multiset vector lower_bound set multiset lower_bound" }, { "answer_id": 68162, "author": "Max Lybbert", "author_id": 10593, "author_profile": "https://Stackoverflow.com/users/10593", "pm_score": 2, "selected": false, "text": "std::sort std::deque std::vector" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67426", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10247/" ]
67,454
<p>How to serve users a dynamically generated ZIP archive in Django?</p> <p>I'm making a site, where users can choose any combination of available books and download them as ZIP archive. I'm worried that generating such archives for each request would slow my server down to a crawl. I have also heard that Django doesn't currently have a good solution for serving dynamically generated files.</p>
[ { "answer_id": 72180, "author": "zgoda", "author_id": 12138, "author_profile": "https://Stackoverflow.com/users/12138", "pm_score": 7, "selected": true, "text": "HttpResponse application/x-zip-compressed application/octet-stream content-disposition" }, { "answer_id": 12951461, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 6, "selected": false, "text": "import os\nimport zipfile\nimport StringIO\n\nfrom django.http import HttpResponse\n\n\ndef getfiles(request):\n # Files (local path) to put in the .zip\n # FIXME: Change this (get paths from DB etc)\n filenames = [\"/tmp/file1.txt\", \"/tmp/file2.txt\"]\n\n # Folder name in ZIP archive which contains the above files\n # E.g [thearchive.zip]/somefiles/file2.txt\n # FIXME: Set this to something better\n zip_subdir = \"somefiles\"\n zip_filename = \"%s.zip\" % zip_subdir\n\n # Open StringIO to grab in-memory ZIP contents\n s = StringIO.StringIO()\n\n # The zip compressor\n zf = zipfile.ZipFile(s, \"w\")\n\n for fpath in filenames:\n # Calculate path for file in zip\n fdir, fname = os.path.split(fpath)\n zip_path = os.path.join(zip_subdir, fname)\n\n # Add file, at correct path\n zf.write(fpath, zip_path)\n\n # Must close zip for all contents to be written\n zf.close()\n\n # Grab ZIP file from in-memory, make response with correct MIME-type\n resp = HttpResponse(s.getvalue(), mimetype = \"application/x-zip-compressed\")\n # ..and correct content-disposition\n resp['Content-Disposition'] = 'attachment; filename=%s' % zip_filename\n\n return resp\n" }, { "answer_id": 26658291, "author": "Thibault J", "author_id": 665797, "author_profile": "https://Stackoverflow.com/users/665797", "pm_score": 3, "selected": false, "text": "pip install django-zipview from zipview.views import BaseZipView\n\nfrom reviews import Review\n\n\nclass CommentsArchiveView(BaseZipView):\n \"\"\"Download at once all comments for a review.\"\"\"\n\n def get_files(self):\n document_key = self.kwargs.get('document_key')\n reviews = Review.objects \\\n .filter(document__document_key=document_key) \\\n .exclude(comments__isnull=True)\n\n return [review.comments.file for review in reviews if review.comments.name]\n" }, { "answer_id": 40076866, "author": "pitaside", "author_id": 4380481, "author_profile": "https://Stackoverflow.com/users/4380481", "pm_score": 3, "selected": false, "text": "import io\n\ndef my_downloadable_zip(request):\n zip_io = io.BytesIO()\n with zipfile.ZipFile(zip_io, mode='w', compression=zipfile.ZIP_DEFLATED) as backup_zip:\n backup_zip.write('file_name_loc_to_zip') # u can also make use of list of filename location\n # and do some iteration over it\n response = HttpResponse(zip_io.getvalue(), content_type='application/x-zip-compressed')\n response['Content-Disposition'] = 'attachment; filename=%s' % 'your_zipfilename' + \".zip\"\n response['Content-Length'] = zip_io.tell()\n return response\n" }, { "answer_id": 49220016, "author": "Antoine Pinsard", "author_id": 1529346, "author_profile": "https://Stackoverflow.com/users/1529346", "pm_score": 5, "selected": false, "text": "StringIO BytesIO HttpResponse response = HttpResponse(content_type='application/zip')\nzip_file = zipfile.ZipFile(response, 'w')\nfor filename in filenames:\n zip_file.write(filename)\nresponse['Content-Disposition'] = 'attachment; filename={}'.format(zipfile_name)\nreturn response\n zip_file.close() response" }, { "answer_id": 51655455, "author": "Pasha M", "author_id": 8992267, "author_profile": "https://Stackoverflow.com/users/8992267", "pm_score": 3, "selected": false, "text": "import zipfile\nimport os\nfrom io import BytesIO\n\ndef download_zip_file(request):\n filelist = [\"path/to/file-11.txt\", \"path/to/file-22.txt\"]\n\n byte_data = BytesIO()\n zip_file = zipfile.ZipFile(byte_data, \"w\")\n\n for file in filelist:\n filename = os.path.basename(os.path.normpath(file))\n zip_file.write(file, filename)\n zip_file.close()\n\n response = HttpResponse(byte_data.getvalue(), content_type='application/zip')\n response['Content-Disposition'] = 'attachment; filename=files.zip'\n\n # Print list files in zip_file\n zip_file.printdir()\n\n return response\n" }, { "answer_id": 58849165, "author": "yspreen", "author_id": 2585092, "author_profile": "https://Stackoverflow.com/users/2585092", "pm_score": 0, "selected": false, "text": "def download_view(request, name=\"\"):\n from django_zip_stream.responses import FolderZipResponse\n path = settings.STATIC_ROOT\n path = os.path.join(path, name)\n\n return FolderZipResponse(path)\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9812/" ]
67,457
<p>How can I show a web page in a transparent window and have the white part of the web page also transparent.</p>
[ { "answer_id": 72180, "author": "zgoda", "author_id": 12138, "author_profile": "https://Stackoverflow.com/users/12138", "pm_score": 7, "selected": true, "text": "HttpResponse application/x-zip-compressed application/octet-stream content-disposition" }, { "answer_id": 12951461, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 6, "selected": false, "text": "import os\nimport zipfile\nimport StringIO\n\nfrom django.http import HttpResponse\n\n\ndef getfiles(request):\n # Files (local path) to put in the .zip\n # FIXME: Change this (get paths from DB etc)\n filenames = [\"/tmp/file1.txt\", \"/tmp/file2.txt\"]\n\n # Folder name in ZIP archive which contains the above files\n # E.g [thearchive.zip]/somefiles/file2.txt\n # FIXME: Set this to something better\n zip_subdir = \"somefiles\"\n zip_filename = \"%s.zip\" % zip_subdir\n\n # Open StringIO to grab in-memory ZIP contents\n s = StringIO.StringIO()\n\n # The zip compressor\n zf = zipfile.ZipFile(s, \"w\")\n\n for fpath in filenames:\n # Calculate path for file in zip\n fdir, fname = os.path.split(fpath)\n zip_path = os.path.join(zip_subdir, fname)\n\n # Add file, at correct path\n zf.write(fpath, zip_path)\n\n # Must close zip for all contents to be written\n zf.close()\n\n # Grab ZIP file from in-memory, make response with correct MIME-type\n resp = HttpResponse(s.getvalue(), mimetype = \"application/x-zip-compressed\")\n # ..and correct content-disposition\n resp['Content-Disposition'] = 'attachment; filename=%s' % zip_filename\n\n return resp\n" }, { "answer_id": 26658291, "author": "Thibault J", "author_id": 665797, "author_profile": "https://Stackoverflow.com/users/665797", "pm_score": 3, "selected": false, "text": "pip install django-zipview from zipview.views import BaseZipView\n\nfrom reviews import Review\n\n\nclass CommentsArchiveView(BaseZipView):\n \"\"\"Download at once all comments for a review.\"\"\"\n\n def get_files(self):\n document_key = self.kwargs.get('document_key')\n reviews = Review.objects \\\n .filter(document__document_key=document_key) \\\n .exclude(comments__isnull=True)\n\n return [review.comments.file for review in reviews if review.comments.name]\n" }, { "answer_id": 40076866, "author": "pitaside", "author_id": 4380481, "author_profile": "https://Stackoverflow.com/users/4380481", "pm_score": 3, "selected": false, "text": "import io\n\ndef my_downloadable_zip(request):\n zip_io = io.BytesIO()\n with zipfile.ZipFile(zip_io, mode='w', compression=zipfile.ZIP_DEFLATED) as backup_zip:\n backup_zip.write('file_name_loc_to_zip') # u can also make use of list of filename location\n # and do some iteration over it\n response = HttpResponse(zip_io.getvalue(), content_type='application/x-zip-compressed')\n response['Content-Disposition'] = 'attachment; filename=%s' % 'your_zipfilename' + \".zip\"\n response['Content-Length'] = zip_io.tell()\n return response\n" }, { "answer_id": 49220016, "author": "Antoine Pinsard", "author_id": 1529346, "author_profile": "https://Stackoverflow.com/users/1529346", "pm_score": 5, "selected": false, "text": "StringIO BytesIO HttpResponse response = HttpResponse(content_type='application/zip')\nzip_file = zipfile.ZipFile(response, 'w')\nfor filename in filenames:\n zip_file.write(filename)\nresponse['Content-Disposition'] = 'attachment; filename={}'.format(zipfile_name)\nreturn response\n zip_file.close() response" }, { "answer_id": 51655455, "author": "Pasha M", "author_id": 8992267, "author_profile": "https://Stackoverflow.com/users/8992267", "pm_score": 3, "selected": false, "text": "import zipfile\nimport os\nfrom io import BytesIO\n\ndef download_zip_file(request):\n filelist = [\"path/to/file-11.txt\", \"path/to/file-22.txt\"]\n\n byte_data = BytesIO()\n zip_file = zipfile.ZipFile(byte_data, \"w\")\n\n for file in filelist:\n filename = os.path.basename(os.path.normpath(file))\n zip_file.write(file, filename)\n zip_file.close()\n\n response = HttpResponse(byte_data.getvalue(), content_type='application/zip')\n response['Content-Disposition'] = 'attachment; filename=files.zip'\n\n # Print list files in zip_file\n zip_file.printdir()\n\n return response\n" }, { "answer_id": 58849165, "author": "yspreen", "author_id": 2585092, "author_profile": "https://Stackoverflow.com/users/2585092", "pm_score": 0, "selected": false, "text": "def download_view(request, name=\"\"):\n from django_zip_stream.responses import FolderZipResponse\n path = settings.STATIC_ROOT\n path = os.path.join(path, name)\n\n return FolderZipResponse(path)\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44972/" ]
67,492
<p>Let's say the first N integers divisible by 3 starting with 9.</p> <p>I'm sure there is some one line solution using lambdas, I just don't know it that area of the language well enough yet.</p>
[ { "answer_id": 67552, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 0, "selected": false, "text": "yield internal IEnumerable Answer(N)\n{\n int n=0;\n int i=9;\n while (true)\n {\n if (i % 3 == 0)\n {\n n++;\n yield return i;\n }\n\n if (n>=N) return;\n i++;\n }\n}\n" }, { "answer_id": 67562, "author": "Charles Graham", "author_id": 7705, "author_profile": "https://Stackoverflow.com/users/7705", "pm_score": 0, "selected": false, "text": "public int f(int n)\n{\n if(ht[n].containsValue)\n return ht[n];\n else\n {\n //do calculation\n ht[n] = result;\n return result;\n }\n}\n" }, { "answer_id": 67677, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 1, "selected": false, "text": "const int __N = 100;\nconst int __start = 9;\nconst int __divisibleBy = 3;\n\n\nvar array = Enumerable.Range(__start, __N * __divisibleBy).Where(x => x % __divisibleBy == 0).Take(__N).ToArray();\n" }, { "answer_id": 67695, "author": "porges", "author_id": 10311, "author_profile": "https://Stackoverflow.com/users/10311", "pm_score": 3, "selected": false, "text": "int[] numbers =\n Enumerable.Range(9,10000)\n .Where(x => x % 3 == 0)\n .Take(20)\n .ToArray();\n int[] numbers =\n Enumerable.Range(9,10000)\n .AsParallel() //added this line\n .Where(x => x % 3 == 0)\n .Take(20)\n .ToArray();\n" }, { "answer_id": 67721, "author": "Guy", "author_id": 1463, "author_profile": "https://Stackoverflow.com/users/1463", "pm_score": 1, "selected": false, "text": "int n = 10; // Take first 10 that meet criteria\nint[] ia = Enumerable\n .Range(0,999)\n .Where(a => a % 3 == 0 && a.ToString()[0] == '9')\n .Take(n)\n .ToArray();\n" }, { "answer_id": 67933, "author": "Loren Segal", "author_id": 6436, "author_profile": "https://Stackoverflow.com/users/6436", "pm_score": 1, "selected": false, "text": "(q % m) s (s + (s % m) + m*n) s=q Range static int[] givemeN(int n)\n{\n const int baseVal = 9;\n const int modVal = 3;\n\n int i = 0;\n return Array.ConvertAll<int, int>(\n new int[n],\n new Converter<int, int>(\n x => baseVal + (baseVal % modVal) + \n ((i++) * modVal)\n ));\n}\n delegate static int[] givemeN(int n, Func<int, int> func)\n{\n int i = 0;\n return Array.ConvertAll<int, int>(new int[n], new Converter<int, int>(a => func(i++)));\n}\n givemeN(5, i => 9 + 3 * i)" }, { "answer_id": 68036, "author": "Cameron MacFarland", "author_id": 3820, "author_profile": "https://Stackoverflow.com/users/3820", "pm_score": 4, "selected": true, "text": "var numbers = Enumerable.Range(0, n).Select(i => i * 3 + 9);\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
67,499
<p>I have found that skin files only work if they are placed at the root theme folder in the App_Themes folder.</p> <p>For example, if you have 2 themes in the App_Themes folder, you cannot add another sub folder to the theme folder and place a seperate skin file in that subfolder. </p> <p>It's not much of a limitation, but it would give you more flexibility to further customize an app.</p> <p>Can anyone shed light on why this behavior occurs as it does in 2.0?</p>
[ { "answer_id": 71634, "author": "thomasb", "author_id": 6776, "author_profile": "https://Stackoverflow.com/users/6776", "pm_score": 1, "selected": false, "text": "<asp:DataList runat=\"server\" SkinID=\"DataListColor\" Width=\"100%\">\n <ItemStyle BackColor=\"Blue\" ForeColor=\"Red\" />\n</asp:DataList>\n\n<asp:DataList runat=\"server\" SkinID=\"DataListSmall\" Width=\"50%\">\n</asp:DataList>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
67,518
<p>I am trying to get the <code>Edit with Vim</code> context menu to open files in a new tab of the previously opened Gvim instance (if any).</p> <p>Currently, using <code>Regedit</code> I have modified this key:</p> <pre><code>\HKEY-LOCAL-MACHINE\SOFTWARE\Vim\Gvim\path = "C:\Programs\Vim\vim72\gvim.exe" -p --remote-tab-silent "%*" </code></pre> <p>The registry key type is <code>REG_SZ</code>.</p> <p>This almost works... Currently it opens the file in a new tab, but it also opens another tab (which is the active tab) the tab is labeled <code>\W\S\--literal</code> and the file seems to be trying to open the following file. </p> <pre><code>C:\Windows\System32\--literal </code></pre> <p>I think the problem is around the <code>"%*"</code> - I tried changing that to <code>"%1"</code> but if i do that I get an extra tab called <code>%1</code>.</p> <p><strong>Affected version</strong></p> <ul> <li>Vim version 7.2 (same behaviour on 7.1) </li> <li>Windows vista home premium</li> </ul> <p>Thanks for any help. </p> <p>David. </p>
[ { "answer_id": 78234, "author": "David Turner", "author_id": 10171, "author_profile": "https://Stackoverflow.com/users/10171", "pm_score": 2, "selected": false, "text": "Windows Registry Editor Version 5.00\n\n[HKEY_CLASSES_ROOT\\*\\shell\\Edit with Vim]\n@=\"\"\n\n[HKEY_CLASSES_ROOT\\*\\shell\\Edit with Vim\\command]\n@=\"\\\"C:\\\\Programs\\\\vim\\\\vim72\\\\gvim.exe\\\" -p --remote-tab-silent \\\"%1\\\" \\\"%*\\\"\"\n\n[HKEY_CLASSES_ROOT\\Applications\\gvim.exe\\shell\\open\\command]\n@=\"\\\"C:\\\\Programs\\\\vim\\\\vim72\\\\gvim.exe\\\" -p --remote-tab-silent \\\"%1\\\" \\\"%*\\\"\"\n" }, { "answer_id": 1725842, "author": "Krishna", "author_id": 210010, "author_profile": "https://Stackoverflow.com/users/210010", "pm_score": 2, "selected": false, "text": "HKEY-LOCAL-MACHINE\\SOFTWARE\\Vim\\Gvim\\path = \"C:\\Programs\\Vim \\vim72\\gvim.exe\" -p\n" }, { "answer_id": 20655637, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "_vimrc autocmd BufReadPost * tab ball" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10171/" ]
67,554
<p>I'm looking for a profiler in order to find the bottleneck in my C++ code. I'd like to find a free, non-intrusive, and good profiling tool. I'm a game developer, and I use PIX for Xbox&nbsp;360 and found it very good, but it's not free. I know the Intel <a href="https://en.wikipedia.org/wiki/VTune" rel="noreferrer">VTune</a>, but it's not free either.</p>
[ { "answer_id": 8982554, "author": "Arty", "author_id": 1166346, "author_profile": "https://Stackoverflow.com/users/1166346", "pm_score": 4, "selected": false, "text": "void f()\n{\n srand(time(0));\n\n vector<double> v(300000);\n\n generate_n(v.begin(), v.size(), &random);\n sort(v.begin(), v.end());\n sort(v.rbegin(), v.rend());\n sort(v.begin(), v.end());\n sort(v.rbegin(), v.rend());\n}\n" }, { "answer_id": 16311387, "author": "MW_dev", "author_id": 46654, "author_profile": "https://Stackoverflow.com/users/46654", "pm_score": 3, "selected": false, "text": "wpr.exe -start CPU\n...\nwpr.exe -stop output.etl\nwpa.exe output.etl\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10120/" ]
67,561
<p>The <a href="http://en.wikipedia.org/wiki/Law_Of_Demeter" rel="noreferrer">wikipedia article</a> about <a href="http://c2.com/cgi/wiki?LawOfDemeter" rel="noreferrer">Law of Demeter</a> says:</p> <blockquote> <p>The law can be stated simply as "use only one dot".</p> </blockquote> <p>However a <a href="http://weblogs.asp.net/jgalloway/archive/2006/12/06/a-simple-example-of-a-fluent-interface.aspx" rel="noreferrer">simple example</a> of a <a href="http://en.wikipedia.org/wiki/Fluent_interface" rel="noreferrer">fluent interface</a> may look like this:</p> <pre><code>static void Main(string[] args) { new ZRLabs.Yael.Pipeline("cat.jpg") .Rotate(90) .Watermark("Monkey") .RoundCorners(100, Color.Bisque) .Save("test.png"); } </code></pre> <p>So does this goes together?</p>
[ { "answer_id": 67593, "author": "Quibblesome", "author_id": 1143, "author_profile": "https://Stackoverflow.com/users/1143", "pm_score": 3, "selected": false, "text": "CurrentCustomer.Orders[0].Manufacturer.Address.Email(text);\n CurrentCustomer.Orders[0].EmailManufacturer(text);\n" }, { "answer_id": 67615, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 5, "selected": false, "text": "var List<SomeObj> list = new List<SomeObj>();\n//initialize data here\nreturn list.FindAll( i => i == someValue ).Sort( i1, i2 => i2 > i1).ToArray();\n" }, { "answer_id": 4269333, "author": "Andrei Rînea", "author_id": 1796, "author_profile": "https://Stackoverflow.com/users/1796", "pm_score": 3, "selected": false, "text": "var a = new ZRLabs.Yael.Pipeline(\"cat.jpg\");\na = a.Rotate(90);\na = a.Watermark(\"Monkey\");\na = a.RoundCorners(100, Color.Bisque);\na = a.Save(\"test.png\");\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2361/" ]
67,612
<p>In Javascript: How does one find the coordinates (x, y, height, width) of every link in a webpage?</p>
[ { "answer_id": 67642, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 3, "selected": true, "text": "$(\"a\").each(function() {\n var link = $(this);\n var top = link.offset().top;\n var left = link.offset().left;\n var width = link.offset.width();\n var height = link.offset.height();\n});\n" }, { "answer_id": 67674, "author": "Peter Boughton", "author_id": 9360, "author_profile": "https://Stackoverflow.com/users/9360", "pm_score": 0, "selected": false, "text": "$j('a').each( findOffset );\n\nfunction findOffset()\n{\n alert\n ( 'x=' + $j(this).offset().left\n + ' y=' + $j(this).offset().top\n + ' width=' + $j(this).width()\n + ' height=' + $j(this).height()\n );\n}\n" }, { "answer_id": 68073, "author": "HFLW", "author_id": 252822, "author_profile": "https://Stackoverflow.com/users/252822", "pm_score": 2, "selected": false, "text": "var links = document.getElementsByTagName(\"a\");\nfor(var i in links) {\n var link = links[i];\n console.log(link.offsetWidth, link.offsetHeight);\n}\n" }, { "answer_id": 33945031, "author": "Jonatas Walker", "author_id": 4640499, "author_profile": "https://Stackoverflow.com/users/4640499", "pm_score": 1, "selected": false, "text": "function getAllChildren (node, tag) {\n return [].slice.call(node.getElementsByTagName(tag));\n}\nfunction offset(element){\n var rect = element.getBoundingClientRect();\n var docEl = doc.documentElement;\n return {\n left: rect.left + window.pageXOffset - docEl.clientLeft,\n top: rect.top + window.pageYOffset - docEl.clientTop,\n width: element.offsetWidth,\n height: element.offsetHeight\n };\n}\n\nvar links = getAllChildren(document.body, 'a');\nlinks.forEach(function(link){\n var offset_node = offset(node);\n console.info(offset_node);\n});\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/401774/" ]
67,621
<p>I am working with ASP.net.<br><br> I am trying to call a method that exists on the base class for the page I am using. I want to call this method via Javascript and do not require any rendering to be handled by ASP.net.<br><br> What would be the easiest way to accomplish this. <br><br> I have looked at PageMethods which for some reason are not working and found that a lot of other people have had trouble with them.</p>
[ { "answer_id": 297326, "author": "Toran Billups", "author_id": 2701, "author_profile": "https://Stackoverflow.com/users/2701", "pm_score": 0, "selected": false, "text": "Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load\n Response.Cache.SetCacheability(HttpCacheability.NoCache)\n If Request.HttpMethod = \"GET\" Then\n 'do some work and return the rendered html\n ElseIf Request.HttpMethod = \"POST\" Then\n 'do some work and return xml\n Response.ContentType = \"text/xml\"\n Response.Write(\"<data></data>\")\n Response.End()\n Else\n Response.StatusCode = 404\n Response.End()\n End If\n End Sub\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3821/" ]
67,631
<p>How do I load a Python module given its full path?</p> <p>Note that the file can be anywhere in the filesystem where the user has access rights.</p> <hr /> <p><sub><strong>See also:</strong> <a href="https://stackoverflow.com/questions/301134">How to import a module given its name as string?</a></sub></p>
[ { "answer_id": 67672, "author": "Matt", "author_id": 10035, "author_profile": "https://Stackoverflow.com/users/10035", "pm_score": 3, "selected": false, "text": "imp.find_module() imp.load_module() /home/mypath/mymodule.py imp.find_module('mymodule', '/home/mypath/')\n" }, { "answer_id": 67692, "author": "Sebastian Rittau", "author_id": 7779, "author_profile": "https://Stackoverflow.com/users/7779", "pm_score": 12, "selected": true, "text": "import importlib.util\nimport sys\nspec = importlib.util.spec_from_file_location(\"module.name\", \"/path/to/file.py\")\nfoo = importlib.util.module_from_spec(spec)\nsys.modules[\"module.name\"] = foo\nspec.loader.exec_module(foo)\nfoo.MyClass()\n from importlib.machinery import SourceFileLoader\n\nfoo = SourceFileLoader(\"module.name\", \"/path/to/file.py\").load_module()\nfoo.MyClass()\n import imp\n\nfoo = imp.load_source('module.name', '/path/to/file.py')\nfoo.MyClass()\n" }, { "answer_id": 67693, "author": "zuber", "author_id": 9812, "author_profile": "https://Stackoverflow.com/users/9812", "pm_score": 4, "selected": false, "text": "load_source(module_name, path_to_file)\n" }, { "answer_id": 67705, "author": "user10370", "author_id": 10370, "author_profile": "https://Stackoverflow.com/users/10370", "pm_score": 2, "selected": false, "text": "###################\n## #\n## classloader.py #\n## #\n###################\n\nimport sys, types\n\ndef _get_mod(modulePath):\n try:\n aMod = sys.modules[modulePath]\n if not isinstance(aMod, types.ModuleType):\n raise KeyError\n except KeyError:\n # The last [''] is very important!\n aMod = __import__(modulePath, globals(), locals(), [''])\n sys.modules[modulePath] = aMod\n return aMod\n\ndef _get_func(fullFuncName):\n \"\"\"Retrieve a function object from a full dotted-package name.\"\"\"\n\n # Parse out the path, module, and function\n lastDot = fullFuncName.rfind(u\".\")\n funcName = fullFuncName[lastDot + 1:]\n modPath = fullFuncName[:lastDot]\n\n aMod = _get_mod(modPath)\n aFunc = getattr(aMod, funcName)\n\n # Assert that the function is a *callable* attribute.\n assert callable(aFunc), u\"%s is not callable.\" % fullFuncName\n\n # Return a reference to the function itself,\n # not the results of the function.\n return aFunc\n\ndef _get_class(fullClassName, parentClass=None):\n \"\"\"Load a module and retrieve a class (NOT an instance).\n\n If the parentClass is supplied, className must be of parentClass\n or a subclass of parentClass (or None is returned).\n \"\"\"\n aClass = _get_func(fullClassName)\n\n # Assert that the class is a subclass of parentClass.\n if parentClass is not None:\n if not issubclass(aClass, parentClass):\n raise TypeError(u\"%s is not a subclass of %s\" %\n (fullClassName, parentClass))\n\n # Return a reference to the class itself, not an instantiated object.\n return aClass\n\n\n######################\n## Usage ##\n######################\n\nclass StorageManager: pass\nclass StorageManagerMySQL(StorageManager): pass\n\ndef storage_object(aFullClassName, allOptions={}):\n aStoreClass = _get_class(aFullClassName, StorageManager)\n return aStoreClass(allOptions)\n" }, { "answer_id": 67708, "author": "ctcherry", "author_id": 10322, "author_profile": "https://Stackoverflow.com/users/10322", "pm_score": 5, "selected": false, "text": "configfile = '~/config.py'\n\nimport os\nimport sys\n\nsys.path.append(os.path.dirname(os.path.expanduser(configfile)))\n\nimport config\n" }, { "answer_id": 67715, "author": "Wheat", "author_id": 70142, "author_profile": "https://Stackoverflow.com/users/70142", "pm_score": 4, "selected": false, "text": "sys.path /foo/bar.py\n import sys\nsys.path[0:0] = ['/foo'] # Puts the /foo directory at the start of your path\nimport bar\n" }, { "answer_id": 68628, "author": "Chris Calloway", "author_id": 10769, "author_profile": "https://Stackoverflow.com/users/10769", "pm_score": 4, "selected": false, "text": "__import__ chdir def import_file(full_path_to_module):\n try:\n import os\n module_dir, module_file = os.path.split(full_path_to_module)\n module_name, module_ext = os.path.splitext(module_file)\n save_cwd = os.getcwd()\n os.chdir(module_dir)\n module_obj = __import__(module_name)\n module_obj.__file__ = full_path_to_module\n globals()[module_name] = module_obj\n os.chdir(save_cwd)\n except Exception as e:\n raise ImportError(e)\n return module_obj\n\n\nimport_file('/home/somebody/somemodule.py')\n" }, { "answer_id": 129374, "author": "Daryl Spitzer", "author_id": 4766, "author_profile": "https://Stackoverflow.com/users/4766", "pm_score": 9, "selected": false, "text": "import sys\n# the mock-0.3.1 dir contains testcase.py, testutils.py & mock.py\nsys.path.append('/foo/bar/mock-0.3.1')\n\nfrom testcase import TestCase\nfrom testutils import RunTests\nfrom mock import Mock, sentinel, patch\n" }, { "answer_id": 6284270, "author": "ubershmekel", "author_id": 177498, "author_profile": "https://Stackoverflow.com/users/177498", "pm_score": 2, "selected": false, "text": "imp import_file >>>from import_file import import_file\n>>>mylib = import_file('c:\\\\mylib.py')\n>>>another = import_file('relative_subdir/another.py')\n" }, { "answer_id": 8721254, "author": "Hengjie", "author_id": 914986, "author_profile": "https://Stackoverflow.com/users/914986", "pm_score": 2, "selected": false, "text": "path = os.path.join('./path/to/folder/with/py/files', '*.py')\nfor infile in glob.glob(path):\n basename = os.path.basename(infile)\n basename_without_extension = basename[:-3]\n\n # http://docs.python.org/library/imp.html?highlight=imp#module-imp\n imp.load_source(basename_without_extension, infile)\n" }, { "answer_id": 25827116, "author": "bob_twinkles", "author_id": 783910, "author_profile": "https://Stackoverflow.com/users/783910", "pm_score": 3, "selected": false, "text": "pkgutil walk_packages importlib import pkgutil\nimport importlib\n\npackages = pkgutil.walk_packages(path='.')\nfor importer, name, is_package in packages:\n mod = importlib.import_module(name)\n # do whatever you want with module now, it's been imported!\n" }, { "answer_id": 26995106, "author": "user2760152", "author_id": 2760152, "author_profile": "https://Stackoverflow.com/users/2760152", "pm_score": 2, "selected": false, "text": "ln -s /absolute/path/to/module/module.py /absolute/path/to/script/module.py\n /absolute/path/to/script/module.pyc /absolute/path/to/module/module.py from module import *\n" }, { "answer_id": 27127448, "author": "Zompa", "author_id": 2783173, "author_profile": "https://Stackoverflow.com/users/2783173", "pm_score": -1, "selected": false, "text": "import imp\nimport sys\n\ndef __import__(name, globals=None, locals=None, fromlist=None):\n # Fast path: see if the module has already been imported.\n try:\n return sys.modules[name]\n except KeyError:\n pass\n\n # If any of the following calls raises an exception,\n # there's a problem we can't handle -- let the caller handle it.\n\n fp, pathname, description = imp.find_module(name)\n\n try:\n return imp.load_module(name, fp, pathname, description)\n finally:\n # Since we may exit via an exception, close fp explicitly.\n if fp:\n fp.close()\n" }, { "answer_id": 29589414, "author": "Redlegjed", "author_id": 4779459, "author_profile": "https://Stackoverflow.com/users/4779459", "pm_score": 3, "selected": false, "text": "def import_module_from_file(full_path_to_module):\n \"\"\"\n Import a module given the full path/filename of the .py file\n\n Python 3.4\n\n \"\"\"\n\n module = None\n\n try:\n\n # Get module name and path from full path\n module_dir, module_file = os.path.split(full_path_to_module)\n module_name, module_ext = os.path.splitext(module_file)\n\n # Get module \"spec\" from filename\n spec = importlib.util.spec_from_file_location(module_name,full_path_to_module)\n\n module = spec.loader.load_module()\n\n except Exception as ec:\n # Simple error printing\n # Insert \"sophisticated\" stuff here\n print(ec)\n\n finally:\n return module\n" }, { "answer_id": 30605451, "author": "yoniLavi", "author_id": 493553, "author_profile": "https://Stackoverflow.com/users/493553", "pm_score": 2, "selected": false, "text": "exec exec \"/path/to/module foo() module = dict()\nwith open(\"/path/to/module\") as f:\n exec(f.read(), module)\nmodule['foo']()\n class MyModuleClass(dict):\n def __getattr__(self, name):\n return self.__getitem__(name)\n" }, { "answer_id": 32905959, "author": "Peter Zhu", "author_id": 4388898, "author_profile": "https://Stackoverflow.com/users/4388898", "pm_score": 2, "selected": false, "text": "filename = \"directory/module.py\"\n\ndirectory, module_name = os.path.split(filename)\nmodule_name = os.path.splitext(module_name)[0]\n\npath = list(sys.path)\nsys.path.insert(0, directory)\ntry:\n module = __import__(module_name)\nfinally:\n sys.path[:] = path # restore\n" }, { "answer_id": 37339817, "author": "ncoghlan", "author_id": 597742, "author_profile": "https://Stackoverflow.com/users/597742", "pm_score": 6, "selected": false, "text": "from runpy import run_path\nsettings = run_path(\"/path/to/file.py\")\n" }, { "answer_id": 37611448, "author": "sorin", "author_id": 99834, "author_profile": "https://Stackoverflow.com/users/99834", "pm_score": 4, "selected": false, "text": "config_file = \"/tmp/config.py\"\nwith open(config_file) as f:\n code = compile(f.read(), config_file, 'exec')\n exec(code, globals(), locals())\n" }, { "answer_id": 43602557, "author": "Mad Physicist", "author_id": 2988730, "author_profile": "https://Stackoverflow.com/users/2988730", "pm_score": 4, "selected": false, "text": "spec_from_loader spec_from_file_location from importlib.util import spec_from_loader, module_from_spec\nfrom importlib.machinery import SourceFileLoader \n\nspec = spec_from_loader(\"module.name\", SourceFileLoader(\"module.name\", \"/path/to/file.py\"))\nmod = module_from_spec(spec)\nspec.loader.exec_module(mod)\n SourceFileLoader .txt spec_from_file_location .txt importlib.machinery.SOURCE_SUFFIXES haggis.load.load_module" }, { "answer_id": 48191370, "author": "David", "author_id": 926217, "author_profile": "https://Stackoverflow.com/users/926217", "pm_score": 2, "selected": false, "text": "import sys\nimport importlib.machinery\n\ndef load_module(name, filename):\n # If the Loader finds the module name in this list it will use\n # module_name.__file__ instead so we need to delete it here\n if name in sys.modules:\n del sys.modules[name]\n loader = importlib.machinery.ExtensionFileLoader(name, filename)\n module = loader.load_module()\n locals()[name] = module\n globals()[name] = module\n\nload_module('something', r'C:\\Path\\To\\something.pyd')\nsomething.do_something()\n" }, { "answer_id": 48455971, "author": "Andrei Keino", "author_id": 3859945, "author_profile": "https://Stackoverflow.com/users/3859945", "pm_score": 2, "selected": false, "text": "libPath = '../../MyLibs'\nimport sys\nif not libPath in sys.path: sys.path.append(libPath)\nimport pyfunc as pf\n" }, { "answer_id": 50395128, "author": "Sam Grondahl", "author_id": 1188448, "author_profile": "https://Stackoverflow.com/users/1188448", "pm_score": 7, "selected": false, "text": "MODULE_PATH = \"/path/to/your/module/__init__.py\"\nMODULE_NAME = \"mymodule\"\nimport importlib\nimport sys\nspec = importlib.util.spec_from_file_location(MODULE_NAME, MODULE_PATH)\nmodule = importlib.util.module_from_spec(spec)\nsys.modules[spec.name] = module \nspec.loader.exec_module(module)\n" }, { "answer_id": 50509034, "author": "Ataxias", "author_id": 4055338, "author_profile": "https://Stackoverflow.com/users/4055338", "pm_score": 2, "selected": false, "text": "importlib imp import importlib\n\ndirname, basename = os.path.split(pyfilepath) # pyfilepath: '/my/path/mymodule.py'\nsys.path.append(dirname) # only directories should be added to PYTHONPATH\nmodule_name = os.path.splitext(basename)[0] # '/my/path/mymodule.py' --> 'mymodule'\nmodule = importlib.import_module(module_name) # name space of defined module (otherwise we would literally look for \"module_name\")\n a = module.myvar\nb = module.myfunc(a)\n" }, { "answer_id": 52236722, "author": "Michael Scott Asato Cuthbert", "author_id": 1293501, "author_profile": "https://Stackoverflow.com/users/1293501", "pm_score": 0, "selected": false, "text": "__init__.py import pathlib\n\ndef likely_python_module(filename):\n '''\n Given a filename or Path, return the \"likely\" python module name. That is, iterate\n the parent directories until it doesn't contain an __init__.py file.\n\n :rtype: str\n '''\n p = pathlib.Path(filename).resolve()\n paths = []\n if p.name != '__init__.py':\n paths.append(p.stem)\n while True:\n p = p.parent\n if not p:\n break\n if not p.is_dir():\n break\n\n inits = [f for f in p.iterdir() if f.name == '__init__.py']\n if not inits:\n break\n\n paths.append(p.stem)\n\n return '.'.join(reversed(paths))\n __init__.py __init__.py" }, { "answer_id": 53311583, "author": "Miladiouss", "author_id": 7428659, "author_profile": "https://Stackoverflow.com/users/7428659", "pm_score": 7, "selected": false, "text": "import sys\nsys.path.append(\"/path/to/my/modules/\")\nimport my_module\n .bashrc source ~/.bashrc export PYTHONPATH=\"${PYTHONPATH}:/path/to/my/modules/\"\n" }, { "answer_id": 53651717, "author": "abhimanyu", "author_id": 8135029, "author_profile": "https://Stackoverflow.com/users/8135029", "pm_score": 3, "selected": false, "text": "import sys\nsys.path.append(\"<project-path>/lib/\")\nfrom tes1 import Client1\nfrom tes2 import Client2\nimport tes3\n from test import Client1\nfrom test import Client2\nfrom test import test3\n" }, { "answer_id": 57843421, "author": "Andry", "author_id": 2672125, "author_profile": "https://Stackoverflow.com/users/2672125", "pm_score": 2, "selected": false, "text": "importlib sys.path <root>\n |\n +- test.py\n |\n +- testlib.py\n |\n +- /std1\n | |\n | +- testlib.std1.py\n |\n +- /std2\n | |\n | +- testlib.std2.py\n |\n +- /std3\n |\n +- testlib.std3.py\n test.py\n -> testlib.py\n -> testlib.std1.py\n -> testlib.std2.py\n -> testlib.std3.py\n import os, sys, inspect, copy\n\nSOURCE_FILE = os.path.abspath(inspect.getsourcefile(lambda:0)).replace('\\\\','/')\nSOURCE_DIR = os.path.dirname(SOURCE_FILE)\n\nprint(\"test::SOURCE_FILE: \", SOURCE_FILE)\n\n# portable import to the global space\nsys.path.append(TACKLELIB_ROOT) # TACKLELIB_ROOT - path to the library directory\nimport tacklelib as tkl\n\ntkl.tkl_init(tkl)\n\n# cleanup\ndel tkl # must be instead of `tkl = None`, otherwise the variable would be still persist\nsys.path.pop()\n\ntkl_import_module(SOURCE_DIR, 'testlib.py')\n\nprint(globals().keys())\n\ntestlib.base_test()\ntestlib.testlib_std1.std1_test()\ntestlib.testlib_std1.testlib_std2.std2_test()\n#testlib.testlib.std3.std3_test() # does not reachable directly ...\ngetattr(globals()['testlib'], 'testlib.std3').std3_test() # ... but reachable through the `globals` + `getattr`\n\ntkl_import_module(SOURCE_DIR, 'testlib.py', '.')\n\nprint(globals().keys())\n\nbase_test()\ntestlib_std1.std1_test()\ntestlib_std1.testlib_std2.std2_test()\n#testlib.std3.std3_test() # does not reachable directly ...\nglobals()['testlib.std3'].std3_test() # ... but reachable through the `globals` + `getattr`\n # optional for 3.4.x and higher\n#import os, inspect\n#\n#SOURCE_FILE = os.path.abspath(inspect.getsourcefile(lambda:0)).replace('\\\\','/')\n#SOURCE_DIR = os.path.dirname(SOURCE_FILE)\n\nprint(\"1 testlib::SOURCE_FILE: \", SOURCE_FILE)\n\ntkl_import_module(SOURCE_DIR + '/std1', 'testlib.std1.py', 'testlib_std1')\n\n# SOURCE_DIR is restored here\nprint(\"2 testlib::SOURCE_FILE: \", SOURCE_FILE)\n\ntkl_import_module(SOURCE_DIR + '/std3', 'testlib.std3.py')\n\nprint(\"3 testlib::SOURCE_FILE: \", SOURCE_FILE)\n\ndef base_test():\n print('base_test')\n # optional for 3.4.x and higher\n#import os, inspect\n#\n#SOURCE_FILE = os.path.abspath(inspect.getsourcefile(lambda:0)).replace('\\\\','/')\n#SOURCE_DIR = os.path.dirname(SOURCE_FILE)\n\nprint(\"testlib.std1::SOURCE_FILE: \", SOURCE_FILE)\n\ntkl_import_module(SOURCE_DIR + '/../std2', 'testlib.std2.py', 'testlib_std2')\n\ndef std1_test():\n print('std1_test')\n # optional for 3.4.x and higher\n#import os, inspect\n#\n#SOURCE_FILE = os.path.abspath(inspect.getsourcefile(lambda:0)).replace('\\\\','/')\n#SOURCE_DIR = os.path.dirname(SOURCE_FILE)\n\nprint(\"testlib.std2::SOURCE_FILE: \", SOURCE_FILE)\n\ndef std2_test():\n print('std2_test')\n # optional for 3.4.x and higher\n#import os, inspect\n#\n#SOURCE_FILE = os.path.abspath(inspect.getsourcefile(lambda:0)).replace('\\\\','/')\n#SOURCE_DIR = os.path.dirname(SOURCE_FILE)\n\nprint(\"testlib.std3::SOURCE_FILE: \", SOURCE_FILE)\n\ndef std3_test():\n print('std3_test')\n 3.7.4 test::SOURCE_FILE: <root>/test01/test.py\nimport : <root>/test01/testlib.py as testlib -> []\n1 testlib::SOURCE_FILE: <root>/test01/testlib.py\nimport : <root>/test01/std1/testlib.std1.py as testlib_std1 -> ['testlib']\nimport : <root>/test01/std1/../std2/testlib.std2.py as testlib_std2 -> ['testlib', 'testlib_std1']\ntestlib.std2::SOURCE_FILE: <root>/test01/std1/../std2/testlib.std2.py\n2 testlib::SOURCE_FILE: <root>/test01/testlib.py\nimport : <root>/test01/std3/testlib.std3.py as testlib.std3 -> ['testlib']\ntestlib.std3::SOURCE_FILE: <root>/test01/std3/testlib.std3.py\n3 testlib::SOURCE_FILE: <root>/test01/testlib.py\ndict_keys(['__name__', '__doc__', '__package__', '__loader__', '__spec__', '__annotations__', '__builtins__', '__file__', '__cached__', 'os', 'sys', 'inspect', 'copy', 'SOURCE_FILE', 'SOURCE_DIR', 'TackleGlobalImportModuleState', 'tkl_membercopy', 'tkl_merge_module', 'tkl_get_parent_imported_module_state', 'tkl_declare_global', 'tkl_import_module', 'TackleSourceModuleState', 'tkl_source_module', 'TackleLocalImportModuleState', 'testlib'])\nbase_test\nstd1_test\nstd2_test\nstd3_test\nimport : <root>/test01/testlib.py as . -> []\n1 testlib::SOURCE_FILE: <root>/test01/testlib.py\nimport : <root>/test01/std1/testlib.std1.py as testlib_std1 -> ['testlib']\nimport : <root>/test01/std1/../std2/testlib.std2.py as testlib_std2 -> ['testlib', 'testlib_std1']\ntestlib.std2::SOURCE_FILE: <root>/test01/std1/../std2/testlib.std2.py\n2 testlib::SOURCE_FILE: <root>/test01/testlib.py\nimport : <root>/test01/std3/testlib.std3.py as testlib.std3 -> ['testlib']\ntestlib.std3::SOURCE_FILE: <root>/test01/std3/testlib.std3.py\n3 testlib::SOURCE_FILE: <root>/test01/testlib.py\ndict_keys(['__name__', '__doc__', '__package__', '__loader__', '__spec__', '__annotations__', '__builtins__', '__file__', '__cached__', 'os', 'sys', 'inspect', 'copy', 'SOURCE_FILE', 'SOURCE_DIR', 'TackleGlobalImportModuleState', 'tkl_membercopy', 'tkl_merge_module', 'tkl_get_parent_imported_module_state', 'tkl_declare_global', 'tkl_import_module', 'TackleSourceModuleState', 'tkl_source_module', 'TackleLocalImportModuleState', 'testlib', 'testlib_std1', 'testlib.std3', 'base_test'])\nbase_test\nstd1_test\nstd2_test\nstd3_test\n 3.7.4 3.2.5 2.7.16 testlib.std.py testlib testlib.blabla.py testlib_blabla sys.path SOURCE_FILE SOURCE_DIR tkl_import_module 3.4.x tkl_import_module named->local->named local->named->local 3.4.x tkl_import_module tkl_declare_global 3.3.x tkl_import_module tkl_import_module 3.4.x tkl_import_module tkl_import_module tkl_source_module source tkl_declare_global" }, { "answer_id": 58943466, "author": "fny", "author_id": 390897, "author_profile": "https://Stackoverflow.com/users/390897", "pm_score": 3, "selected": false, "text": "from thesmuggler import smuggle\n\n# À la `import weapons`\nweapons = smuggle('weapons.py')\n\n# À la `from contraband import drugs, alcohol`\ndrugs, alcohol = smuggle('drugs', 'alcohol', source='contraband.py')\n\n# À la `from contraband import drugs as dope, alcohol as booze`\ndope, booze = smuggle('drugs', 'alcohol', source='contraband.py')\n" }, { "answer_id": 58974141, "author": "Kumar KS", "author_id": 4270698, "author_profile": "https://Stackoverflow.com/users/4270698", "pm_score": 4, "selected": false, "text": "utils.py src/main/util/ import sys\nsys.path.append('./')\n\nimport src.main.util.utils\n#or\nfrom src.main.util.utils import json_converter # json_converter is example method\n" }, { "answer_id": 63332270, "author": "Benos", "author_id": 2321965, "author_profile": "https://Stackoverflow.com/users/2321965", "pm_score": 1, "selected": false, "text": "from pathlib import Path\nfrom importlib.util import spec_from_file_location, module_from_spec\nfrom typing import Optional\n\n\ndef get_module_from_path(path: Path, relative_to: Optional[Path] = None):\n if not relative_to:\n relative_to = Path.cwd()\n\n abs_path = path.absolute()\n relative_path = abs_path.relative_to(relative_to.absolute())\n if relative_path.name == \"__init__.py\":\n relative_path = relative_path.parent\n module_name = \".\".join(relative_path.with_suffix(\"\").parts)\n mod = module_from_spec(spec_from_file_location(module_name, path))\n return mod\n\n\ndef get_modules_from_folder(folder: Optional[Path] = None, glob_str: str = \"*/**/*.py\"):\n if not folder:\n folder = Path(\".\")\n\n mod_list = []\n for file_path in sorted(folder.glob(glob_str)):\n mod_list.append(get_module_from_path(file_path))\n\n return mod_list\n" }, { "answer_id": 66181002, "author": "Bryan Grace", "author_id": 2600905, "author_profile": "https://Stackoverflow.com/users/2600905", "pm_score": 0, "selected": false, "text": "from importlib.machinery import SourceFileLoader\nimport os\n\ndef LOAD(MODULE_PATH):\n if (MODULE_PATH[0] == \"/\"):\n FULL_PATH = MODULE_PATH;\n else:\n DIR_PATH = os.path.dirname (os.path.realpath (__file__))\n FULL_PATH = os.path.normpath (DIR_PATH + \"/\" + MODULE_PATH)\n\n return SourceFileLoader (FULL_PATH, FULL_PATH).load_module ()\n Y = LOAD(\"../Z.py\")\nA = LOAD(\"./A.py\")\nD = LOAD(\"./C/D.py\")\nA_ = LOAD(\"/IMPORTS/A.py\")\n\nY.DEF();\nA.DEF();\nD.DEF();\nA_.DEF();\n def DEF():\n print(\"A\");\n" }, { "answer_id": 66499112, "author": "Mhadhbi issam", "author_id": 9791039, "author_profile": "https://Stackoverflow.com/users/9791039", "pm_score": -1, "selected": false, "text": "module = dict()\n\ncode = \"\"\"\nimport json\n\ndef testhi() :\n return json.dumps({\"key\" : \"value\"}, indent = 4 )\n\"\"\"\n\nexec(code, module)\nx = module['testhi']()\nprint(x)\n" }, { "answer_id": 68361215, "author": "ジョージ", "author_id": 558008, "author_profile": "https://Stackoverflow.com/users/558008", "pm_score": 3, "selected": false, "text": "from pydoc import importfile\nmodule = importfile('/path/to/module.py')\n" }, { "answer_id": 69286913, "author": "Max Kleiner", "author_id": 9041224, "author_profile": "https://Stackoverflow.com/users/9041224", "pm_score": -1, "selected": false, "text": "PYMODULE = 'C:\\maXbox\\mX47464\\maxbox4\\examples\\histogram15.py';\nExecstring(LoadStringJ(PYMODULE));\n println('get module data: '+evalStr('pyplot.hist(x)'));\n Execstring('sys.path.append(r'+'\"'+PYMODULEPATH+'\")');\nExecstring('from histogram import *'); \n" }, { "answer_id": 70797815, "author": "Jorge", "author_id": 3170848, "author_profile": "https://Stackoverflow.com/users/3170848", "pm_score": 0, "selected": false, "text": "from pydoc import importfile\nmodule = importfile('/full/path/to/module/module.py')\nname = module.myclass() # myclass is a class inside your python file\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10286/" ]
67,647
<p>I'm looking for a way to extract the audio part of a FLV file. </p> <p>I'm recording from the user's microphone and the audio is encoded using the <a href="http://en.wikipedia.org/wiki/Nellymoser_Asao_Codec" rel="nofollow noreferrer">Nellymoser Asao Codec</a>. This is the default codec and there's no way to change this.</p>
[ { "answer_id": 76266, "author": "Costo", "author_id": 1130, "author_profile": "https://Stackoverflow.com/users/1130", "pm_score": 4, "selected": true, "text": "ffmpeg -i source.flv -nv -f mp3 destination.mp3 Unsupported audio codec (n)" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1130/" ]
67,676
<p>How can I use .NET DataSet.Select method to search records that match a DateTime? What format should I use to enter my dates in?</p>
[ { "answer_id": 67696, "author": "Leo Moore", "author_id": 6336, "author_profile": "https://Stackoverflow.com/users/6336", "pm_score": 3, "selected": true, "text": "ds.select(DBDate = '15 Sep 2008')\n" }, { "answer_id": 67753, "author": "creohornet", "author_id": 9111, "author_profile": "https://Stackoverflow.com/users/9111", "pm_score": 0, "selected": false, "text": " public string BuildSQL()\n {\n // Format: CAST('2000-05-08 12:35:29' AS datetime)\n StringBuilder sb = new StringBuilder(\"CAST('\");\n\n sb.Append(_dateTime.ToString(\"yyyy-MM-dd HH:mm:ss\"));\n sb.Append(\"' AS datetime)\");\n\n return sb.ToString();\n }\n" }, { "answer_id": 14658794, "author": "user2034559", "author_id": 2034559, "author_profile": "https://Stackoverflow.com/users/2034559", "pm_score": 0, "selected": false, "text": "dataTable.Select(String.Format(\"DateCreated='{0}'\",_dateCreated.ToString(\"O\")));\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67676", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7277/" ]
67,682
<p>I'm trying to make it so when a user scrolls down a page, click a link, do whatever it is they need to do, and then come back to the pages w/ links, they are at the same (x-y) location in the browser they were before. How do I do that?</p> <p>I'm a DOM Newbie so I don't know too much about how to do this. </p> <p>Target Browsers: IE6/7/8, Firefox 2/3, Opera, Safari</p> <p>Added: I'm using a program called JQuery to help me learn</p>
[ { "answer_id": 127998, "author": "deepwell", "author_id": 21473, "author_profile": "https://Stackoverflow.com/users/21473", "pm_score": 2, "selected": false, "text": "<html>\n <head>\n <script type=\"text/javascript\" src=\"jquery.js\"></script>\n <script type=\"text/javascript\">\n jQuery(document).ready(function(){\n $(\"#special\").click(function(e){\n $('#status2').html(e.pageX +', '+ e.pageY);\n }); \n });\n </script>\n </head>\n <body>\n <h2 id=\"status2\">\n 0, 0\n </h2>\n <div style=\"width: 100px; height: 100px; background:#ccc;\" id=\"special\">\n Click me anywhere!\n </div>\n </body>\n</html>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10352/" ]
67,685
<p>I want my website to join some webcam recordings in FLV files (like this one). This needs to be done on Linux without user input. How do I do this? For simplicity's sake, I'll use the same flv as both inputs in hope of getting a flv that plays the same thing twice in a row.</p> <p>That should be easy enough, right? There's even a full code example in the <a href="http://ffmpeg.mplayerhq.hu/faq.html#SEC31" rel="noreferrer">ffmpeg FAQ</a>.</p> <p>Well, pipes seem to be giving me problems (both on my mac running Leopard and on Ubuntu 8.04) so let's keep it simple and use normal files. Also, if I don't specify a rate of 15 fps, the visual part plays <a href="http://www.marc-andre.ca/posts/blog/webcam/output-norate.flv" rel="noreferrer">extremely fast</a>. The example script thus becomes:</p> <pre><code>ffmpeg -i input.flv -vn -f u16le -acodec pcm_s16le -ac 2 -ar 44100 \ - &gt; temp.a &lt; /dev/null ffmpeg -i input.flv -an -f yuv4mpegpipe - &gt; temp.v &lt; /dev/null cat temp.v temp.v &gt; all.v cat temp.a temp.a &gt; all.a ffmpeg -f u16le -acodec pcm_s16le -ac 2 -ar 44100 -i all.a \ -f yuv4mpegpipe -i all.v -sameq -y output.flv </code></pre> <p>Well, using this will work for the audio, but I only get the video the first time around. This seems to be the case for any flv I throw as input.flv, including the movie teasers that come with red5.</p> <p>a) Why doesn't the example script work as advertised, in particular why do I not get all the video I'm expecting?</p> <p>b) Why do I have to specify a framerate while Wimpy player can play the flv at the right speed?</p> <p>The only way I found to join two flvs was to use mencoder. Problem is, mencoder doesn't seem to join flvs:</p> <pre><code>mencoder input.flv input.flv -o output.flv -of lavf -oac copy \ -ovc lavc -lavcopts vcodec=flv </code></pre> <p>I get a Floating point exception...</p> <pre><code>MEncoder 1.0rc2-4.0.1 (C) 2000-2007 MPlayer Team CPU: Intel(R) Xeon(R) CPU 5150 @ 2.66GHz (Family: 6, Model: 15, Stepping: 6) CPUflags: Type: 6 MMX: 1 MMX2: 1 3DNow: 0 3DNow2: 0 SSE: 1 SSE2: 1 Compiled for x86 CPU with extensions: MMX MMX2 SSE SSE2 success: format: 0 data: 0x0 - 0x45b2f libavformat file format detected. [flv @ 0x697160]Unsupported audio codec (6) [flv @ 0x697160]Could not find codec parameters (Audio: 0x0006, 22050 Hz, mono) [lavf] Video stream found, -vid 0 [lavf] Audio stream found, -aid 1 VIDEO: [FLV1] 240x180 0bpp 1000.000 fps 0.0 kbps ( 0.0 kbyte/s) [V] filefmt:44 fourcc:0x31564C46 size:240x180 fps:1000.00 ftime:=0.0010 ** MUXER_LAVF ***************************************************************** REMEMBER: MEncoder's libavformat muxing is presently broken and can generate INCORRECT files in the presence of B frames. Moreover, due to bugs MPlayer will play these INCORRECT files as if nothing were wrong! ******************************************************************************* OK, exit Opening video filter: [expand osd=1] Expand: -1 x -1, -1 ; -1, osd: 1, aspect: 0.000000, round: 1 ========================================================================== Opening video decoder: [ffmpeg] FFmpeg's libavcodec codec family Selected video codec: [ffflv] vfm: ffmpeg (FFmpeg Flash video) ========================================================================== audiocodec: framecopy (format=6 chans=1 rate=22050 bits=16 B/s=0 sample-0) VDec: vo config request - 240 x 180 (preferred colorspace: Planar YV12) VDec: using Planar YV12 as output csp (no 0) Movie-Aspect is undefined - no prescaling applied. videocodec: libavcodec (240x180 fourcc=31564c46 [FLV1]) VIDEO CODEC ID: 22 AUDIO CODEC ID: 10007, TAG: 0 Writing header... [NULL @ 0x67d110]codec not compatible with flv Floating point exception </code></pre> <p>c) Is there a way for mencoder to decode and encode flvs correctly?</p> <p>So the only way I've found so far to join flvs, is to use ffmpeg to go back and forth between flv and avi, and use mencoder to join the avis:</p> <pre><code>ffmpeg -i input.flv -vcodec rawvideo -acodec pcm_s16le -r 15 file.avi mencoder -o output.avi -oac copy -ovc copy -noskip file.avi file.avi ffmpeg -i output.avi output.flv </code></pre> <p>d) There must be a better way to achieve this... Which one?</p> <p>e) Because of the problem of the framerate, though, only flvs with constant framerate (like the one I recorded through <a href="http://ffmpeg.mplayerhq.hu/faq.html#SEC31" rel="noreferrer">facebook</a>) will be converted correctly to avis, but this won't work for the flvs I seem to be recording (like <a href="http://www.marc-andre.ca/posts/blog/webcam/test-wowza.flv" rel="noreferrer">this one</a> or <a href="http://www.marc-andre.ca/posts/blog/webcam/test-red5-publisher.flv" rel="noreferrer">this one</a>). Is there a way to do this for these flvs too?</p> <p>Any help would be very appreciated.</p>
[ { "answer_id": 107523, "author": "paranoio", "author_id": 11124, "author_profile": "https://Stackoverflow.com/users/11124", "pm_score": -1, "selected": false, "text": "cat yourVideos/*.flv >> big.flv\n" }, { "answer_id": 143015, "author": "Marc-André Lafortune", "author_id": 8279, "author_profile": "https://Stackoverflow.com/users/8279", "pm_score": 0, "selected": false, "text": "flvtool" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8279/" ]
67,699
<p>My <code>master</code> and <code>development</code> branches are tracked remotely on <a href="http://en.wikipedia.org/wiki/GitHub" rel="noreferrer">GitHub</a>. How do I clone both these branches?</p>
[ { "answer_id": 67712, "author": "MattoxBeckman", "author_id": 10354, "author_profile": "https://Stackoverflow.com/users/10354", "pm_score": 5, "selected": false, "text": "git clone git branch -a git checkout foo" }, { "answer_id": 67716, "author": "elmarco", "author_id": 1277510, "author_profile": "https://Stackoverflow.com/users/1277510", "pm_score": 6, "selected": false, "text": "git checkout -b branch origin/branchname\n" }, { "answer_id": 67748, "author": "Luuk Paulussen", "author_id": 10394, "author_profile": "https://Stackoverflow.com/users/10394", "pm_score": 6, "selected": false, "text": "git checkout -b dev refs/remotes/origin/dev\n Branch dev set up to track remote branch refs/remotes/origin/dev. Switched to a new branch \"dev\"\n" }, { "answer_id": 72156, "author": "emk", "author_id": 12089, "author_profile": "https://Stackoverflow.com/users/12089", "pm_score": 13, "selected": true, "text": "cd $ git clone git://example.com/myproject\n$ cd myproject\n $ git branch\n* master\n -a $ git branch -a\n* master\n remotes/origin/HEAD\n remotes/origin/master\n remotes/origin/v1.0-stable\n remotes/origin/experimental\n $ git checkout origin/experimental\n $ git checkout experimental\n\nBranch experimental set up to track remote branch experimental from origin.\nSwitched to a new branch 'experimental'\n $ git branch\n* experimental\n master\n git remote $ git remote add win32 git://example.com/users/joe/myproject-win32-port\n$ git branch -a\n* master\n remotes/origin/HEAD\n remotes/origin/master\n remotes/origin/v1.0-stable\n remotes/origin/experimental\n remotes/win32/master\n remotes/win32/new-widgets\n gitk $ gitk --all &\n" }, { "answer_id": 1186645, "author": "murphytalk", "author_id": 144330, "author_profile": "https://Stackoverflow.com/users/144330", "pm_score": 7, "selected": false, "text": "git checkout -t origin/experimental\n git checkout --track origin/experimental\n" }, { "answer_id": 4414131, "author": "user43685", "author_id": 43685, "author_profile": "https://Stackoverflow.com/users/43685", "pm_score": 3, "selected": false, "text": "#!/usr/bin/env ruby\n\nlocal = []\nremote = {}\n\n# Prepare\n%x[git reset --hard HEAD]\n%x[git checkout master] # Makes sure that * is on master.\n%x[git branch -a].each_line do |line|\n line.strip!\n if /origin\\//.match(line)\n remote[line.gsub(/origin\\//, '')] = line\n else\n local << line\n end\nend\n# Update \nremote.each_pair do |loc, rem|\n next if local.include?(loc)\n %x[git checkout --track -b #{loc} #{rem}]\nend\n%x[git fetch]\n" }, { "answer_id": 4682612, "author": "Gabe Kopley", "author_id": 283398, "author_profile": "https://Stackoverflow.com/users/283398", "pm_score": 10, "selected": false, "text": "git pull --all\n" }, { "answer_id": 4754797, "author": "bigfish", "author_id": 583867, "author_profile": "https://Stackoverflow.com/users/583867", "pm_score": 9, "selected": false, "text": "#!/bin/bash\nfor branch in $(git branch --all | grep '^\\s*remotes' | egrep --invert-match '(:?HEAD|master)$'); do\n git branch --track \"${branch##*/}\" \"$branch\"\ndone\n git fetch --all\ngit pull --all\n git branch -a | grep -v HEAD | perl -ne 'chomp($_); s|^\\*?\\s*||; if (m|(.+)/(.+)| && not $d{$2}) {print qq(git branch --track $2 $1/$2\\n)} else {$d{$_}=1}' | csh -xfs" }, { "answer_id": 6186997, "author": "rapher", "author_id": 777553, "author_profile": "https://Stackoverflow.com/users/777553", "pm_score": 5, "selected": false, "text": "$ git clone git://example.com/myproject\n\n$ cd myproject\n\n$ git checkout branchxyz\nBranch branchxyz set up to track remote branch branchxyz from origin.\nSwitched to a new branch 'branchxyz'\n\n$ git pull\nAlready up-to-date.\n\n$ git branch\n* branchxyz\n master\n\n$ git branch -a\n* branchxyz\n master\n remotes/origin/HEAD -> origin/master\n remotes/origin/branchxyz\n remotes/origin/branch123\n git clone git://example.com/myprojectt" }, { "answer_id": 7216269, "author": "Dave", "author_id": 915724, "author_profile": "https://Stackoverflow.com/users/915724", "pm_score": 9, "selected": false, "text": "--mirror remote git clone --mirror path/to/original path/to/dest/.git\ncd path/to/dest\ngit config --bool core.bare false\ngit checkout anybranch\n" }, { "answer_id": 10563611, "author": "Nikos C.", "author_id": 856199, "author_profile": "https://Stackoverflow.com/users/856199", "pm_score": 8, "selected": false, "text": "git checkout somebranch\n $ git checkout somebranch\nBranch somebranch set up to track remote branch somebranch from origin.\nSwitched to a new branch 'somebranch'\n $ git checkout -b <branch> --track <remote>/<branch>\n" }, { "answer_id": 12389954, "author": "Andy", "author_id": 312480, "author_profile": "https://Stackoverflow.com/users/312480", "pm_score": 2, "selected": false, "text": "mkdir YourRepo\ncd YourRepo\ngit init --bare .git # create a bare repo\ngit remote add origin REMOTE_URL # add a remote\ngit fetch origin refs/heads/*:refs/heads/* # fetch heads\ngit fetch origin refs/tags/*:refs/tags/* # fetch tags\ngit init # reinit work tree\ngit checkout master # checkout a branch\n" }, { "answer_id": 13575102, "author": "Jacob Fike", "author_id": 506537, "author_profile": "https://Stackoverflow.com/users/506537", "pm_score": 6, "selected": false, "text": "mkdir repo\ncd repo\ngit clone --bare path/to/repo.git .git\ngit config --unset core.bare\ngit reset --hard\n git branch --mirror --bare" }, { "answer_id": 16563327, "author": "nobody", "author_id": 2383918, "author_profile": "https://Stackoverflow.com/users/2383918", "pm_score": 6, "selected": false, "text": "git config --global alias.clone-branches '! git branch -a | sed -n \"/\\/HEAD /d; /\\/master$/d; /remotes/p;\" | xargs -L1 git checkout -t'\n git clone-branches\n" }, { "answer_id": 17635744, "author": "Camwyn", "author_id": 813905, "author_profile": "https://Stackoverflow.com/users/813905", "pm_score": 2, "selected": false, "text": "git checkout -b recreated-branch-name\ngit branch -a (to list remote branches)\ngit rebase remotes/remote-origin/recreated-branch-name\n $ git checkout -b mynewbranch\n\n$ git branch -a\n master\n remotes/sjp/master\n remotes/sjp/mynewbranch\n\n$ git fetch (habit to always do before)\n\n$ git rebase remotes/sjp/mynewbranch\n" }, { "answer_id": 20697765, "author": "ikaruss", "author_id": 1998046, "author_profile": "https://Stackoverflow.com/users/1998046", "pm_score": 3, "selected": false, "text": "git checkout master ; remote=origin ; for brname in `git branch -r | grep $remote | grep -v master | grep -v HEAD | awk '{gsub(/^[^\\/]+\\//,\"\",$1); print $1}'`; do git branch -D $brname ; git checkout -b $brname $remote/$brname ; done ; git checkout master\n git checkout master ;\nremote=origin ;\nfor brname in `\n git branch -r | grep $remote | grep -v master | grep -v HEAD\n | awk '{gsub(/^[^\\/]+\\//,\"\",$1); print $1}'\n`; do\n git branch -D $brname ;\n git checkout -b $brname $remote/$brname ;\ndone ;\ngit checkout master\n" }, { "answer_id": 20783081, "author": "Sam", "author_id": 1776255, "author_profile": "https://Stackoverflow.com/users/1776255", "pm_score": 6, "selected": false, "text": "git fetch origin git branch -a git checkout --track origin/<branch you want to checkout> git branch\n *your current branch\nsome branch2\nsome branch3\n" }, { "answer_id": 22199624, "author": "Cerran", "author_id": 3198108, "author_profile": "https://Stackoverflow.com/users/3198108", "pm_score": 6, "selected": false, "text": "git clone git branch git branch -a git branch branchone origin/branchone\ngit branch branchtwo origin/branchtwo\ngit branch branchthree origin/branchthree\n branchone origin/branchone git branch localbranchname origin/branchone\n git branch -a" }, { "answer_id": 27020944, "author": "Haimei", "author_id": 2730862, "author_profile": "https://Stackoverflow.com/users/2730862", "pm_score": 5, "selected": false, "text": "git clone <your_http_url>\n git branch -a\n git checkout <your_branch_name>\n" }, { "answer_id": 28115781, "author": "Gaui", "author_id": 1053611, "author_profile": "https://Stackoverflow.com/users/1053611", "pm_score": 4, "selected": false, "text": "git clone --mirror OLD_REPO_URL\ncd new-cloned-project\nmkdir .git\nmv * .git\ngit config --local --bool core.bare false\ngit reset --hard HEAD\ngit remote add newrepo NEW_REPO_URL\ngit push --all newrepo\ngit push --tags newrepo\n git config --global alias.clone-branches '! git branch -a | sed -n \"/\\/HEAD /d; /\\/master$/d; /remotes/p;\" | xargs -L1 git checkout -t'\ngit clone OLD_REPO_URL\ncd new-cloned-project\ngit clone-branches\ngit remote add newrepo NEW_REPO_URL\ngit push --all newrepo\ngit push --tags newrepo\n" }, { "answer_id": 28617347, "author": "Tebe", "author_id": 758158, "author_profile": "https://Stackoverflow.com/users/758158", "pm_score": 4, "selected": false, "text": "for branch in `git branch -r | grep -v 'HEAD\\|master'`; do\n git branch --track ${branch##*/} $branch;\ndone\n" }, { "answer_id": 32501388, "author": "jofel", "author_id": 1182783, "author_profile": "https://Stackoverflow.com/users/1182783", "pm_score": 3, "selected": false, "text": "(git branch -r | sed -n '/->/!s#^ origin/##p' && echo master) | xargs -L1 git checkout\n git clone master git branch -r | sed -n '/->/!s#^ origin/##p'| xargs -L1 git checkout\n" }, { "answer_id": 34122093, "author": "FedericoCapaldo", "author_id": 3245486, "author_profile": "https://Stackoverflow.com/users/3245486", "pm_score": 5, "selected": false, "text": "git branch -a\n git checkout -b branchname origin/branchname\n cd ~/Desktop && mkdir my_repo_folder && cd my_repo_folder\ngit clone --mirror https://github.com/planetoftheweb/responsivebootstrap.git .git\n git config --bool core.bare false\n git reset --hard\n" }, { "answer_id": 35948878, "author": "Phil", "author_id": 3432865, "author_profile": "https://Stackoverflow.com/users/3432865", "pm_score": 3, "selected": false, "text": "git clone <repo> <destination_folder>\ncd <destination_folder>\ngit fetch && git checkout <branch>\n git clone https://[email protected]/team/repository.git project_folder\ncd project_folder\ngit fetch && git checkout develop\n" }, { "answer_id": 36322324, "author": "kenorb", "author_id": 55075, "author_profile": "https://Stackoverflow.com/users/55075", "pm_score": 3, "selected": false, "text": "git ls-refs git fetch git pull --all git fetch --all git ls-remote -h -t origin\n git fetch origin --depth=10000 $(git ls-remote -h -t origin)\n --depth=10000 git branch -avv\n $ git remote -v show origin\n\n...\n Remote branches:\n master tracked\n git remote set-branches git remote set-branches --add origin missing_branch\n remotes/origin $ git remote -v show origin\n\n...\n Remote branches:\n missing_branch new (next fetch will store in remotes/origin)\n$ git fetch\nFrom github.com:Foo/Bar\n * [new branch] missing_branch -> origin/missing_branch\n git remote -v git config branch.master.remote origin origin git remote show origin" }, { "answer_id": 37906446, "author": "gringo_dave", "author_id": 545918, "author_profile": "https://Stackoverflow.com/users/545918", "pm_score": 4, "selected": false, "text": "Function git-GetAllRemoteBranches {\n iex \"git branch -r\" <# get all remote branches #> `\n | % { $_ -Match \"origin\\/(?'name'\\S+)\" } <# select only names of the branches #> `\n | % { Out-Null; $matches['name'] } <# write does names #>\n}\n\n\nFunction git-CheckoutAllBranches {\n git-GetAllRemoteBranches `\n | % { iex \"git checkout $_\" } <# execute ' git checkout <branch>' #>\n}\n" }, { "answer_id": 41082358, "author": "Albert.Qing", "author_id": 770627, "author_profile": "https://Stackoverflow.com/users/770627", "pm_score": 4, "selected": false, "text": "#!/bin/bash\nfor branch in `git branch -a | grep remotes | grep -v HEAD | grep -v master `; do\n git branch --track ${branch#remotes/origin/} $branch\ndone\n" }, { "answer_id": 42428398, "author": "raisercostin", "author_id": 99248, "author_profile": "https://Stackoverflow.com/users/99248", "pm_score": 4, "selected": false, "text": "git clone --mirror git://example.com/myproject myproject-local-bare-repo.git\n git clone --mirror git://example.com/myproject myproject/.git\ncd myproject\ngit config --unset core.bare\ngit config receive.denyCurrentBranch updateInstead\ngit checkout master\n" }, { "answer_id": 43551285, "author": "ashes999", "author_id": 210780, "author_profile": "https://Stackoverflow.com/users/210780", "pm_score": 3, "selected": false, "text": "git fetch <origin-name> <branch-name>" }, { "answer_id": 45257871, "author": "Alireza", "author_id": 5423108, "author_profile": "https://Stackoverflow.com/users/5423108", "pm_score": 4, "selected": false, "text": "git branch --all git branch --all git branch -a git fetch git fetch && git checkout your_branch_name" }, { "answer_id": 50534323, "author": "Bernd Jungblut", "author_id": 1106617, "author_profile": "https://Stackoverflow.com/users/1106617", "pm_score": 4, "selected": false, "text": "git clone --mirror git clone --mirror /path/to/original.git\ngit remote set-url origin /path/to/new-repo.git\ngit push -u origin\n" }, { "answer_id": 53684037, "author": "lacostenycoder", "author_id": 3625433, "author_profile": "https://Stackoverflow.com/users/3625433", "pm_score": 2, "selected": false, "text": "mkdir somerepo\ncd somerepo\n git clone --bare [email protected]:someuser/somerepo.git .git\ngit config --bool core.bare false\ngit reset --hard\ngit branch\n" }, { "answer_id": 56687773, "author": "konsolebox", "author_id": 445221, "author_profile": "https://Stackoverflow.com/users/445221", "pm_score": 3, "selected": false, "text": "git branch -r | awk -F/ '{ system(\"git checkout \" $NF) }'\n git checkout -b <branch> -t <remote>/<branch> git branch -r | awk '{ system(\"git checkout -t \" $NF) }'\n git config --global alias.clone-branches '! git branch -r | awk -F/ \"{ system(\\\"git checkout \\\" \\$NF) }\"'\ngit config --global alias.clone-branches '! git branch -r | awk \"{ system(\\\"git checkout -t \\\" \\$NF) }\"'\n track-all track-all-branches" }, { "answer_id": 58101436, "author": "Tony Barganski", "author_id": 2305748, "author_profile": "https://Stackoverflow.com/users/2305748", "pm_score": 4, "selected": false, "text": "git clone http://[email protected]\n git pull --all\n git branch -a checkout git pull --all remote/origin remote/origin branches $ for i in $(git branch -a |grep 'remotes' | awk -F/ '{print $3}' \\ \n| grep -v 'HEAD ->');do git checkout -b $i --track origin/$i; done\n for i in $(git branch -a |grep 'remotes' |grep -v 'HEAD ->');do \\\nbasename ${i##\\./} | xargs -I {} git checkout -b {} --track origin/{}; done\n checkout remote/origin/<branchname> --track remote/origin git pull" }, { "answer_id": 58218112, "author": "Marcelo Viana", "author_id": 3880899, "author_profile": "https://Stackoverflow.com/users/3880899", "pm_score": -1, "selected": false, "text": "sudo git clone https://github.com/marceloviana/allBranches.git && sudo cp -rfv allBranches/allBranches.sh /usr/bin/allBranches && sudo chmod +x /usr/bin/allBranches && sudo rm -rf allBranches\n ~$ allBranches /var/www/myproject1/\n ~$ allBranches /var/www/myproject2/\n ~$ allBranches ./\n ~$ allBranches .\n git branch\n" }, { "answer_id": 62977519, "author": "Vopel", "author_id": 11777065, "author_profile": "https://Stackoverflow.com/users/11777065", "pm_score": 0, "selected": false, "text": "function Invoke-GitCloneAll($url) {\n $repo = $url.Split('/')[-1].Replace('.git', '')\n $repo_d = Join-Path $pwd $repo\n if (Test-Path $repo_d) {\n Write-Error \"fatal: destination path '$repo_d' already exists and is not an empty directory.\" -ErrorAction Continue\n } else {\n Write-Host \"`nCloning all branches of $repo...\"\n git -c fetch.prune=false clone $url -q --progress &&\n git -c fetch.prune=false --git-dir=\"$(Join-Path $repo_d '.git')\" --work-tree=\"$repo_d\" pull --all\n Write-Host \"\" #newline\n }\n}\n -c fetch.prune=false && git pull" }, { "answer_id": 63061894, "author": "jasonleonhard", "author_id": 1783588, "author_profile": "https://Stackoverflow.com/users/1783588", "pm_score": 1, "selected": false, "text": "gitCloneAllBranches() { # clone all git branches at once easily and cd in\n # clone as \"bare repo\"\n git clone --mirror $1\n # rename without .git extension\n with_extension=$(basename $1)\n without_extension=$(echo $with_extension | sed 's/.git//')\n mv $with_extension $without_extension\n cd $without_extension\n # change from \"bare repository\" to not\n git config --bool core.bare false\n # check if still bare repository if so\n if [[ $(git rev-parse --is-bare-repository) == false ]]; then\n echo \"ready to go\"\n else\n echo \"WARNING: STILL BARE GIT REPOSITORY\"\n fi\n # EXAMPLES:\n # gitCloneAllBranches https://github.com/something/something.git\n}\n" }, { "answer_id": 63134844, "author": "Astor", "author_id": 9326701, "author_profile": "https://Stackoverflow.com/users/9326701", "pm_score": 2, "selected": false, "text": "git merge path/to/source.git --mirror\ncd source.git\ngit remote remove origin\ngit remote add origin path/to/target.git\ngit push origin --all\ngit push origin --tags\n" }, { "answer_id": 63970897, "author": "STREET MONEY", "author_id": 9082515, "author_profile": "https://Stackoverflow.com/users/9082515", "pm_score": 1, "selected": false, "text": "mkdir -p -- newproject_folder\ncd newproject_folder\ngit clone --mirror https://github.com/USER_NAME/RepositoryName.git .git\ngit config --bool core.bare false\ngit reset --hard\n" }, { "answer_id": 68359412, "author": "Victor Mwenda", "author_id": 3131579, "author_profile": "https://Stackoverflow.com/users/3131579", "pm_score": 0, "selected": false, "text": "git clone --bare remote-repo-url.git localdirname/.git\n cd localdirname\n git config --bool core.bare false\n git reset --hard\n git branch -al\n" }, { "answer_id": 68582362, "author": "Devin Rhode", "author_id": 565877, "author_profile": "https://Stackoverflow.com/users/565877", "pm_score": 3, "selected": false, "text": "mkdir -p -- myapp-mirror\ncd myapp-mirror\ngit clone --mirror https://git.myco.com/group/myapp.git .git\ngit config --bool core.bare false\ngit config --bool core.logAllRefUpdates true\ngit reset --hard # restore working directory\n git log -S\"specialVar\" git config --unset remote.origin.mirror\n master git clone --mirror" }, { "answer_id": 69055255, "author": "Ricardo", "author_id": 2571805, "author_profile": "https://Stackoverflow.com/users/2571805", "pm_score": 3, "selected": false, "text": "$ git clone https://github.com/BrandonBlair/elegantframeworks.git\n\n$ git branch -a\n\n* master\n remotes/origin/HEAD -> origin/master\n remotes/origin/config_recipe\n remotes/origin/functionaltests\n remotes/origin/master\n remotes/origin/parallel\n remotes/origin/parametrize\n remotes/origin/parametrize_data_excel\n remotes/origin/unittesting\n remotes/origin/unittesting1\n git checkout $ for b in `git branch -a | cut -c18- | cut -d\\ -f1`; do git checkout $b; git stash; done\n $ git branch -a\n\n config_recipe\n functionaltests\n master\n parallel\n parametrize\n parametrize_data_excel\n unittesting\n* unittesting1\n remotes/origin/HEAD -> origin/master\n remotes/origin/config_recipe\n remotes/origin/functionaltests\n remotes/origin/master\n remotes/origin/parallel\n remotes/origin/parametrize\n remotes/origin/parametrize_data_excel\n remotes/origin/unittesting\n remotes/origin/unittesting1\n remotes/origin/ grep HEAD cut git checkout" }, { "answer_id": 73141359, "author": "CervEd", "author_id": 1507124, "author_profile": "https://Stackoverflow.com/users/1507124", "pm_score": 1, "selected": false, "text": "origin pattern #!/bin/sh\ngit fetch --all\ngit for-each-ref --format='%(refname:short)' refs/remotes/origin/pattern |\\\n sed 's@\\(origin/\\)\\(.*\\)@\\2\\t\\1\\2@' |\\\n xargs -n 2 git branch --track\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/117/" ]
67,706
<p>Has anyone come up with a good way of performing full text searches (<code>FREETEXT() CONTAINS()</code>) for any number of arbitrary keywords using standard LinqToSql query syntax?</p> <p>I'd obviously like to avoid having to use a Stored Proc or have to generate a Dynamic SQL calls.</p> <p>Obviously I could just pump the search string in on a parameter to a SPROC that uses FREETEXT() or CONTAINS(), but I was hoping to be more creative with the search and build up queries like:</p> <p>"pepperoni pizza" and burger, not "apple pie".</p> <p>Crazy I know - but wouldn't it be neat to be able to do this directly from LinqToSql? Any tips on how to achieve this would be much appreciated.</p> <p>Update: I think I may be on to something <a href="http://tomasp.net/blog/linq-expand-update.aspx" rel="nofollow noreferrer">here</a>...</p> <p>Also: I rolled back the change made to my question title because it actually changed the meaning of what I was asking. I <em>know</em> that full text search is not supported in LinqToSql - I would have asked that question if I wanted to know that. Instead - I have updated my title to appease the edit-happy-trigger-fingered masses.</p>
[ { "answer_id": 361690, "author": "LaserJesus", "author_id": 45207, "author_profile": "https://Stackoverflow.com/users/45207", "pm_score": 3, "selected": false, "text": "string q = query.Query;\nIQueryable<Story> stories = ActiveStories\n .Join(tvf_SearchStories(q), o => o.StoryId, i => i.StoryId, (o,i) => o)\n .Where (s => (query.CategoryIds.Contains(s.CategoryId)) &&\n /* time frame filter */\n (s.PostedOn >= (query.Start ?? SqlDateTime.MinValue.Value)) &&\n (s.PostedOn <= (query.End ?? SqlDateTime.MaxValue.Value)));\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1107/" ]
67,713
<p>In Google Reader, you can use a bookmarklet to "note" a page you're visiting. When you press the bookmarklet, a little Google form is displayed on top of the current page. In the form you can enter a description, etc. When you press Submit, the form submits itself without leaving the page, and then the form disappears. All in all, a very smooth experience.</p> <p>I obviously tried to take a look at how it's done, but the most interesting parts are minified and unreadable. So...</p> <p>Any ideas on how to implement something like this (on the browser side)? What issues are there? Existing blog posts describing this?</p>
[ { "answer_id": 67897, "author": "Sam Hasler", "author_id": 2541, "author_profile": "https://Stackoverflow.com/users/2541", "pm_score": 0, "selected": false, "text": "createElement appendChild insertBefore" }, { "answer_id": 68110, "author": "Anutron", "author_id": 10071, "author_profile": "https://Stackoverflow.com/users/10071", "pm_score": 3, "selected": true, "text": "javascript:void((function(){\n var e=document.createElement('script');\n e.setAttribute('type','text/javascript');\n e.setAttribute('src','http://www.iminta.com/javascripts/new_bookmarklet.js?noCache='+new%20Date().getTime());\n document.body.appendChild(e)\n})())\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10155/" ]
67,734
<p>I'd like to execute JavaScript code from within a C# assembly and have the results of the JavaScript code returned to the calling C# code.</p> <p>It's easier to define things that I'm not trying to do:</p> <ul> <li><p>I'm not trying to call a JavaScript function on a web page from my code behind.</p></li> <li><p>I'm not trying to load a WebBrowser control.</p></li> <li><p>I don't want to have the JavaScript perform an AJAX call to a server.</p></li> </ul> <p>What I want to do is write unit tests in JavaScript and have then unit tests output JSON, even plain text would be fine. Then I want to have a generic C# class/executible that can load the file containing the JS, run the JS unit tests, scrap/load the results, and return a pass/fail with details during a post-build task.</p> <p>I think it's possible using the old ActiveX ScriptControl, but it seems like there ought to be a .NET way to do this without using SilverLight, the DLR, or anything else that hasn't shipped yet. Anyone have any ideas?</p> <p>update: <a href="http://blogs.msdn.com/brada/articles/239857.aspx" rel="nofollow noreferrer">From Brad Abrams blog</a></p> <pre><code>namespace Microsoft.JScript.Vsa { [Obsolete("There is no replacement for this feature. " + "Please see the ICodeCompiler documentation for additional help. " + "http://go.microsoft.com/fwlink/?linkid=14202")] </code></pre> <p>Clarification: We have unit tests for our JavaScript functions that are written in JavaScript using the JSUnit framework. Right now during our build process, we have to manually load a web page and click a button to ensure that all of the JavaScript unit tests pass. I'd like to be able to execute the tests during the post-build process when our automated C# unit tests are run and report the success/failure alongside of out C# unit tests and use them as an indicator as to whether or not the build is broken.</p>
[ { "answer_id": 67786, "author": "scubabbl", "author_id": 9450, "author_profile": "https://Stackoverflow.com/users/9450", "pm_score": 3, "selected": false, "text": "<add assembly=\"Microsoft.Vsa, Version=8.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A\"/></assemblies>\n using Microsoft.JScript;\n\npublic class MyClass {\n\n public static Microsoft.JScript.Vsa.VsaEngine Engine = Microsoft.JScript.Vsa.VsaEngine.CreateEngine();\n\n public static object EvaluateScript(string script)\n {\n object Result = null;\n try\n {\n Result = Microsoft.JScript.Eval.JScriptEvaluate(JScript, Engine);\n }\n catch (Exception ex)\n {\n return ex.Message;\n }\n\n return Result;\n }\n\n public void MyMethod() {\n string myscript = ...;\n object myresult = EvaluateScript(myscript);\n }\n}\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1538/" ]
67,736
<p>I have a service contract that defines a method with a parameter of type System.Object (xs:anyType in the WSDL). I want to be able to pass simple types as well as complex types in this parameter. Simple types work fine, but when I try to pass a complex type that is defined in my WSDL, I get this error:</p> <p>Element '<a href="http://tempuri.org/:value" rel="nofollow noreferrer">http://tempuri.org/:value</a>' contains data of the '<a href="http://schemas.datacontract.org/2004/07/MyNamespace:MyClass" rel="nofollow noreferrer">http://schemas.datacontract.org/2004/07/MyNamespace:MyClass</a>' data contract. The deserializer has no knowledge of any type that maps to this contract. Add the type corresponding to 'MyClass' to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding it to the list of known types passed to DataContractSerializer.</p> <p>Adding it as a known type doesn't help because it's already in my WSDL. How can I pass an object of a complex type via an "xs:anyType" parameter?</p> <p>More info:</p> <p>I believe this works when using NetDataContract, but I can't use that because my client is Silverlight.</p> <p>I have seen references to complex types explicitly extending xs:anyType, but I have no idea how to make WCF generate a WSDL that does that, and I have no idea whether or not it would even help.</p> <p>Thanks</p>
[ { "answer_id": 81286, "author": "sajidnizami", "author_id": 9498, "author_profile": "https://Stackoverflow.com/users/9498", "pm_score": 1, "selected": false, "text": "public ServiceDataContract() { }\n\npublic ServiceDataContract(TValueType Value)\n{\n this.m_objValue = Value;\n}\n\nprivate TValueType m_objValue;\n\n[DataMember(IsRequired = true, Name = \"Value\", Order = 1)]\npublic TValueType Value\n{\n get { return m_objValue; }\n set { m_objValue = value; }\n}\n public ServiceDataContract<string[]> GetStrings()\n{\n string[] temp = new string[10];\n return new ServiceDataContract<string[]>(temp);\n}\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10391/" ]
67,760
<p>Has anyone got <a href="http://perldoc.perl.org/Sys/Syslog.html" rel="nofollow noreferrer">Sys::Syslog</a> to work on Solaris? (I'm running Sys::Syslog 0.05 on Perl v5.8.4 on SunOS 5.10 on SPARC). Here's what doesn't work for me:</p> <pre><code>openlog "myprog", "pid", "user" or die; syslog "crit", "%s", "Test from $0" or die; closelog() or warn "Can't close: $!"; system "tail /var/adm/messages"; </code></pre> <p>Whatever I do, the closelog returns an error and nothing ever gets logged anywhere.</p>
[ { "answer_id": 68121, "author": "rjbs", "author_id": 10478, "author_profile": "https://Stackoverflow.com/users/10478", "pm_score": 2, "selected": false, "text": "[ 'tcp', 'udp', 'unix', 'stream' ]\n setlogsock('inet', $hostname);\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
67,761
<p>Despite the documentation, NetworkStream.Write does not appear to wait until the data has been sent. Instead, it waits until the data has been copied to a buffer and then returns. That buffer is transmitted in the background.</p> <p>This is the code I have at the moment. Whether I use ns.Write or ns.BeginWrite doesn't matter - both return immediately. The EndWrite also returns immediately (which makes sense since it is writing to the send buffer, not writing to the network).</p> <pre><code> bool done; void SendData(TcpClient tcp, byte[] data) { NetworkStream ns = tcp.GetStream(); done = false; ns.BeginWrite(bytWriteBuffer, 0, data.Length, myWriteCallBack, ns); while (done == false) Thread.Sleep(10); }   public void myWriteCallBack(IAsyncResult ar) { NetworkStream ns = (NetworkStream)ar.AsyncState; ns.EndWrite(ar); done = true; } </code></pre> <p>How can I tell when the data has actually been sent to the client?</p> <p>I want to wait for 10 seconds(for example) for a response from the server after sending my data otherwise I'll assume something was wrong. If it takes 15 seconds to send my data, then it will always timeout since I can only start counting from when NetworkStream.Write returns - which is before the data has been sent. I want to start counting 10 seconds from when the data has left my network card.</p> <p>The amount of data and the time to send it could vary - it could take 1 second to send it, it could take 10 seconds to send it, it could take a minute to send it. The server does send an response when it has received the data (it's a smtp server), but I don't want to wait forever if my data was malformed and the response will never come, which is why I need to know if I'm waiting for the data to be sent, or if I'm waiting for the server to respond.</p> <p>I might want to show the status to the user - I'd like to show "sending data to server", and "waiting for response from server" - how could I do that?</p>
[ { "answer_id": 67773, "author": "palehorse", "author_id": 312, "author_profile": "https://Stackoverflow.com/users/312", "pm_score": 0, "selected": false, "text": "ns.Flush()\n" }, { "answer_id": 67856, "author": "sbeskur", "author_id": 10446, "author_profile": "https://Stackoverflow.com/users/10446", "pm_score": -1, "selected": false, "text": "tcp.NoDelay = true" }, { "answer_id": 68166, "author": "Alex Lyman", "author_id": 5897, "author_profile": "https://Stackoverflow.com/users/5897", "pm_score": 1, "selected": false, "text": "void SendData(TcpClient tcp, byte[] data) {\n NetworkStream ns = tcp.GetStream();\n // BUG?: should bytWriteBuffer == data?\n IAsyncResult r = ns.BeginWrite(bytWriteBuffer, 0, data.Length, null, null);\n r.AsyncWaitHandle.WaitOne();\n ns.EndWrite(r);\n}\n" }, { "answer_id": 79676, "author": "Glyph", "author_id": 13564, "author_profile": "https://Stackoverflow.com/users/13564", "pm_score": 4, "selected": false, "text": "Write Read" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4495/" ]
67,790
<p>I have some code with multiple functions very similar to each other to look up an item in a list based on the contents of one field in a structure. The only difference between the functions is the type of the structure that the look up is occurring in. If I could pass in the type, I could remove all the code duplication.</p> <p>I also noticed that there is some mutex locking happening in these functions as well, so I think I might leave them alone...</p>
[ { "answer_id": 67838, "author": "Charles Graham", "author_id": 7705, "author_profile": "https://Stackoverflow.com/users/7705", "pm_score": -1, "selected": false, "text": "void foo(void* obj);\n\nvoid main()\n{\n struct bla obj;\n ...\n foo(&obj);\n ...\n}\n\nvoid foo(void* obj)\n{\n printf(obj -> x, \"%s\")\n}\n" }, { "answer_id": 67842, "author": "tialaramex", "author_id": 9654, "author_profile": "https://Stackoverflow.com/users/9654", "pm_score": 3, "selected": false, "text": "struct person {\n int index;\n};\n\nstruct clown {\n int index;\n char *hat;\n};\n\n/* we're not going to define a firetruck here */\nstruct firetruck;\n\n\nstruct fireman {\n int index;\n struct firetruck *truck;\n};\n\nint getindexof(struct person *who)\n{\n return who->index;\n}\n\nint main(int argc, char *argv[])\n{\n struct fireman sam;\n /* somehow sam gets initialised */\n sam.index = 5;\n\n int index = getindexof((struct person *) &sam);\n printf(\"Sam's index is %d\\n\", index);\n\n return 0;\n}\n" }, { "answer_id": 67903, "author": "Gordon Wrigley", "author_id": 10471, "author_profile": "https://Stackoverflow.com/users/10471", "pm_score": 0, "selected": false, "text": "\n#include \n#define getfield(s, name) ((s).name)\n\ntypedef struct{\n int x;\n}Bob;\n\ntypedef struct{\n int y;\n}Fred;\n\nint main(int argc, char**argv){\n Bob b;\n b.x=6;\n\n Fred f;\n f.y=7;\n\n printf(\"%d, %d\\n\", getfield(b, x), getfield(f, y));\n}\n" }, { "answer_id": 68003, "author": "gnkdl_gansklgna", "author_id": 10470, "author_profile": "https://Stackoverflow.com/users/10470", "pm_score": 0, "selected": false, "text": "callFuncWithInputThenOutput(input, &struct.output);" }, { "answer_id": 96369, "author": "fizzer", "author_id": 18167, "author_profile": "https://Stackoverflow.com/users/18167", "pm_score": 1, "selected": false, "text": "#include <stdio.h>\n\ntypedef struct\n{\n int id;\n int junk1;\n} Foo;\n\ntypedef struct\n{\n int id;\n long junk2;\n} Bar;\n\ntypedef union\n{\n struct\n {\n int id;\n } common;\n\n Foo foo;\n Bar bar;\n} U;\n\nint matches(const U *candidate, int wanted)\n{\n return candidate->common.id == wanted;\n}\n\nint main(void)\n{\n Foo f = { 23, 0 };\n Bar b = { 42, 0 };\n\n U fu;\n U bu;\n\n fu.foo = f;\n bu.bar = b;\n\n puts(matches(&fu, 23) ? \"true\" : \"false\");\n puts(matches(&bu, 42) ? \"true\" : \"false\");\n\n return 0;\n}\n #include <stddef.h>\n#include <stdio.h>\n\ntypedef struct\n{\n int id;\n int junk1;\n} Foo;\n\ntypedef struct\n{\n int junk2;\n int id;\n} Bar;\n\nint matches(const void* candidate, size_t idOffset, int wanted)\n{\n return *(int*)((const unsigned char*)candidate + idOffset) == wanted;\n}\n\n#define MATCHES(type, candidate, wanted) matches(candidate, offsetof(type, id), wanted)\n\nint main(void)\n{\n Foo f = { 23, 0 };\n Bar b = { 0, 42 };\n puts(MATCHES(Foo, &f, 23) ? \"true\" : \"false\");\n puts(MATCHES(Bar, &b, 42) ? \"true\" : \"false\");\n\n return 0;\n}\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10394/" ]
67,798
<p>I'm looking for a multiline regex that will match occurrences after a blank line. For example, given a sample email below, I'd like to match "From: Alex". <code>^From:\s*(.*)$</code> works to match any From line, but I want it to be restricted to lines in the body (anything after the first blank line).</p> <pre> Received: from a server Date: today To: Ted From: James Subject: [fwd: hi] fyi ----- Forwarded Message ----- To: James From: Alex Subject: hi Party! </pre>
[ { "answer_id": 67843, "author": "Loren Segal", "author_id": 6436, "author_profile": "https://Stackoverflow.com/users/6436", "pm_score": 3, "selected": true, "text": "\\A.*?\\r?\\n\\r?\\n.*?^From:\\s*([^\\r\\n]+)$\n" }, { "answer_id": 67862, "author": "gregmac", "author_id": 7913, "author_profile": "https://Stackoverflow.com/users/7913", "pm_score": 0, "selected": false, "text": "(?<=\\n\\n).*(From:\\s*(.*?))$\n" }, { "answer_id": 68031, "author": "Teetow", "author_id": 10541, "author_profile": "https://Stackoverflow.com/users/10541", "pm_score": 0, "selected": false, "text": "\\s{2,}.+?(.+?From:\\s(?<Sender>.+?)\\s)+?\n \\s{2,} RegexOptions.SingleLine RegexOptions.ExplicitCapture" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10392/" ]
67,810
<p>I would like to debug my separately running JSP/Struts/Tomcat/Hibernate application stack using the Eclipse IDE debugger. How do I setup the java JVM and eclipse so that I can set breakpoints, monitor variable values, and see the code that is currently executing?</p>
[ { "answer_id": 67927, "author": "Dónal", "author_id": 2648, "author_profile": "https://Stackoverflow.com/users/2648", "pm_score": 1, "selected": false, "text": "java" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10402/" ]
67,819
<p>In php, how can I get the number of apache children that are currently available <br>(<code>status = SERVER_READY</code> in the apache scoreboard)?</p> <p>I'm really hoping there is a simple way to do this in php that I am missing.</p>
[ { "answer_id": 67832, "author": "ceejayoz", "author_id": 1902010, "author_profile": "https://Stackoverflow.com/users/1902010", "pm_score": 2, "selected": false, "text": "ps aux | grep httpd ps aux | grep apache exec('ps aux | grep apache', $output);\n$processes = count($output);\n" }, { "answer_id": 67990, "author": "giltotherescue", "author_id": 8215, "author_profile": "https://Stackoverflow.com/users/8215", "pm_score": 1, "selected": false, "text": "<?php\n\n$status = file('http://yourserver/server-status?auto');\nforeach ($status as $line) {\n if (substr($line, 0, 10) == 'IdleWorkers') {\n $idle_workers = trim(substr($line, 12));\n print $idle_workers;\n break;\n }\n}\n\n?>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]