qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
293,342
<p>I am using HtmlAgilityPack. I create an HtmlDocument and LoadHtml with the following string:</p> <pre><code>&lt;select id="foo_Bar" name="foo.Bar"&gt;&lt;option selected="selected" value="1"&gt;One&lt;/option&gt;&lt;option value="2"&gt;Two&lt;/option&gt;&lt;/select&gt; </code></pre> <p>This does some unexpected things. First, it gives two parser errors, EndTagNotRequired. Second, the select node has 4 children - two for the option tags and two more for the inner text of the option tags. Last, the OuterHtml is like this:</p> <pre><code>&lt;select id="foo_Bar" name="foo.Bar"&gt;&lt;option selected="selected" value="1"&gt;One&lt;option value="2"&gt;Two&lt;/select&gt; </code></pre> <p>So basically it is deciding for me to drop the closing tags on the options. Let's leave aside for a moment whether it is proper and desirable to do that. I am using HtmlAgilityPack to test HTML generation code, so I don't want it to make any decision for me or give any errors unless the HTML is truly malformed. Is there some way to make it behave how I want? I tried setting some of the options for HtmlDocument, specifically:</p> <pre><code> doc.OptionAutoCloseOnEnd = false; doc.OptionCheckSyntax = false; doc.OptionFixNestedTags = false; </code></pre> <p>This is not working. If HtmlAgilityPack cannot do what I want, can you recommend something that can?</p>
[ { "answer_id": 293357, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 6, "selected": true, "text": "// they sometimes contain, and sometimes they don 't...\nElementsFlags.Add(\"option\", HtmlElementFlag.Empty);\n HtmlNode.ElementsFlags.Remove(\"option\");" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29493/" ]
293,344
<p>I am making a little GUI frontend for a app at the moment using wxPython.</p> <p>I am using <code>wx.StaticText()</code> to create a place to hold some text, code below:</p> <pre><code>content = wx.StaticText(panel, -1, "Text Here", style=wx.ALIGN_CENTRE) </code></pre> <p>I have a button when clicked retrieves data from MySQL, I am wanting to change the value of the <code>StaticText()</code> to the MySQL data or what else could I use the hold the data.</p> <p>I have tried using the below method: </p> <pre><code>contents = wx.TextCtrl(bkg, style=wx.TE_MULTILINE | wx.HSCROLL) content.SetValue("New Text") </code></pre> <p>This displays the data fine but after the data is loaded you can edit the data and I do not want this.</p> <p>Hope you guys understand what I am trying to do, I am new to Python :)</p> <p>Cheers</p>
[ { "answer_id": 293350, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 6, "selected": true, "text": "wx.TextCtrl wx.TE_READONLY" }, { "answer_id": 294100, "author": "DrBloodmoney", "author_id": 35681, "author_profile": "https://Stackoverflow.com/users/35681", "pm_score": 6, "selected": false, "text": "def __init__(self, parent, *args, **kwargs): #frame constructor, etc.\n self.some_text = wx.StaticText(panel, wx.ID_ANY, label=\"Awaiting MySQL Data\", style=wx.ALIGN_CENTER)\n\ndef someFunction(self):\n mysql_data = databasemodel.returnData() #query your database to return a string\n self.some_text.SetLabel(mysql_data)\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30786/" ]
293,345
<p>I'm using the lines functionality to take an input and split up many variables before sending it off to a function. Please look at the run function and tell me why I get the following error. It seems like it should just assign the first string in ln to seq, but I get an error.</p> <pre> ERROR:dishonest.hs:33:11: Couldn't match expected type `[t]' against inferred type `Char' In a 'do' expression: seq &lt;- ln !! 0 In the expression: do ln &lt;- lines s seq &lt;- ln !! 0 states &lt;- ln !! 1 l1 &lt;- listDouble (ln !! 2) .... In the definition of `run': run s = do ln &lt;- lines s seq &lt;- ln !! 0 states &lt;- ln !! 1 .... code follows... <code> import Char maximumInd :: (Double, Double) -> Int maximumInd (d1,d2) | maximum [d1,d2] == d1 = 1 | maximum [d1,d2] == d2 = 2 scoreFunction :: String -> Int -> [Double] -> [Double] -> Double -> Double -> (Double,Double) scoreFunction string (-1) l1 l2 t1 t2 = (0.5, 0.5) scoreFunction string index l1 l2 t1 t2 = ((fst (scoreFunction string (index-1) l1 l2 t1 t2)) * (l1!!num) * (tr (maximumInd (scoreFunction string (index-1) l1 l2 t1 t2))!!1), (snd (scoreFunction string (index-1) l1 l2 t1 t2)) * (l2!!num) * (tr (maximumInd (scoreFunction string (index-1) l1 l2 t1 t2))!!2)) where num = digitToInt (string!!index) tr n | n == 1 = l1 | n == 2 = l2 --split is stolen from teh webs http://julipedia.blogspot.com/2006/08/split-function-in-haskell.html split :: String -> Char -> [String] split [] delim = [""] split (c:cs) delim | c == delim = "" : rest | otherwise = (c : head rest) : tail rest where rest = split cs delim readDouble :: String -> Double readDouble s = read s :: Double listDouble :: String -> [Double] listDouble s = map readDouble $ split s ' ' run :: String -> String run s = do ln &lt;- lines s seq &lt;- ln!!0 states &lt;- ln!!1 l1 &lt;- listDouble (ln!!2) l2 &lt;- listDouble (ln!!3) tr1 &lt;- readDouble (ln!!4) tr2 &lt;- readDouble (ln!!5) show maximumInd (scoreFunction seq (length seq) l1 l2 tr1 tr2) main = do putStrLn "Please compose a test job for Viterbi." putStrLn "First line: A sequence with language [1,9]." putStrLn "Second line: The number of states." putStrLn "For the next 2 lines: space delimited emission probabilities." putStrLn "For the 2 lines after that, transmission probabilities." putStrLn "Then do ./casino &lt; filename " interact run </code></pre>
[ { "answer_id": 293379, "author": "mipadi", "author_id": 28804, "author_profile": "https://Stackoverflow.com/users/28804", "pm_score": 0, "selected": false, "text": "<-" }, { "answer_id": 293397, "author": "Alasdair", "author_id": 2654, "author_profile": "https://Stackoverflow.com/users/2654", "pm_score": 0, "selected": false, "text": "instance Monad [] where\n m >>= f = concatMap f m\n return x = [x]\n fail s = []\n do {ln <- lines \"hello, world\"; ln!!0}\n lines \"hello world\" >>= (\\ln -> ln!!0)\n lines \"hello world\" >>= (!!0)\n concatMap (!!0) (lines \"hello, world\")\n concat $ map (!!0) (lines \"hello, world\")\n run :: String -> String\nrun s = let ln = lines s\n seq = ln!!0\n states = ln!!1\n l1 = listDouble (ln!!2)\n l2 = listDouble (ln!!3)\n tr1 = readDouble (ln!!4)\n tr2 = readDouble (ln!!5)\n in show $ maximumInd (scoreFunction seq (length seq) l1 l2 tr1 tr2)\n" }, { "answer_id": 293398, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 0, "selected": false, "text": "run s = do\n ln <- lines s\n seq <- ln!!0\n states <- ln!!1\n lines s <-" }, { "answer_id": 293404, "author": "CesarB", "author_id": 28258, "author_profile": "https://Stackoverflow.com/users/28258", "pm_score": 3, "selected": false, "text": "run :: String -> String\n String [Char] run s = do\n ln <- lines s\n ...\n do Monad (Monad t) => t a [Char] do [Char] Monad [] [a] [] a IO [] <- [a] do ln <- lines s\n [[Char]] ln [Char] seq <- ln!!0\n ln!!0 Char [] do let run :: String -> String\nrun s = let\n ln = lines s\n seq = ln!!0\n states = ln!!1\n l1 = listDouble (ln!!2)\n l2 = listDouble (ln!!3)\n tr1 = readDouble (ln!!4)\n tr2 = readDouble (ln!!5)\n in show maximumInd (scoreFunction seq (length seq) l1 l2 tr1 tr2)\n" }, { "answer_id": 293468, "author": "ja.", "author_id": 15467, "author_profile": "https://Stackoverflow.com/users/15467", "pm_score": 0, "selected": false, "text": " t = \"[1,9]\\n3\\n1.0 1.0 1.0\\n1.0 1.0 1.0\\n1.0\\n1.0\" \n ln = lines t\nseq = ln!!0\nstates = ln!!1\nl1 = listDouble (ln!!2)\nl2 = listDouble (ln!!3)\ntr1 = readDouble (ln!!4)\ntr2 = readDouble (ln!!5) \n :t scoreFunction\n :t scoreFunction \"\"\n :t scoreFunction 3445\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37840/" ]
293,351
<p>I have an owner-drawn UserControl where I've implemented double-buffering. In order to get double-buffering to work without flicker, I have to override the OnPaintBackground event like so:</p> <pre><code>protected override void OnPaintBackground(PaintEventArgs e) { // don't even have to do anything else } </code></pre> <p>This works great at runtime. The problem is that when I have an instance of the control on a form at design time, it becomes a black hole that shows trails of whatever windows are dragged over it (because the override of the OnPaintBackground event also governs design-time appearance). It's just a cosmetic problem, but it's visually jarring and it always leads new developers on the project to assume something has gone horribly wrong.</p> <p>Is there any way to have an overridden method like this not be overridden at design time, or is there another solution?</p>
[ { "answer_id": 293358, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 2, "selected": false, "text": "if (this.DesignMode)\n{\n return; //or call base.OnPaintBackground()\n}\n" }, { "answer_id": 1369084, "author": "greggorob64", "author_id": 95652, "author_profile": "https://Stackoverflow.com/users/95652", "pm_score": 3, "selected": true, "text": " if(this->DesignMode || \n LicenseManager::UsageMode == LicenseUsageMode::Designtime) \n return;\n" }, { "answer_id": 2195338, "author": "Marcel", "author_id": 79485, "author_profile": "https://Stackoverflow.com/users/79485", "pm_score": 2, "selected": false, "text": "greggorob64 if (DesignMode || LicenseManager.UsageMode == LicenseUsageMode.Designtime) \n{\n return;\n}\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14606/" ]
293,353
<p>Method chaining is the only way I know to build fluent interfaces.</p> <p>Here's an example in C#:</p> <pre><code>John john = new JohnBuilder() .AddSmartCode(&quot;c#&quot;) .WithfluentInterface(&quot;Please&quot;) .ButHow(&quot;Dunno&quot;); Assert.IsNotNull(john); [Test] public void Should_Assign_Due_Date_With_7DayTermsVia_Invoice_Builder() { DateTime now = DateTime.Now; IInvoice invoice = new InvoiceBuilder() .IssuedOn(now) .WithInvoiceNumber(40) .WithPaymentTerms(PaymentTerms.SevenDays) .Generate(); Assert.IsTrue(invoice.DateDue == now.AddDays(7)); } </code></pre> <p>So how do others create fluent interfaces. How do you create it? What language/platform/technology is needed?</p>
[ { "answer_id": 293365, "author": "Jeff Fritz", "author_id": 29156, "author_profile": "https://Stackoverflow.com/users/29156", "pm_score": 2, "selected": false, "text": "public interface IFoo\n{\n IFoo SetBar(string s);\n IFoo DoStuff();\n IFoo SetColor(Color c);\n}\n" }, { "answer_id": 293367, "author": "JoshBerke", "author_id": 26160, "author_profile": "https://Stackoverflow.com/users/26160", "pm_score": 1, "selected": false, "text": "Tokenizer<Bid> tkn = new Tokenizer<Bid>();\ntkn.Add(Token.LambdaToken<Bid>(\"<YourFullName>\", b => Util.CurrentUser.FullName))\n .Add(Token.LambdaToken<Bid>(\"<WalkthroughDate>\",\n b => b.WalkThroughDate.ToShortDateString()))\n .Add(Token.LambdaToken<Bid>(\"<ContactFullName>\", b => b.Contact.FullName))\n .Cache(\"Bid\")\n .SetPattern(@\"<\\w+>\");\n" }, { "answer_id": 293369, "author": "hangy", "author_id": 11963, "author_profile": "https://Stackoverflow.com/users/11963", "pm_score": 4, "selected": false, "text": "void this public class JohnBuilder\n{\n private IList<string> languages = new List<string>();\n private IList<string> fluentInterfaces = new List<string>();\n private string butHow = string.Empty;\n\n public JohnBuilder AddSmartCode(string language)\n {\n this.languages.Add(language);\n return this;\n }\n\n public JohnBuilder WithFluentInterface(string fluentInterface)\n {\n this.fluentInterfaces.Add(fluentInterface);\n return this;\n }\n\n public JohnBuilder ButHow(string butHow)\n {\n this.butHow = butHow;\n return this;\n }\n}\n\npublic static class MyProgram\n{\n public static void Main(string[] args)\n {\n JohnBuilder johnBuilder = new JohnBuilder().AddSmartCode(\"c#\").WithFluentInterface(\"Please\").ButHow(\"Dunno\");\n }\n}\n" }, { "answer_id": 293370, "author": "Chris Pietschmann", "author_id": 7831, "author_profile": "https://Stackoverflow.com/users/7831", "pm_score": 7, "selected": true, "text": "public class JohnBuilder\n{\n public JohnBuilder AddSmartCode(string s)\n {\n // do something\n return this;\n }\n\n public JohnBuilder WithfluentInterface(string s)\n {\n // do something\n return this;\n }\n\n public JohnBuilder ButHow(string s)\n {\n // do something\n return this;\n }\n}\n John = new JohnBuilder()\n .AddSmartCode(\"c#\")\n .WithfluentInterface(\"Please\")\n .ButHow(\"Dunno\");\n" }, { "answer_id": 293576, "author": "Bevan", "author_id": 30280, "author_profile": "https://Stackoverflow.com/users/30280", "pm_score": 6, "selected": false, "text": "Assert.That( result, Is.EqualTo(4));\n Assert.That( result, Is.EqualTo(4.0).Within(0.01));\n myDocument.Save(\"sampleFile.txt\", FilePermissions.ReadOnly);\n myDocument.Save(file:\"SampleFile.txt\", permissions:FilePermissions.ReadOnly);\n myDocument.Save(toFile:\"SampleFile.txt\", withPermissions:FilePermissions.ReadOnly);\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2041/" ]
293,364
<p>Might it make <strong><em>more</em></strong> sense to put 64-bit applications into "Program Files (x64)" and leave 32-bit applications to run in "Program Files"?</p> <p>I have a batch file that need to run a <a href="http://en.wikipedia.org/wiki/Adobe_Flex" rel="nofollow noreferrer">Flex</a> compiler. In x64, that program is in "Program Files (x86)". On Windows&nbsp;Vista 32-bit, it's in "Program Files" - environment variables? Check it: </p> <pre><code>ProgramFiles=C:\Program Files ProgramFiles(x86)=C:\Program Files (x86) </code></pre> <p>What do I do?</p> <hr> <pre><code>set mxmlc="%ProgramFiles(x86)%\Adobe\Flex Builder 3\sdks\3.1.0\bin\mxmlc.exe" if NOT EXIST %mxmlc% set mxmlc="%ProgramFiles%\Adobe\Flex Builder 3\sdks\3.1.0\bin\mxmlc.exe" </code></pre> <p>tnx</p>
[ { "answer_id": 293466, "author": "Aidan Ryan", "author_id": 1042, "author_profile": "https://Stackoverflow.com/users/1042", "pm_score": 3, "selected": false, "text": "SET ExecPath=%ProgramFiles(x86)%\nIF \"%ExecPath%\"==\"\" SET ExecPath=%ProgramFiles%\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11397/" ]
293,368
<pre><code>Open App.Path &amp; "\Folder\" &amp; str(0) For Output </code></pre> <p>Seems to get a path not found however if directly before that I do</p> <pre><code>MsgBox App.Path &amp; "\Folder\" &amp; str(0) </code></pre> <p>It Provides the correct directory/filename that I want</p> <p>and if I replace that string with the direct path in quotes it works fine however that won't be very good for other users of my app :( Anyone know why this doesn't work? </p>
[ { "answer_id": 294772, "author": "GregUzelac", "author_id": 27068, "author_profile": "https://Stackoverflow.com/users/27068", "pm_score": 2, "selected": false, "text": " Open \"c:\\temp\\test.txt\" & Str(0) For Output As #1\n Close #1\n" }, { "answer_id": 11537531, "author": "Berker Yüceer", "author_id": 861019, "author_profile": "https://Stackoverflow.com/users/861019", "pm_score": 0, "selected": false, "text": "Function CreateLog(Destination As String, MyMessage As String)\n Dim PathToCreate, FolderPath, FileName As String\n\n 'Check for Unnecessary Spaces\n Destination = Trim(Destination)\n FolderStr = Destination\n\n 'Gather only FolderPath of Destination\n Do\n FolderStr = Mid(FolderStr, 1, Len(FolderStr) - 1)\n Loop Until Right(FolderStr, 1) = \"\\\" Or Len(FolderStr) < 1\n\n 'Gather only FileName\n FileName = Mid(Destination, Len(FolderStr) + 1, Len(Destination) - Len(FolderStr))\n\n 'If the path does not exist than create it\n 'Recursive approach\n For Each Folder In Split(FolderStr, \"\\\")\n If InStr(1, Folder, \":\") = 0 Then\n PathToCreate = PathToCreate & \"\\\" & Folder\n Else\n PathToCreate = Folder\n End If\n If fso.FolderExists(PathToCreate) = False And PathToCreate <> \"\" Then\n fso.CreateFolder PathToCreate\n End If\n Next\n\n 'Open file and add the message in it\n Open PathToCreate & \"\\\" & FileName & \".txt\" For Append As #1\n Print #1, MyMessage\n Close #1\n\nEnd Function\n CreateLog \"D:\\Test\\NewTest\\NewFolder\\AnotherFolder\\atlastthefile.abcdefg\", \"Hello!\"\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
293,375
<p>On a site where 90% of the pages use the same libraries, should you just load the libraries all the time or only load them when needed? The other pages would be ajax or simple pages that don't have any real functionality.</p> <p>Also, should you only load the code when needed? If part way down a page you need a library, should you load it then or just load it at the top. Maybe it's possible it may never get there before of an error or wrong data. (Loading at the top makes it somewhat easier to understand, but may result in extra code not needed.)</p> <p>I'm also wondering if I should make the libraries more specific so I'm not say loading the code to edit at the same time as viewing?</p> <p>Basically, how much should I worry about loading code or not loading code?</p>
[ { "answer_id": 293392, "author": "hangy", "author_id": 11963, "author_profile": "https://Stackoverflow.com/users/11963", "pm_score": 4, "selected": true, "text": "include require include_once require_once" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5441/" ]
293,380
<p>I'm just starting out writing trying to write a simple program in C and I am using Visual Studios to do so. I heard that it does compile C as well as C++. And I know that it does because it says it compiles. The only problem is that when I go to the output directory, there isn't a .exe file in the directory! It has the following:</p> <ul> <li>BuildLog.html</li> <li>mt.dep</li> <li>test1.obj</li> <li>vc90.idb</li> <li>vc90.pdb</li> </ul> <p>But that is all! No EXE. I've looked through all the options and made sure that it is set to compile to an exe and i checked the output file. That is $(OutDir)\$(ProjectName).exe. But alas, no exe appears. Any ideas?</p> <p>Also when i try to hit f5 and run with debut i get an error that says</p> <blockquote> <p>This application has failed to start because MSVCR90.DLL was not found. Re-installing the application may fix this problem</p> </blockquote>
[ { "answer_id": 293386, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 2, "selected": false, "text": "#include \"stdafx.h\"\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n printf(\"Hello, world!\\n\");\n return 0;\n}\n" }, { "answer_id": 293407, "author": "ine", "author_id": 4965, "author_profile": "https://Stackoverflow.com/users/4965", "pm_score": 1, "selected": false, "text": "Visual C++ > General > Empty Project Add > New Item main.cpp main.c" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2128/" ]
293,388
<p>I am working on a J2ME project that spawns worker threads for numerous tasks such as downloading HTTP content. The basic thread layout is similar to most java apps--there is a main UI thread and worker threads spawned to do stuff behind the scenes. My question is what is the best way to handle exceptions that occur in the worker threads? </p> <p>I usually adhere to the design rationale that most exceptions should be percolate as far as possible. When I write single threaded apps, it is common for me to percolate the exceptions all the way up to the UI layer and then report them in an error dialog to the user. Is there a similar practice for multithreaded apps? The most intuitive thing to me is to catch exceptions in the Thread.run() and then call an invokeLater on the UI thread to report it in a dialog. The issue I see here is that outside of the worker thread dying off prematurely, this approach does not really notify the UI thread there was an error. I do not see a clear way to throw an exception across threads so to speak.</p> <p>Thanks, Andy</p>
[ { "answer_id": 293483, "author": "Stuph", "author_id": 37996, "author_profile": "https://Stackoverflow.com/users/37996", "pm_score": 3, "selected": false, "text": "/**\n * TWO CHOICES:\n * - Monitor your threads and report errors,\n * - setup a callback to do something.\n */\npublic class ThreadExceptions {\n\n /** Demo of {@link RunnableCatch} */\n public static void main(String[] argv) throws InterruptedException {\n final Runnable bad = new NaughtyThread();\n // safe1 doesnt have a callback\n final RunnableCatch safe1 = new RunnableCatch(bad);\n // safe2 DOES have a callback\n final RunnableCatch safe2 = new RunnableCatch(bad, new RunnableCallback() {\n public void handleException(Runnable runnable, Exception exception) {\n System.out.println(\"Callback handled: \" + exception.getMessage());\n exception.printStackTrace();\n }\n\n });\n final Thread t1 = new Thread(safe1, \"myThread\");\n final Thread t2 = new Thread(safe2, \"myThread\");\n t1.start();\n t2.start();\n t1.join();\n t2.join();\n if (safe1.getException() != null) {\n System.out.println(\"thread finished with exceptions\");\n safe1.getException().printStackTrace();\n }\n System.out.println(\"done\");\n }\n\n\n}\n\n/** Throws an exception 50% of the time */\nclass NaughtyThread implements Runnable {\n public void run() {\n try {\n if (Math.random() > .5) {\n throw new RuntimeException(\"badness\");\n }\n } finally {\n System.out.println(\"ran\");\n }\n }\n}\n\n/** Called when an exception occurs */\ninterface RunnableCallback {\n void handleException(Runnable runnable, Exception exception);\n}\n\n/**\n * Catches exceptions thrown by a Runnable,\n * so you can check/view them later and/or\n * deal with them from some callback.\n */\nclass RunnableCatch implements Runnable {\n\n /** Proxy we will run */\n private final Runnable _proxy;\n\n /** Callback, if any */\n private final RunnableCallback _callback;\n\n /** @guarded-by(this) */\n private Exception _exception;\n\n public RunnableCatch(final Runnable proxy) {\n this(proxy, null);\n }\n\n public RunnableCatch(final Runnable proxy, RunnableCallback target) {\n _proxy = proxy;\n _callback = target;\n }\n\n public void run() {\n try {\n _proxy.run();\n } catch (Exception e) {\n synchronized (this) {\n _exception = e;\n }\n if (_callback != null) {\n _callback.handleException(_proxy, e);\n }\n }\n }\n\n /** @return any exception that occured, or NULL */\n public synchronized Exception getException() {\n return _exception;\n }\n}\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37992/" ]
293,389
<p>PHP provides a mechanism to register a shutdown function:</p> <pre><code>register_shutdown_function('shutdown_func'); </code></pre> <p>The problem is that in the recent versions of PHP, this function is still executed DURING the request. </p> <p>I have a platform (in Zend Framework if that matters) where any piece of code throughout the request can register an entry to be logged into the database. Rather than have tons of individual insert statements throughout the request, slowing the page down, I queue them up to be insert at the end of the request. I would like to be able to do this after the HTTP request is complete with the user so the length of time to log or do any other cleanup tasks doesn't affect the user's perceived load time of the page.</p> <p>Is there a built in method in PHP to do this? Or do I need to configure some kind of shared memory space scheme with an external process and signal that process to do the logging?</p>
[ { "answer_id": 293476, "author": "Nicholas Piasecki", "author_id": 32187, "author_profile": "https://Stackoverflow.com/users/32187", "pm_score": 0, "selected": false, "text": "exec()" }, { "answer_id": 293480, "author": "Mike Keen", "author_id": 14182, "author_profile": "https://Stackoverflow.com/users/14182", "pm_score": 0, "selected": false, "text": "<?php\nmysql_query('INSERT INTO queue ('instructions') VALUES ('something would go here');\necho('<iframe src=\"/yourapp/execute_queue/id?' . mysql_insert_id() . '\" />');\n?>\n <?php\n$result = mysql_query('SELECT instructions FROM queue WHERE id = ' . $_GET['id']);\n// From here, simply execute some instruction based on the \"instructions\" field, then delete the instruction from the database.\n?>\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36780/" ]
293,403
<p>Does Lucene QueryParser.parse(string) still work? If it is deprecated, what is the new syntax?</p> <p>Query query = QueryParser.parse("Ophelia");</p> <p>Thanks Tatyana</p>
[ { "answer_id": 293406, "author": "CVertex", "author_id": 209, "author_profile": "https://Stackoverflow.com/users/209", "pm_score": 3, "selected": false, "text": "var qp = new QueryParser(new StandardAnalyzer(),fields);\nqp.Parse(inputString,fields);\n" }, { "answer_id": 29899796, "author": "hcjcch", "author_id": 2937924, "author_profile": "https://Stackoverflow.com/users/2937924", "pm_score": 1, "selected": false, "text": "QueryParser parser = new QueryParser(fields, new StandardAnalyzer());\nQuery query = parser.parse(searchString);\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33917/" ]
293,409
<p>I'm still new to ROR, so pardon the simplicity of the question...</p> <p>So <a href="http://www.example.com/controller/:id" rel="nofollow noreferrer">http://www.example.com/controller/:id</a> displays a record in my table, with :id being a number (1,2,3 etc.).</p> <p>Is there a way I can have :id in the URL be the value of a field in the displayed record? Such that I can have <a href="http://www.example.com/controller/record_field" rel="nofollow noreferrer">http://www.example.com/controller/record_field</a>? I want to have a human-friendly reference to specific records in my table. I'm sure this must be possible. Do I change something in routes.rb?</p> <p>Thanks for the help!</p>
[ { "answer_id": 301184, "author": "Patrick McKenzie", "author_id": 15046, "author_profile": "https://Stackoverflow.com/users/15046", "pm_score": 0, "selected": false, "text": "class Hamburger << ActiveRecord::Base\n\n #this normally defaults to id\n def to_param \n name\n end\n\nend\n\nclass SomeModelController << ApplicationController\n\n def show \n @hamburger = Hamburger.find(params[:id]) #still default code\n end\nend\n\n#goes in some view\nThis is the <%= link_to \"tastiest hamburger ever\", url_for(@hamburger) %>.\n param permalink" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32154/" ]
293,421
<p>I have a vector-like class that contains an array of objects of type <code>"T"</code>, and I want to implement 4 arithmetic operators, which will apply the operation on each item:</p> <pre><code>// Constructors and other functions are omitted for brevity. template&lt;class T, unsigned int D&gt; class Vector { public: // Add a value to each item: naive implementation. void operator += (const T&amp;) { for (int i = 0; i &lt; D; ++i) { data[i] += value; } } void operator -= (const T&amp;) { ... } void operator *= (const T&amp;) { ... } void operator /= (const T&amp;) { ... } private: T items[D]; }; </code></pre> <p>Because operators will contain the same boilerplate code (looping over every element and applying appropriate operation), I thought I could generalize it:</p> <pre><code>template&lt;class T, unsigned int D&gt; class Vector { public: void operator += (const T&amp; value) { do_for_each(???, value); } void operator -= (const T&amp; value) { do_for_each(???, value); } void operator *= (const T&amp; value) { do_for_each(???, value); } void operator /= (const T&amp; value) { do_for_each(???, value); } private: void do_for_each(std::binary_function&lt;void, T, T&gt;&amp; op, T value) { std::for_each(data, data + D, std::bind2nd(op, value)); } T data[D]; }; </code></pre> <p>Now, the problem is, how do I pass an operator that takes two intrinsic types and returns <code>void</code> to <code>do_for_each</code>, as depicted in the example above? C++ does not let me do this trick for intrinsic types (<code>"T::operator+="</code> will not work if <code>"T"</code> is <code>"int"</code>).</p>
[ { "answer_id": 293445, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 4, "selected": true, "text": "std::transform template<class T, unsigned int D>\nclass Vector {\n\npublic:\n Vector& operator += (const T& value) { \n do_for_each(std::plus<T>(), value); \n return *this;\n }\n\n Vector& operator -= (const T& value) { \n do_for_each(std::minus<T>(), value); \n return *this;\n }\n\n Vector& operator *= (const T& value) { \n do_for_each(std::multiplies<T>(), value);\n return *this; \n }\n\n Vector& operator /= (const T& value) { \n do_for_each(std::divides<T>(), value); \n return *this;\n }\n\nprivate:\n template<typename BinFun>\n void do_for_each(BinFun op, const T& value) {\n std::transform(data, data + D, data, std::bind2nd(op, value));\n }\n\n T data[D];\n};\n" }, { "answer_id": 293517, "author": "Alastair", "author_id": 31038, "author_profile": "https://Stackoverflow.com/users/31038", "pm_score": 2, "selected": false, "text": "boost::operators::integer_arithmatic<T>" }, { "answer_id": 293559, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 1, "selected": false, "text": "template<class T, unsigned int D>\nclass Vector \n{\n\n public:\n Vector& operator += (const T& value) { \n std::transform(data, data + D, data, std::bind2nd(std::plus<T>(),value)); \n return *this;\n }\n\n Vector& operator -= (const T& value) { \n std::transform(data, data + D, data, std::bind2nd(std::minus<T>(),value)); \n return *this;\n }\n\n Vector& operator *= (const T& value) { \n std::transform(data, data + D, data, std::bind2nd(std::multiplies<T>(),value));\n return *this; \n }\n\n Vector& operator /= (const T& value) { \n std::transform(data, data + D, data, std::bind2nd(std::divides<T>(),value)); \n return *this;\n }\n\n private:\n T data[D];\n};\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23643/" ]
293,423
<p>I've been utilizing <code>NHibernate 2.0.1.4000</code> on all current .NET 3.5 SP1 projects and have had no problems with any other queries (utilizing either the Query or Criteria APIs), until some new business logic dictated the necessity of a new query in this particular project against the application's database that needs to retrieve records with a specific null property (of type DateTime) from a single table.</p> <p>Knowing that you cannot use the not-equal restriction for this type of query, but instead can use the IsNull restriction, this simple query generates a "Value cannot be null!" Exception when executed. I have extensive DEBUG mode log4net log files, which I have reviewed and haven't yet helped, and I have verified that my class for the table does specify the property I'm checking for is a nullable property (DateTime?) to avoid the problems that can cause by forcing updates to the record, etc., which isn't happening here...</p> <p>Here's the query, nothing complex, and I've tried with/without the MaxResults additional restriction to eliminate it as a problem, and yet, everytime, the exception gets thrown before I can collect the results:</p> <pre><code>ICriteria criteria = session.GetISession().CreateCriteria(typeof (Order)).Add(NHibernate.Criterion.Restrictions.IsNull("ShippedOn")).SetMaxResults(10); IList&lt;Order&gt; entityList = criteria.List&lt;Order&gt;(); </code></pre> <p>Any ideas or pointers to more information that might help me solve this? I've tried using HQL alternatively, same problems... Am I missing something here with regards to returning records with a specific null property?</p>
[ { "answer_id": 293445, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 4, "selected": true, "text": "std::transform template<class T, unsigned int D>\nclass Vector {\n\npublic:\n Vector& operator += (const T& value) { \n do_for_each(std::plus<T>(), value); \n return *this;\n }\n\n Vector& operator -= (const T& value) { \n do_for_each(std::minus<T>(), value); \n return *this;\n }\n\n Vector& operator *= (const T& value) { \n do_for_each(std::multiplies<T>(), value);\n return *this; \n }\n\n Vector& operator /= (const T& value) { \n do_for_each(std::divides<T>(), value); \n return *this;\n }\n\nprivate:\n template<typename BinFun>\n void do_for_each(BinFun op, const T& value) {\n std::transform(data, data + D, data, std::bind2nd(op, value));\n }\n\n T data[D];\n};\n" }, { "answer_id": 293517, "author": "Alastair", "author_id": 31038, "author_profile": "https://Stackoverflow.com/users/31038", "pm_score": 2, "selected": false, "text": "boost::operators::integer_arithmatic<T>" }, { "answer_id": 293559, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 1, "selected": false, "text": "template<class T, unsigned int D>\nclass Vector \n{\n\n public:\n Vector& operator += (const T& value) { \n std::transform(data, data + D, data, std::bind2nd(std::plus<T>(),value)); \n return *this;\n }\n\n Vector& operator -= (const T& value) { \n std::transform(data, data + D, data, std::bind2nd(std::minus<T>(),value)); \n return *this;\n }\n\n Vector& operator *= (const T& value) { \n std::transform(data, data + D, data, std::bind2nd(std::multiplies<T>(),value));\n return *this; \n }\n\n Vector& operator /= (const T& value) { \n std::transform(data, data + D, data, std::bind2nd(std::divides<T>(),value)); \n return *this;\n }\n\n private:\n T data[D];\n};\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37974/" ]
293,431
<p>Why won't this work? I'm trying to make an instance of a class delete itself.</p> <pre><code>&gt;&gt;&gt; class A(): def kill(self): del self &gt;&gt;&gt; a = A() &gt;&gt;&gt; a.kill() &gt;&gt;&gt; a &lt;__main__.A instance at 0x01F23170&gt; </code></pre>
[ { "answer_id": 293447, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 6, "selected": false, "text": ">>> class A():\n... def kill_a(self):\n... print self\n... del self\n... def kill_b(self):\n... del self\n... print self\n... \n>>> a = A()\n>>> b = A()\n>>> a.kill_a()\n<__main__.A instance at 0xb771250c>\n>>> b.kill_b()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"<stdin>\", line 7, in kill_b\nUnboundLocalError: local variable 'self' referenced before assignment\n" }, { "answer_id": 293462, "author": "Cybis", "author_id": 32998, "author_profile": "https://Stackoverflow.com/users/32998", "pm_score": 2, "selected": false, "text": "a = A()\na.kill()\n" }, { "answer_id": 293485, "author": "Jason Baker", "author_id": 2147, "author_profile": "https://Stackoverflow.com/users/2147", "pm_score": 0, "selected": false, "text": "class foo(object):\n def __init__(self):\n self.some_big_object = some_resource\n\n def killBigObject(self):\n del some_big_object\n >>> class manager(object):\n... def __init__(self):\n... self.lookup = {}\n... def addItem(self, name, item):\n... self.lookup[name] = item\n... item.setLookup(self.lookup)\n>>> class Item(object):\n... def __init__(self, name):\n... self.name = name\n... def setLookup(self, lookup):\n... self.lookup = lookup\n... def deleteSelf(self):\n... del self.lookup[self.name]\n>>> man = manager()\n>>> item = Item(\"foo\")\n>>> man.addItem(\"foo\", item)\n>>> man.lookup\n {'foo': <__main__.Item object at 0x81b50>}\n>>> item.deleteSelf()\n>>> man.lookup\n {}\n" }, { "answer_id": 293920, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 4, "selected": false, "text": "set bag set list player.bag.remove(cat)\n here.add( cat )\nplayer.bag.remove(cat)\n" }, { "answer_id": 3435323, "author": "Nathanael Abbotts", "author_id": 414493, "author_profile": "https://Stackoverflow.com/users/414493", "pm_score": 2, "selected": false, "text": "def kill_self(exit_msg = 'killed'):\n global kill_self\n del kill_self\n return exit_msg\n >>> kill_self\n<function kill_self at 0x02A2C780>\n>>> kill_self()\n'killed'\n>>> kill_self\nTraceback (most recent call last):\n File \"<pyshell#28>\", line 1, in <module>\n kill_self\nNameError: name 'kill_self' is not defined\n >>> x = kill_self\n>>> kill_self()\n>>> kill_self\nNameError: name 'kill_self' is not defined\n>>> x\n<function kill_self at 0x...>\n>>> x()\nNameError: global name 'kill_self' is not defined\n" }, { "answer_id": 8429876, "author": "Ilian Zapryanov", "author_id": 887420, "author_profile": "https://Stackoverflow.com/users/887420", "pm_score": 2, "selected": false, "text": " def Death(self):\n if self.stats[\"HP\"] <= 0:\n print(\"%s wounds were too much... Dead!\"%(self.player[\"Name\"]))\n del self\n else:\n return True\n\ndef Damage(self, enemy):\n todamage = self.stats[\"ATK\"] + randint(1,6)\n todamage -= enemy.stats[\"DEF\"]\n if todamage >=0:\n enemy.stats[\"HP\"] -= todamage\n print(\"%s took %d damage from your attack!\"%(enemy.player[\"Name\"], todamage))\n enemy.Death()\n return True\n else:\n print(\"Ineffective...\")\n return True\ndef Attack(self, enemy):\n tohit = self.stats[\"DEX\"] + randint(1,6)\n if tohit > enemy.stats[\"EVA\"]:\n print(\"You landed a successful attack on %s \"%(enemy.player[\"Name\"]))\n self.Damage(enemy)\n return True\n else:\n print(\"Miss!\")\n return True\ndef Action(self, enemylist):\n for i in range(0, len(enemylist)):\n print(\"No.%d, %r\"%(i, enemylist[i]))\n print(\"It`s your turn, %s. Take action!\"%(self.player[\"Name\"]))\n choice = input(\"\\n(A)ttack\\n(D)efend\\n(S)kill\\n(I)tem\\n(H)elp\\n>\")\n if choice == 'a'or choice == 'A':\n who = int(input(\"Who? \"))\n self.Attack(enemylist[who])\n return True\n else:\n return self.Action()\n" }, { "answer_id": 14645298, "author": "Basel Shishani", "author_id": 804138, "author_profile": "https://Stackoverflow.com/users/804138", "pm_score": 1, "selected": false, "text": "class Zero:\n pOne = None\n\nclass One:\n\n pTwo = None \n\n def process(self):\n self.pTwo = Two()\n self.pTwo.dothing()\n self.pTwo.kill()\n\n # now this fails:\n self.pTwo.dothing()\n\n\nclass Two:\n\n def dothing(self):\n print \"two says: doing something\"\n\n def kill(self):\n Zero.pOne.pTwo = None\n\n\ndef main():\n Zero.pOne = One() # just a global\n Zero.pOne.process()\n\n\nif __name__==\"__main__\":\n main()\n if object_exists:\n use_existing_obj()\nelse: \n obj = Obj()\n" }, { "answer_id": 29254550, "author": "Theoxis", "author_id": 4711816, "author_profile": "https://Stackoverflow.com/users/4711816", "pm_score": 0, "selected": false, "text": "class A:\n def __init__(self, name):\n self.name=name\n def kill(self)\n del dict[self.name]\n\ndict={}\ndict[\"a\"]=A(\"a\")\ndict[\"a\"].kill()\n" }, { "answer_id": 38932457, "author": "skywalker", "author_id": 4898487, "author_profile": "https://Stackoverflow.com/users/4898487", "pm_score": 5, "selected": false, "text": "# NOTE: This is Python 3 code, it should work with python 2, but I haven't tested it.\nimport weakref\n\nclass InsaneClass(object):\n _alive = []\n def __new__(cls):\n self = super().__new__(cls)\n InsaneClass._alive.append(self)\n\n return weakref.proxy(self)\n\n def commit_suicide(self):\n self._alive.remove(self)\n\ninstance = InsaneClass()\ninstance.commit_suicide()\nprint(instance)\n\n# Raises Error: ReferenceError: weakly-referenced object no longer exists\n __new__ >>> class Test(): pass\n\n>>> a = Test()\n>>> b = Test()\n\n>>> c = a\n>>> d = weakref.proxy(b)\n>>> d\n<weakproxy at 0x10671ae58 to Test at 0x10670f4e0> \n# The weak reference points to the Test() object\n\n>>> del a\n>>> c\n<__main__.Test object at 0x10670f390> # c still exists\n\n>>> del b\n>>> d\n<weakproxy at 0x10671ab38 to NoneType at 0x1002050d0> \n# d is now only a weak-reference to None. The Test() instance was garbage-collected\n" }, { "answer_id": 53052821, "author": "Anonyme", "author_id": 10576955, "author_profile": "https://Stackoverflow.com/users/10576955", "pm_score": 0, "selected": false, "text": "class A:\n def __init__(self, function):\n self.function = function\n def kill(self):\n self.function(self)\n\ndef delete(object): #We are no longer in A object\n del object\n\na = A(delete)\nprint(a)\na.kill()\nprint(a)\n" }, { "answer_id": 53356767, "author": "Henry", "author_id": 10668840, "author_profile": "https://Stackoverflow.com/users/10668840", "pm_score": 2, "selected": false, "text": "list.remove() bullet_list = []\n\nclass Bullet:\n def kill_self(self):\n bullet_list.remove(self)\n\nbullet_list += [Bullet()]\n" }, { "answer_id": 63133202, "author": "Sailist", "author_id": 11185460, "author_profile": "https://Stackoverflow.com/users/11185460", "pm_score": 0, "selected": false, "text": "class A:\n\n def __init__(self):\n self.a = 123\n\n def kill(self):\n from itertools import chain\n for attr_name in chain(dir(self.__class__), dir(self)):\n if attr_name.startswith('__'):\n continue\n attr = getattr(self, attr_name)\n if callable(attr):\n setattr(self, attr_name, lambda *args, **kwargs: print('NoneType'))\n else:\n setattr(self, attr_name, None)\n a.__str__ = lambda: ''\n a.__repr__ = lambda: ''\n a = A()\nprint(a.a)\na.kill()\n\nprint(a.a)\na.kill()\n\na = A()\nprint(a.a)\n 123\nNone\nNoneType\n123\n" }, { "answer_id": 73458236, "author": "montw", "author_id": 16853862, "author_profile": "https://Stackoverflow.com/users/16853862", "pm_score": 0, "selected": false, "text": "exec class Example():\n def __init__(self, name) -> None:\n self.var_name = name\n\n def kill(self):\n exec(f'del {self.var_name}')\n\ncoolvar = Example('coolvar')\ncoolvar.kill()\n exec" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
293,438
<p>How can I pad a string with spaces on the left when using printf?</p> <p>For example, I want to print "Hello" with 40 spaces preceding it.</p> <p>Also, the string I want to print consists of multiple lines. Do I need to print each line separately?</p> <p>EDIT: Just to be clear, I want exactly 40 spaces printed before every line.</p>
[ { "answer_id": 293448, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 8, "selected": true, "text": "char *ptr = \"Hello\";\nprintf(\"%40s\\n\", ptr);\n printf ptr" }, { "answer_id": 293479, "author": "SoapBox", "author_id": 36384, "author_profile": "https://Stackoverflow.com/users/36384", "pm_score": 5, "selected": false, "text": "printf(\" %s\\n\", myStr );\n printf(\"%40s%s\", \"\", myStr ); printf(\"%40s\", myStr); printf(\"%-40s\", myStr);" }, { "answer_id": 9448093, "author": "jk_", "author_id": 518983, "author_profile": "https://Stackoverflow.com/users/518983", "pm_score": 7, "selected": false, "text": "indent void print_with_indent(int indent, char * string)\n{\n printf(\"%*s%s\", indent, \"\", string);\n}\n" }, { "answer_id": 22715903, "author": "Rece Foc", "author_id": 3473057, "author_profile": "https://Stackoverflow.com/users/3473057", "pm_score": 6, "selected": false, "text": "int space = 40;\nprintf(\"%*s\", space, \"Hello\");\n printf(\"%*d\", space, 10);\nprintf(\"%*c\", space, 'x');\n printf(\"%*d\", 10, 10);\nprintf(\"%*c\", 20, 'x');\nprintf(\"%*s\", 30, \"Hello\");\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18091/" ]
293,444
<p>I'm writing a simple program that's going to parse a logfile of a packet dump from wireshark into a more readable form. I'm doing this with python.</p> <p>Currently I'm stuck on this part:</p> <pre><code>for i in range(len(linelist)): if '### SERVER' in linelist[i]: #do server parsing stuff packet = linelist[i:find("\n\n", i, len(linelist))] </code></pre> <p>linelist is a list created using the readlines() method, so every line in the file is an element in the list. I'm iterating through it for all occurances of "### SERVER", then grabbing all lines after it until the next empty line(which signifies the end of the packet). I must be doing something wrong, because not only is find() not working, but I have a feeling there's a better way to grab everything between ### SERVER and the next occurance of a blank line.</p> <p>Any ideas?</p>
[ { "answer_id": 293568, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 2, "selected": false, "text": " A trailing newline character is kept in the string linelist \"\\n\\n\" if myline in (\"\\n\", \"\"):\n handle_empty_line()\n find" }, { "answer_id": 293685, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 0, "selected": false, "text": "inpacket = False\npackets = []\nfor line in open(\"logfile\"):\n if inpacket:\n content += line\n if line in (\"\\n\", \"\"): # empty line\n inpacket = False\n packets.append(content)\n elif '### SERVER' in line:\n inpacket = True\n content = line\n# put here packets.append on eof if needed\n" }, { "answer_id": 293827, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 0, "selected": false, "text": "fileIter= iter(theFile)\nfor x in fileIter:\n if \"### SERVER\" in x:\n block = [x]\n for y in fileIter:\n if len(y.strip()) == 0: # empty line\n break\n block.append(y)\n print block # Or whatever\n # elif some other pattern:\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2153/" ]
293,482
<p>I need to sanitize HTML submitted by the user by closing any open tags with correct nesting order. I have been looking for an algorithm or Python code to do this but haven't found anything except some half-baked implementations in PHP, etc.</p> <p>For example, something like</p> <pre><code>&lt;p&gt; &lt;ul&gt; &lt;li&gt;Foo </code></pre> <p>becomes</p> <pre><code>&lt;p&gt; &lt;ul&gt; &lt;li&gt;Foo&lt;/li&gt; &lt;/ul&gt; &lt;/p&gt; </code></pre> <p>Any help would be appreciated :)</p>
[ { "answer_id": 293558, "author": "pantsgolem", "author_id": 9261, "author_profile": "https://Stackoverflow.com/users/9261", "pm_score": 6, "selected": true, "text": "from BeautifulSoup import BeautifulSoup\nhtml = \"<p><ul><li>Foo\"\nsoup = BeautifulSoup(html)\nprint soup.prettify()\n <p>\n <ul>\n <li>\n Foo\n </li>\n </ul>\n</p>\n import tidy\nhtml = \"<p><ul><li>Foo\"\nprint tidy.parseString(html, show_body_only=True)\n <ul>\n<li>Foo</li>\n</ul>\n print tidy.parseString(html, show_body_only=True, drop_empty_paras=False)\n <p></p>\n<ul>\n<li>Foo</li>\n</ul>\n print tidy.parseString(html, show_body_only=True, indent=True)\n <ul>\n <li>Foo\n </li>\n</ul>\n" }, { "answer_id": 32627081, "author": "Mithril", "author_id": 1637673, "author_profile": "https://Stackoverflow.com/users/1637673", "pm_score": 1, "selected": false, "text": "BeautifulSoup from BeautifulSoup import BeautifulSoup\nimport lxml.html\nsoup = BeautifulSoup(page)\nh = lxml.html(soup.prettify())\n h = lxml.html(page) soup = BeautifulSoup(page, 'html5lib') html5lib BeautifulSoup html5lib" }, { "answer_id": 53265133, "author": "drt", "author_id": 7705116, "author_profile": "https://Stackoverflow.com/users/7705116", "pm_score": 1, "selected": false, "text": "from BeautifulSoup import BeautifulSoup\nsoup = BeautifulSoup(page, 'html5lib')\n soup = bs4.BeautifulSoup(html, 'html5lib')\nf_html = soup.prettify()\nprint(f'Formatted html::: {f_html}')\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8024/" ]
293,495
<p>I have a dropdown box and a literal tag inside an Update Panel. On the selection change event of the dropdown up requery the database and repopulate the literal tag and then call UPdatePanel.Update().</p> <p>below, is there are way i can avoid having to create a new Oledbconnection each time as this seems slow. Can i reuse and store:</p> <ol> <li>The Datasource</li> <li>The connection in the page. </li> </ol> <p>if so, how do i keep this state between calls from the GUI to the server? Here is my selection change code below</p> <pre><code>protected void cboPeople_SelectedIndexChanged(object sender, EventArgs e) { string dataSource = ConfigurationSettings.AppSettings["contactsDB"]; var objConn = new OleDbConnection(dataSource); string id = People[cboPeople.Text]; UpdateLiteral(objConn, id); } </code></pre>
[ { "answer_id": 293579, "author": "Robert Wagner", "author_id": 10784, "author_profile": "https://Stackoverflow.com/users/10784", "pm_score": 2, "selected": true, "text": "string dataSource = ConfigurationSettings.AppSettings[\"contactsDB\"];\nusing(var objConn = new OleDbConnection(dataSource))\n{\n string id = People[cboPeople.Text];\n UpdateLiteral(objConn, id);\n}\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293495", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4653/" ]
293,499
<p>Yesterday, I found myself writing code like this:</p> <pre><code>SomeStruct getSomeStruct() { SomeStruct input; cin &gt;&gt; input.x; cin &gt;&gt; input.y; } </code></pre> <p>Of course forgetting to actually return the struct I just created. Oddly enough, the values in the struct that <em>was</em> returned by this function got initialized to zero (when compiled using g++ that is). Is this just a coincidence or did another SomeStruct get created and initialized somewhere implicitly?</p>
[ { "answer_id": 293520, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 5, "selected": false, "text": "-Wall -Wreturn-type -Wall -Werror" }, { "answer_id": 293563, "author": "CesarB", "author_id": 28258, "author_profile": "https://Stackoverflow.com/users/28258", "pm_score": 4, "selected": true, "text": "x y getSomeStruct getSomeStruct return SomeStruct getSomeStruct" }, { "answer_id": 293737, "author": "Douglas Leeder", "author_id": 3978, "author_profile": "https://Stackoverflow.com/users/3978", "pm_score": 1, "selected": false, "text": "-Wall -Werror" }, { "answer_id": 294183, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 2, "selected": false, "text": "GetSomeStruct() error C4716: 'getSomeStruct' : must return a value Warning 18: implied return of getSomeStruct at closing '}' does not return value warning: missing return statement at end of non-void function \"getSomeStruct\"" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2147/" ]
293,500
<p>We have built a custom socket server in ruby and packaged it as a gem. Since this is an internal project we can not simply publish it to RubyForge or GitHub. I tried to setup our own gem server but gem would not authenticate over https. Our other deployment is all for standard rails applications that use capistrano and svn for deployment.</p> <p>Our current setup which is to use a rails-like deployment with capistrano. which does the following:</p> <ul> <li>Check out the code from svn</li> <li>Build the gem</li> <li>Install the gem</li> <li>Restart the server</li> </ul> <p>This just seems awkward, and makes the gem packaging seem like extra work -- but outside of the deployment issue it fits really nicely as a gem.</p> <p>Is there a cleaner approach?</p>
[ { "answer_id": 293670, "author": "Pistos", "author_id": 28558, "author_profile": "https://Stackoverflow.com/users/28558", "pm_score": 2, "selected": false, "text": "gem install /path/to/some.gem\n" }, { "answer_id": 295504, "author": "Jonke", "author_id": 15638, "author_profile": "https://Stackoverflow.com/users/15638", "pm_score": 3, "selected": true, "text": "gem server #That will serve all your local installed gems.\n\ngem install YourLocalPkg1.X.X.gem\n gem sources --add localhost:8808\ngem install YourGem\n rake gem\ngem install YourLocalPkg2.X.X.gem #on YourHost\n gem update YourGem #on client machine\n * Check out the code from svn #the railspart not in the gem\n* gem update YourGem # or install if not exist....\n* Restart the server\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19839/" ]
293,506
<p>I am trying to send a user to another page using a Javascript Function:</p> <pre><code>&lt;input type="button" name="confirm" value="nextpage" onClick="message()"&gt; </code></pre> <p>And my JavaScript:</p> <pre><code>function message() { ConfirmStatus = confirm("Install a Virus?"); if (ConfirmStatus == true) { //Send user to another page } } </code></pre> <p>Does anyone know how to send a user to another specific page?</p>
[ { "answer_id": 293510, "author": "titaniumdecoy", "author_id": 18091, "author_profile": "https://Stackoverflow.com/users/18091", "pm_score": 3, "selected": false, "text": "window.location.href = \"newpage.html\";" }, { "answer_id": 293512, "author": "José Leal", "author_id": 37190, "author_profile": "https://Stackoverflow.com/users/37190", "pm_score": 5, "selected": false, "text": "location.href = 'http://www.google.com';\nor\nlocation.href = 'myrelativepage.php';\n header('Location: index.php'); Response.Redirect(\"yourpage.aspx\"); response.sendRedirect(\"http://www.google.com\"); " }, { "answer_id": 293675, "author": "Matthew Schinckel", "author_id": 188, "author_profile": "https://Stackoverflow.com/users/188", "pm_score": 2, "selected": false, "text": "<meta http-equiv=\"refresh\" content=\"2;url=http://other-domain.com\">\n http://other-domain.com" }, { "answer_id": 59506999, "author": "RandomSqueaker", "author_id": 12561910, "author_profile": "https://Stackoverflow.com/users/12561910", "pm_score": 2, "selected": false, "text": "window.location.replace(\"http://www.link.com\");\n" }, { "answer_id": 63491981, "author": "omid29", "author_id": 12383839, "author_profile": "https://Stackoverflow.com/users/12383839", "pm_score": 1, "selected": false, "text": "window.location.href = \"YOUR_RELATIVE_PATH_HERE\"" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
293,524
<p>I have code in an Update Panel and even though on a button click i am inserting data into a db and simply calling Updatepanel.Update() the whole page is reloaded:</p> <p>Gifts.ASPX</p> <pre><code>&lt;table style="width:100%;"&gt; &lt;tr&gt; &lt;td&gt; &lt;asp:Label ID="Label2" runat="server" Text="Gift"&gt;&lt;/asp:Label&gt; &lt;/td&gt; &lt;td&gt; &lt;asp:UpdatePanel ID="UpdatePanel3" runat="server" UpdateMode="Conditional"&gt; &lt;ContentTemplate&gt; &lt;asp:TextBox ID="txtNewGift" runat="server"&gt;&lt;/asp:TextBox&gt; &lt;/ContentTemplate&gt; &lt;/asp:UpdatePanel&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; </code></pre> <p>Gifts.aspx.CS</p> <pre><code>protected void cmdAddGift_Click(object sender, EventArgs e) { OleDbConnection objConn = new OleDbConnection(DataSource); Random r = new Random(); int giftID = r.Next(1200, 14000); OleDbCommand objCommand = new OleDbCommand("Insert into Gifts (GiftID, Description) values (" + giftID + ",'" + txtNewGift.Text + "')", objConn); ExecuteCommand(objCommand); PopulateGifts(objConn); txtNewGift.Text = ""; UpdatePanel3.Update(); } </code></pre> <p>Any ideas why this whole page would reload instead of just the textbox getting update?</p>
[ { "answer_id": 293591, "author": "Robert Wagner", "author_id": 10784, "author_profile": "https://Stackoverflow.com/users/10784", "pm_score": 2, "selected": false, "text": "<asp:UpdatePanel runat=\"server\">\n <ContentTemplate>\n <!-- Content -->\n <asp:Button runat=\"server\" ID=\"btnInnerPart\" Text=\"Inner Part\" />\n <asp:Button runat=\"server\" ID=\"btnInnerFull\" Text=\"Inner Full\" />\n </ContentTemplate>\n <Triggers>\n <asp:AsyncPostBackTrigger ControlID=\"btnOuterPart\" />\n <asp:PostBackTrigger ControlID=\"btnInnerFull\" />\n </Triggers>\n</asp:UpdatePanel>\n<asp:Button runat=\"server\" ID=\"btnOuterFull\" Text=\"Outer Full\" />\n<asp:Button runat=\"server\" ID=\"btnOuterPart\" Text=\"Outer Part\" />\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4653/" ]
293,541
<p>Is there a PHP version of JavaScript's confirm() function?<br> If not, what are my other options or how do I make something similar to the confirm()?</p>
[ { "answer_id": 293544, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 3, "selected": false, "text": "<p>Are you sure you want to do this?</p>\n\n<form action=\"page2.php\" method=\"post\">\n <input type=\"submit\" name=\"ok\" value=\"OK\" />\n <input type=\"submit\" name=\"cancel\" value=\"Cancel\" />\n</form>\n <?php\n\nif (isset($_POST['ok'])) {\n // They pressed OK\n}\n\nif (isset($_POST['cancel'])) {\n // They pressed Cancel\n}\n\n?>\n" }, { "answer_id": 293550, "author": "José Leal", "author_id": 37190, "author_profile": "https://Stackoverflow.com/users/37190", "pm_score": 2, "selected": false, "text": "<form action=\"page2.php\" method=\"post\">\n Your choice: <input type=\"radio\" name=\"choice\" value=\"yes\"> Yes <input type=\"radio\" name=\"choice\" value=\"no\" /> No\n <button type=\"submit\">Send</button>\n</form>\n if (isset($_POST['choice']) /* Always check buddy */) {\n switch($_POST['choice']) {\n case 'yes':\n /// Code here\n break;\n case 'no':\n /// Code here\n break;\n default:\n /// Error treatment\n break;\n }\n}\nelse {\n // error treatment\n}\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
293,582
<p>I was hoping to automate some tasks related to SubVersion, so I got SharpSvn. Unfortunately I cant find much documentation for it. </p> <p>I want to be able to view the changes after a user commits a new revision so I can parse the code for special comments that can then be uploaded into my ticket system.</p>
[ { "answer_id": 293848, "author": "Bert Huijben", "author_id": 2094, "author_profile": "https://Stackoverflow.com/users/2094", "pm_score": 3, "selected": true, "text": "static void Main(string[] args)\n{\n SvnHookArguments ha;\n if (!SvnHookArguments.ParseHookArguments(args, SvnHookType.PostCommit, false, out ha))\n {\n Console.Error.WriteLine(\"Invalid arguments\");\n Environment.Exit(1);\n }\n\n using (SvnLookClient cl = new SvnLookClient())\n {\n SvnChangeInfoEventArgs ci;\n cl.GetChangeInfo(ha.LookOrigin, out ci);\n\n // ci contains information on the commit e.g.\n Console.WriteLine(ci.LogMessage); // Has log message\n\n foreach(SvnChangeItem i in ci.ChangedPaths)\n {\n //\n }\n }\n}\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38013/" ]
293,590
<p>I came across the case where depending on the execution path I may need to invoke an inclusion of .js file from controller. Is there a nice way of doing it? (besides setting some view variable with actual .js include code)?</p>
[ { "answer_id": 293805, "author": "smack0007", "author_id": 26566, "author_profile": "https://Stackoverflow.com/users/26566", "pm_score": 4, "selected": true, "text": "$this->headScript()->appendFile('filename.js'); $this->view->headScript()->appendFile('filename.js'); <?=$this->headScript();?>" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35520/" ]
293,597
<p>It seems with the built in friendly routing library in .NET MVC, it would allow us to do something like this.</p> <p>In case it's not obvious what I want to with the built in stuff in .NET MVC, I want to a url starting with www to be automatically redirected to a non-www url using the MVC framework.</p>
[ { "answer_id": 4837455, "author": "BrunoLM", "author_id": 340760, "author_profile": "https://Stackoverflow.com/users/340760", "pm_score": 3, "selected": false, "text": "web.config <system.webServer> <rewrite>\n <rules>\n <rule name=\"Canonical\" stopProcessing=\"true\">\n <match url=\".*\" />\n <conditions>\n <add input=\"{HTTP_HOST}\" pattern=\"^www[.](.+)\" />\n </conditions>\n <action type=\"Redirect\" url=\"http://{C:1}/{R:0}\" redirectType=\"Permanent\" />\n </rule>\n </rules>\n</rewrite>\n global.asax.cs protected void Application_BeginRequest(object sender, EventArgs ev)\n{\n if (Request.Url.Host.StartsWith(\"www\", StringComparison.InvariantCultureIgnoreCase))\n {\n Response.Clear();\n Response.AddHeader(\"Location\", \n String.Format(\"{0}://{1}{2}\", Request.Url.Scheme, Request.Url.Host.Substring(4), Request.Url.PathAndQuery)\n );\n Response.StatusCode = 301;\n Response.End();\n }\n}\n <rewrite>\n <rules>\n <rule name=\"Canonical\" stopProcessing=\"true\">\n <match url=\".*\" />\n <conditions>\n <add input=\"{HTTP_HOST}\" pattern=\"^([a-z]+[.]net)$\" />\n </conditions>\n <action type=\"Redirect\" url=\"http://www.{C:0}/{R:0}\" redirectType=\"Permanent\" />\n </rule>\n </rules>\n</rewrite>\n {C:0} 1, 2, ..., N" }, { "answer_id": 5857969, "author": "Arrabi", "author_id": 233085, "author_profile": "https://Stackoverflow.com/users/233085", "pm_score": 0, "selected": false, "text": "if (HttpContext.Current.Request.Url.ToString().ToLower().Contains(\"http://YourSite.com\"))\n {\n HttpContext.Current.Response.Status = \"301 Moved Permanently\";\n HttpContext.Current.Response.AddHeader(\"Location\", Request.Url.ToString().ToLower().Replace(\"http://YourSite.com\",\"http://www.YourSite.com\"));\n }\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/438/" ]
293,601
<p>I'm building a small web app in PHP that stores some information in a plain text file. However, this text file is used/modified by all users of my app at some given point in time and possible at the same time.</p> <p>So the questions is. What would be the best way to make sure that only one user can make changes to the file at any given point in time?</p>
[ { "answer_id": 293674, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 2, "selected": false, "text": " user->save : \n getWritelock(); \n write( $file ); \n write_commitmessage( $commitmessagefile ); # <-- author , comment, etc \n call \"hg commit -l $commitmessagefile $file \" ; \n releaseWriteLock(); \n done.\n" }, { "answer_id": 293704, "author": "andy.gurin", "author_id": 22388, "author_profile": "https://Stackoverflow.com/users/22388", "pm_score": 6, "selected": true, "text": " $fp = fopen(\"/tmp/lock.txt\", \"r+\");\n\nif (flock($fp, LOCK_EX)) { // acquire an exclusive lock\n ftruncate($fp, 0); // truncate file\n fwrite($fp, \"Write something here\\n\");\n fflush($fp); // flush output before releasing the lock\n flock($fp, LOCK_UN); // release the lock\n} else {\n echo \"Couldn't get the lock!\";\n}\n\nfclose($fp);\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21406/" ]
293,602
<p>I have a ASP.NET project and when building the project it is showing build suceessfull. But when I am building the deployment project, it is showing build failed with an error message </p> <pre><code>Error 5 "aspnet_compiler.exe" exited with code 1 </code></pre> <p>I rechecked my project and found that when i am removing the line <strong><code>&lt;!--#include file="admin/topstyle.asp"--&gt;</code></strong>, it is working fine. If I use this line, I am getting error building web deployment project to create my dll.</p> <p><strong>topstyle.asp</strong> is a file which render some common styles for the page like heading image and all.</p> <p>Can anyone tell me how to get rid of this problem?</p>
[ { "answer_id": 301436, "author": "user39603", "author_id": 39603, "author_profile": "https://Stackoverflow.com/users/39603", "pm_score": 0, "selected": false, "text": "<!-- include virtual=\"~/page.asp\" -->" }, { "answer_id": 29691550, "author": "user4799664", "author_id": 4799664, "author_profile": "https://Stackoverflow.com/users/4799664", "pm_score": 1, "selected": false, "text": "dtRow.Item(\"ParentGroupName\") = Session(\"SecondaryGroupItems\").GetSecondaryGroupItem(Session(\"LgItems\").GetLgItem(mFnTransaction.FnTransactionDetails(1).LgId).SecondaryGroupId).Name\n Dim mmSecondaryGroupId As Integer = 0\nDim mmLgId As Integer = 0\n\nmmLgId = mFnTransaction.FnTransactionDetails(1).LgId\n\nmmSecondaryGroupId = DirectCast(Session(\"LgItems\"), LgItems).GetLgItem(mmLgId).SecondaryGroupId\n\ndtRow.Item(\"ParentGroupName\") = DirectCast(Session(\"SecondaryGroupItems\"), SecondaryGroupItems).GetSecondaryGroupItem(mmSecondaryGroupId).Name\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29982/" ]
293,617
<p>I'm writing a file that requires dates to be in decimal format:</p> <blockquote> <p><code>2007-04-24T13:18:09</code> becomes <code>39196.554270833331000</code> </p> </blockquote> <p>Does anyone have a time formatter that will do this (Decimal time is what VB/Office, etc. use)?</p> <p>Basic code goes like follows:</p> <pre><code>final DateTime date = new DateTime(2007, 04, 24, 13, 18, 9, 0, DateTimeZone.UTC); double decimalTime = (double) date.plusYears(70).plusDays(1).getMillis() / (Days.ONE.toStandardDuration().getMillis())); //=39196.554270833331000. </code></pre> <p>For the example above.</p> <p>(I started on a DateTimePrinter that would do this, but it's too hard for now (I don't have the joda source linked, so I can't get ideas easily)).</p> <p>Note: Decimal time is the number of days since 1900 - the . represents partial days. 2.6666666 would be 4pm on January 2, 1900</p>
[ { "answer_id": 1404759, "author": "user86614", "author_id": 86614, "author_profile": "https://Stackoverflow.com/users/86614", "pm_score": 0, "selected": false, "text": "final long MILLIS_IN_DAY = 1000L * 60L * 60L * 24L;\n\nfinal Calendar startOfTime = Calendar.getInstance();\nstartOfTime.setTimeZone(TimeZone.getTimeZone(\"UTC\"));\nstartOfTime.clear();\nstartOfTime.set(1900, 0, 1, 0, 0, 0);\n\nfinal Calendar myDate = Calendar.getInstance();\nmyDate.setTimeZone(TimeZone.getTimeZone(\"UTC\"));\nmyDate.clear();\nmyDate.set(2007, 3, 24, 13, 18, 9); // 2007-04-24T13:18:09\n\nfinal long diff = myDate.getTimeInMillis() - startOfTime.getTimeInMillis() + (2 * MILLIS_IN_DAY);\nfinal double decimalTime = (double) diff / (double) MILLS_IN_DAY;\nSystem.out.println(decimalTime); // 39196.55427083333\n 2 * MILLIS_IN_DAY" }, { "answer_id": 10453045, "author": "JodaStephen", "author_id": 38896, "author_profile": "https://Stackoverflow.com/users/38896", "pm_score": 1, "selected": false, "text": "DateTimeFormatterBuilder" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37193/" ]
293,648
<p>How do I make one of those hyperlinks where when you click it, it will display a popup asking "are you sure?"</p> <pre><code>&lt;INPUT TYPE="Button" NAME="confirm" VALUE="???" onClick="message()"&gt; </code></pre> <p>I already have a message() function working. I just need to know what the input type for a hyperlink would be.</p>
[ { "answer_id": 293710, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 2, "selected": false, "text": "javascript:message() message this <script type=\"text/javascript\" language=\"JavaScript\">\nfunction AskAndSubmit(t)\n{\n var answer = confirm(\"Are you sure you want to do this?\");\n if (answer)\n {\n t.form.submit();\n }\n}\n</script>\n\n<form action=\"Tests/Test.html\" method=\"GET\" name=\"subscriberAddForm\">\n<input type=\"hidden\" name=\"locationId\" value=\"2721\"/>\n<input type=\"text\" name=\"text\" value=\"3.1415926535897732384\"/>\n<input type=\"button\" name=\"Confirm\" value=\"Submit this form\" onclick=\"AskAndSubmit(this)\"/>\n</form>\n" }, { "answer_id": 293714, "author": "JacquesB", "author_id": 7488, "author_profile": "https://Stackoverflow.com/users/7488", "pm_score": 5, "selected": false, "text": "<a href=\"http://somewhere_else\" onclick=\"return confirm()\">\n confirm false" }, { "answer_id": 294207, "author": "Nahom Tijnam", "author_id": 11172, "author_profile": "https://Stackoverflow.com/users/11172", "pm_score": 0, "selected": false, "text": "<a href=\"#\" onclick=\"message(); return false;\">???</a>\n" }, { "answer_id": 981857, "author": "marcgg", "author_id": 90691, "author_profile": "https://Stackoverflow.com/users/90691", "pm_score": 4, "selected": false, "text": "<a href=\"http://something.com\" onclick=\"return confirmAction()\">try to click, I dare you</a>\n function confirmAction(){\n var confirmed = confirm(\"Are you sure? This will remove this entry forever.\");\n return confirmed;\n}\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
293,649
<p>I'd like to rank my stories based on "controversy" quotient. For example, reddit.com currently has "controversial" section: <a href="http://www.reddit.com/controversial/" rel="nofollow noreferrer">http://www.reddit.com/controversial/</a></p> <p>When a story has a lot of up and a lot of down votes, it's controversial even though the total score is 0 (for example). How should I calculate this quotient score so that when there's a lot of people voting up and down, I can capture this somehow.</p> <p>Thanks!!!</p> <p>Nick</p>
[ { "answer_id": 293830, "author": "MusiGenesis", "author_id": 14606, "author_profile": "https://Stackoverflow.com/users/14606", "pm_score": 0, "selected": false, "text": "// figure out if up or down is winning - doesn't matter which\nif (up_votes > down_votes)\n{\n win_votes = up_votes;\n lose_votes = down_votes;\n}\nelse\n{\n win_votes = down_votes;\n lose_votes = up_votes;\n}\n// losewin_ratio is always <= 1, near 0 if win_votes >> lose_votes\nlosewin_ratio = lose_votes / win_votes; \ntotal_votes = up_votes + down_votes;\ncontroversy_score = total_votes * losewin_ratio; // large means controversial\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38015/" ]
293,668
<p>is it possible to use the ajaxComplete or ajaxStop features of jQuery to decide whether or not the callback gets called?</p> <p>Essentially I want to be able to take basic error checking code that is currently in most of my callbacks, and add it to a sort of global callback.</p>
[ { "answer_id": 293788, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 1, "selected": false, "text": "ajaxComplete ajaxStop" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32392/" ]
293,672
<p>A few weeks back I was using std::ifstream to read in some files and it was failing immediately on open because the file was larger than 4GB. At the time I couldnt find a decent answer as to why it was limited to 32 bit files sizes, so I wrote my own using native OS API.</p> <p>So, my question then: Is there a way to handle files greater than 4GB in size using std::ifstream/std::ostream (IE: standard c++)</p> <p>EDIT: Using the STL implementation from the VC 9 compiler (Visual Studio 2008). EDIT2: Surely there has to be standard way to support file sizes larger than 4GB.</p>
[ { "answer_id": 293709, "author": "Eugene Yokota", "author_id": 3827, "author_profile": "https://Stackoverflow.com/users/3827", "pm_score": 5, "selected": true, "text": "off_t #include <streambuf>\n__int64_t temp=std::numeric_limits<std::streamsize>::max();\n" }, { "answer_id": 293927, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 2, "selected": false, "text": "std::size_t std::off_t" }, { "answer_id": 30610742, "author": "zhaorufei", "author_id": 64469, "author_profile": "https://Stackoverflow.com/users/64469", "pm_score": 1, "selected": false, "text": "int64_t file_pos = 4LL * 1024 * 1024 * 1024 + 1;\nfile.seekp( file_pos, SEEK_SET );\nassert( file );\ncout << \"cur pos: \" << file.tellp() << endl; // the output is: 4294967297(4GB + 1)\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29049/" ]
293,694
<p>i've got regex which was alright, but as it camed out doesn't work well in some situations </p> <p><strong>Keep eye on message preview cause message editor do some tricky things with "\"</strong></p> <blockquote> <p>[\[]?[\^%#\$\*@\-;].*?[\^%#\$\*@\-;][\]]</p> </blockquote> <p>its task is to find pattern which in general looks like that</p> <blockquote> <p>[ABA]</p> </blockquote> <ul> <li>A - char from set ^,%,#,$,*,@,-,;</li> <li>B - some text</li> <li>[ and ] are included in pattern</li> </ul> <p>is expected to find all occurences of this pattern in test string</p> <blockquote> <p>Black fox [#sample1#] [%sample2%] - [#sample3#] eats blocks.</p> </blockquote> <p>but instead of expected list of matches</p> <ul> <li>"[#sample1#]" </li> <li>"[%sample2%]"</li> <li>"[#sample3#]" </li> </ul> <p>I get this</p> <ul> <li>"[#sample1#]" </li> <li>"[%sample2%]"</li> <li>"- [#sample3#]" </li> </ul> <p>And it seems that this problem will occur also with other chars in set "A". So could somebody suggest changes to my regex to make it work as i need?</p> <p>and less important thing, how to make my regex to exclude patterns which look like that</p> <blockquote> <p>[ABC]</p> </blockquote> <ul> <li>A - char from set ^,%,#,$,*,@,-,;</li> <li>B - some text</li> <li>C - char from set ^,%,#,$,*,@,-,; <strong>other than A</strong></li> <li>[ and ] are included in pattern</li> </ul> <p>for example</p> <blockquote> <p>[$sample1#] [%sample2@] [%sample3;]</p> </blockquote> <p>thanks in advance</p> <p>MTH</p>
[ { "answer_id": 293703, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 1, "selected": false, "text": "\\[[\\^%#\\$\\*@\\-;].*?[\\^%#\\$\\*@\\-;]\\]\n \\[([\\^%#\\$\\*@\\-;])([^\\]]*?)(?=\\1)([\\^%#\\$\\*@\\-;])\\]\n \\[([\\^%#\\$\\*@\\-;])([^\\]]*?)(?!\\1)([\\^%#\\$\\*@\\-;])\\]\n" }, { "answer_id": 293719, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 3, "selected": true, "text": "[#sample1#] [%sample2%] [#sample3#] [%sample4;] Regex re = new Regex(@\"\\[([%#$*@;^-]).+?\\1\\]\");\nstring s = \"Black fox [#sample1#] [%sample2%] - [#sample3#] [%sample4;] eats blocks.\";\n\nMatchCollection mc = re.Matches(s);\nforeach (Match m in mc)\n{\n Console.WriteLine(m.Value);\n}\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293694", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24824/" ]
293,725
<p>i need a Regular Expression to convert a a string to a link.i wrote something but it doesnt work in asp.net.i couldnt solve and i am new in Regular Expression.This function converts (bkz: string) to (bkz: show.aspx?td=string)</p> <pre><code>Dim pattern As String = "&amp;lt;bkz[a-z0-9$-$&amp;-&amp;.-.ö-öı-ış-şç-çğ-ğü-ü\s]+)&amp;gt;" Dim regex As New Regex(pattern, RegexOptions.IgnoreCase) str = regex.Replace(str, "&lt;a href=""show.aspx?td=$1""&gt;&lt;font color=""#CC0000""&gt;$1&lt;/font&gt;&lt;/a&gt;") </code></pre>
[ { "answer_id": 293729, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 2, "selected": true, "text": "&lt;bkz:\\s+((?:.(?!&gt;))+?.)&gt;\n" }, { "answer_id": 293734, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<span id=\"Label1\">(bkz: <a href=\"http://www.mysite.com?t=here\">here</a>)</span>\n <span id=\"Label1\">(bkz: here)</span>\n" }, { "answer_id": 293746, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 2, "selected": false, "text": "\\(bkz: ([a-z0-9$&.öışçğü\\s]+)\\)\n (bkz: <a href=\"\"show.aspx?td=$1\"\"><span style=\"\"color: #C00\"\">$1</span></a>)\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
293,728
<p>My application will read xml from urlconnection. The xml encoding is ISO-8859-1, it contains é character. I use xerces saxparser to parse received xml content. However, é can not be parsed correctly while running application under lunix OS. Everything works fine in Windows. Could you guys please give me some hints? Thanks a lot</p>
[ { "answer_id": 293837, "author": "Fernando Miguélez", "author_id": 34880, "author_profile": "https://Stackoverflow.com/users/34880", "pm_score": 1, "selected": false, "text": "// Parse the input\nSAXParser saxParser = factory.newSAXParser();\nInputStream is = new ByteArrayInputStream(stringToParse.getBytes());\nsaxParser.parse( is, handler );\n stringToParse.getBytes()" }, { "answer_id": 303234, "author": "Sophie Gage", "author_id": 37134, "author_profile": "https://Stackoverflow.com/users/37134", "pm_score": 0, "selected": false, "text": "InputSource inputSource = new InputSource(xmlInputStream);\ninputSource.setEncoding(\"ISO-8859-1\");\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
293,743
<p>I have been writting a keyword search script based on this tutorial: <a href="http://www.hackosis.com/2007/11/06/howto-simple-search-engine-with-php-and-mysql/" rel="nofollow noreferrer">http://www.hackosis.com/2007/11/06/howto-simple-search-engine-with-php-and-mysql/</a></p> <p>Like some of the commenters mentioned, the script only ends up returning results based on the last word in the search terms. So I have also tried to implement one of the suggestions from another user, but now I seem to only be able to get results based on the first search term.</p> <p>The code for my script can be found here: <a href="http://php.pastebin.com/m7759afd3" rel="nofollow noreferrer">http://php.pastebin.com/m7759afd3</a></p> <p>My print_r for the results looks like this:</p> <pre><code>SELECT * FROM blog WHERE blog_title LIKE '%barry%' OR blog_content LIKE '%barry%' AND blog_title LIKE '%child%' OR blog_content LIKE '%child%' AND blog_title LIKE '%help%' OR blog_content LIKE '%help%' ORDER BY blog_title SELECT * FROM links WHERE link_title LIKE '%barry%' OR link_desc LIKE '%barry%' AND link_title LIKE '%child%' OR link_desc LIKE '%child%' AND link_title LIKE '%help%' OR link_desc LIKE '%help%' ORDER BY link_title SELECT * FROM pages WHERE page_title LIKE '%barry%' OR page_content LIKE '%barry%' AND page_title LIKE '%child%' OR page_content LIKE '%child%' AND page_title LIKE '%help%' OR page_content LIKE '%help%' ORDER BY page_title </code></pre> <p>Thank you for any help you might be able to offer.</p>
[ { "answer_id": 293753, "author": "Nahom Tijnam", "author_id": 11172, "author_profile": "https://Stackoverflow.com/users/11172", "pm_score": 3, "selected": true, "text": "SELECT * FROM blog WHERE blog_title LIKE '%barry%' OR blog_content LIKE '%barry%' OR blog_title LIKE '%child%' OR blog_content LIKE '%child%' OR blog_title LIKE '%help%' OR blog_content LIKE '%help%' ORDER BY blog_title\n blog_title, blog_content" }, { "answer_id": 293819, "author": "foxy", "author_id": 30119, "author_profile": "https://Stackoverflow.com/users/30119", "pm_score": 1, "selected": false, "text": " SELECT * FROM blog\n WHERE (blog_title LIKE '%barry%' OR blog_content LIKE '%barry%')\n AND (blog_title LIKE '%child%' OR blog_content LIKE '%child%')\n AND (blog_title LIKE '%help%' OR blog_content LIKE '%help%')\n ORDER BY blog_title\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293743", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38020/" ]
293,750
<p>This is in reference to the <a href="https://stackoverflow.com/questions/282944/jquery-one-slider-controls-another">question</a> previously asked</p> <p>The problem here is, each <code>slider</code> controls the other. It results in feedback. </p> <p>How do I possibly stop it?</p> <pre><code>$(function() { $("#slider").slider({ slide: moveSlider2 }); $("#slider1").slider({ slide: moveSlider1 }); function moveSlider2( e, ui ) { $('#slider1').slider( 'moveTo', Math.round(ui.value) ); } function moveSlider1( e, ui ) { $('#slider').slider( 'moveTo', Math.round(ui.value) ); } }); </code></pre>
[ { "answer_id": 293808, "author": "user37125", "author_id": 37125, "author_profile": "https://Stackoverflow.com/users/37125", "pm_score": 3, "selected": true, "text": "$(function () {\n var slider = $(\"#slider\");\n var slider1 = $(\"#slider1\");\n var sliderHandle = $(\"#slider\").find('.ui-slider-handle');\n var slider1Handle = $(\"#slider1\").find('.ui-slider-handle');\n\n slider.slider({ slide: moveSlider1 });\n slider1.slider({ slide: moveSlider });\n\n function moveSlider( e, ui ) {\n sliderHandle.css('left', slider1Handle.css('left'));\n }\n\n function moveSlider1( e, ui ) {\n slider1Handle.css('left', sliderHandle.css('left'));\n }\n});\n" }, { "answer_id": 293816, "author": "Svante", "author_id": 31615, "author_profile": "https://Stackoverflow.com/users/31615", "pm_score": 0, "selected": false, "text": "moveSlider1 moveSlider2" }, { "answer_id": 310944, "author": "Badri", "author_id": 21480, "author_profile": "https://Stackoverflow.com/users/21480", "pm_score": 0, "selected": false, "text": " var s1 = true;\n var s2 = true;\n $('#slider').slider({\n handle: '.slider_handle',\n min: -100,\n max: 100,\n start: function(e, ui) {\n },\n stop: function(e, ui) { \n },\n slide: function(e, ui) {\n if(s1)\n {\n s2 = false;\n $('#slider1').slider(\"moveTo\", ui.value);\n s2 = true;\n }\n }\n });\n\n\n $(\"#slider1\").slider({ \n min: -100, \n max: 100,\n start: function(e, ui) {\n },\n stop: function(e, ui) { \n },\n slide: function(e, ui) {\n if(s2)\n {\n s1 = false;\n $('#slider').slider(\"moveTo\", ui.value);\n s1 = true;\n }\n }\n });\n\n});\n" }, { "answer_id": 8470709, "author": "beginner_", "author_id": 972647, "author_profile": "https://Stackoverflow.com/users/972647", "pm_score": 0, "selected": false, "text": "$('#slider').slider(\"moveTo\", ui.value);\n $('#slider').slider(\"option\", \"value\", ui.value);\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21480/" ]
293,760
<p>Here's what I got so far (that doesn't work). At this point I thought my target was Ansi encoded, but I really don't want to have to know at this point. My browser seems to be able to determine what encoding to use, How can I?</p> <pre><code>static void GetUrl(Uri uri, string localFileName) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); HttpWebResponse response; response = (HttpWebResponse)request.GetResponse(); // Save the stream to file Stream responseStream = response.GetResponseStream(); StreamReader reader = new StreamReader(responseStream, Encoding.Default); Stream fileStream = File.OpenWrite(localFileName); using (StreamWriter sw = new StreamWriter(fileStream, Encoding.Default)) { sw.Write(reader.ReadToEnd()); sw.Flush(); sw.Close(); } } </code></pre> <hr> <p><strong>After answers</strong> (currently only tested on a UTF-8 site):</p> <pre><code>static void GetUrl(Uri uri, string localFileName) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); try { // Hope GetEncoding() knows how to parse the CharacterSet Encoding encoding = Encoding.GetEncoding(response.CharacterSet); StreamReader reader = new StreamReader(response.GetResponseStream(), encoding); using (StreamWriter sw = new StreamWriter(localFileName, false, encoding)) { sw.Write(reader.ReadToEnd()); sw.Flush(); sw.Close(); } } finally { response.Close(); } } </code></pre>
[ { "answer_id": 293763, "author": "lubos hasko", "author_id": 275, "author_profile": "https://Stackoverflow.com/users/275", "pm_score": 3, "selected": true, "text": "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=US-ASCII\">\n <?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n Content-Type: text/html; charset=ISO-8859-1\n" }, { "answer_id": 293775, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 2, "selected": false, "text": "Encoding.Default Stream responseStream = response.GetResponseStream();\nEncoding enc = Encoding.GetEncoding(response.CharacterSet);\nStreamReader reader = new StreamReader(responseStream, enc);\nStream fileStream = File.OpenWrite(localFileName);\nusing (StreamWriter sw = new StreamWriter(fileStream, enc))\n{ /* ... */ }\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16260/" ]
293,761
<p>How can I make Emacs show blank spaces (like a space, a tab, a line-jump, etc). Many other editors like Kate and Eclipse have this feature and I find it very useful to see when code is indent-broken because of mix of spaces and tabs (particularly Python).</p>
[ { "answer_id": 293765, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 3, "selected": false, "text": "(if (>= emacs-major-version 22)\n (progn\n ;; Mode to use with Emacs 22\n ;; http://emacswiki.org/cgi-bin/wiki/BlankMode\n (require 'blank-mode)\n ;; Mode not active by default: let's activate it\n (global-blank-mode t)\n ;; ... activate it when text mode where color syntax is not active by default\n (add-hook 'text-mode-hook 'blank-mode-on)\n ;; All invisible chars are shown, except newline char.\n (setq blank-chars '(tabs spaces trailing lines space-before-tab))\n ;; Show only for one color, no mark inserted\n (setq blank-style '(color))\n ;; Use for normal space (not shown)\n (set-face-background 'blank-space-face nil)\n (set-face-foreground 'blank-space-face \"black\")\n ;; used for non breakable space\n (set-face-background 'blank-hspace-face \"PaleGreen\")\n (set-face-foreground 'blank-hspace-face \"black\")\n ;; Used for spaces left of a tab\n (set-face-background 'blank-space-before-tab-face \"orange\")\n (set-face-foreground 'blank-space-before-tab-face \"black\")\n ;; Used for tab\n (set-face-background 'blank-tab-face \"lemonchiffon\")\n (set-face-foreground 'blank-tab-face \"black\")\n ;; used for extra space at the end of a line\n (set-face-background 'blank-trailing-face \"gold\")\n (set-face-foreground 'blank-trailing-face \"black\")\n ;; Used for line too long\n (set-face-background 'blank-line-face \"snow2\")\n (set-face-foreground 'blank-line-face \"black\")\n )\n (progn\n ;; For older Emacs prior to version 22.\n ;; http://www.emacswiki.org/cgi-bin/wiki/show-wspace.el\n (require 'show-wspace)\n (add-hook 'font-lock-mode-hook 'show-ws-highlight-tabs)\n (add-hook 'font-lock-mode-hook 'show-ws-highlight-hard-spaces)\n (add-hook 'font-lock-mode-hook 'show-ws-highlight-trailing-whitespace)\n )\n)\n" }, { "answer_id": 293795, "author": "Justin Tanner", "author_id": 609, "author_profile": "https://Stackoverflow.com/users/609", "pm_score": 7, "selected": true, "text": "M-x whitespace-mode" }, { "answer_id": 294482, "author": "user37248", "author_id": 37248, "author_profile": "https://Stackoverflow.com/users/37248", "pm_score": 2, "selected": false, "text": "(setq-default indent-tabs-mode nil) C-x h M-x untabify C-s C-i M-x hexl-mode C-x h M-x indent-region" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6068/" ]
293,762
<p>I can't directly add ChartFrame object to my Jframe object with .add(Component) method. And it's not possible to cast from ChartFrame to JComponent. Casting ChartFrame to Component from java.awt library is also impossible. </p> <p>How can I add ChartFrame to JFrame the other way?</p>
[ { "answer_id": 293771, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 1, "selected": false, "text": "JDesktopPane desktop = ...\nJFrame frame = ...\n\nframe.setContentPane(desktop);\n\nJInternalFrame internalFrame = ...\ndesktop.add(internalFrame);\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35594/" ]
293,768
<p>How do I get a patch from a commit in order to send it to another developer? And how do I best avoid a merge conflict with this patch when merging our trees at a later date?</p> <p>If you know how please explain how to do this in your VCS of choice such as subversion, git, Mercurial, bzr or etc.</p>
[ { "answer_id": 293803, "author": "Xian", "author_id": 4642, "author_profile": "https://Stackoverflow.com/users/4642", "pm_score": 2, "selected": false, "text": "svn diff > mypatch.diff\n patch -p0 -i mypatch.diff\n" }, { "answer_id": 293917, "author": "Spoike", "author_id": 3713, "author_profile": "https://Stackoverflow.com/users/3713", "pm_score": 6, "selected": true, "text": "git-diff git diff fa1afe1 deadbeef > patch.diff\n patch.diff git-apply git apply patch.diff\n git apply < git diff fa1afe1 deadbeef\n C* C A---B---C---D master, public/master\n \\\n E---C*---F feature_foo\n git-rebase feature_foo git rebase master feature_foo\n A---B---C---D master, public/master\n \\\n E*---F* feature_foo\n E* F* E F" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3713/" ]
293,774
<p>With wxWidgets I use the following code:</p> <pre><code>HWND main_window = ... ... wxWindow *w = new wxWindow(); wxWindow *window = w->CreateWindowFromHWND(0, (WXHWND) main_window); </code></pre> <p>How do I do the same thing in Qt? The <code>HWND</code> is the handle of the window I want as the parent window for the new QtWidget.</p>
[ { "answer_id": 293778, "author": "ChrisN", "author_id": 3853, "author_profile": "https://Stackoverflow.com/users/3853", "pm_score": 3, "selected": false, "text": "QWinWidget" }, { "answer_id": 293781, "author": "sep", "author_id": 30333, "author_profile": "https://Stackoverflow.com/users/30333", "pm_score": 4, "selected": true, "text": "HWND main_window = ...\n...\nQWidget *w = new QWidget();\nw->create((WinId)main_window);\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1709/" ]
293,780
<p>Is there a way to get the amount of free diskspace of a disk or a folder in a CMD without having to install some thirdparty applications?</p> <p>I have a CMD that copies a big file to a given directory and could of course use the errorlevel return from the copy command, but then I have to wait for the time it takes to copy the file (eg...to that then the disk is full and the copy operation fails).</p> <p>I would like to know before I start the copy if it is any idea at all. Tried the DU.EXE utility from Sysinternals, but that show occupied space only.</p>
[ { "answer_id": 293784, "author": "Nico", "author_id": 22970, "author_profile": "https://Stackoverflow.com/users/22970", "pm_score": 7, "selected": false, "text": "dir c:\\ fsutil volume diskfree c:" }, { "answer_id": 293785, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 6, "selected": false, "text": "dir|find \"bytes free\"\n wmic /node:\"%COMPUTERNAME%\" LogicalDisk Where DriveType=\"3\" Get DeviceID,FreeSpace|find /I \"c:\"\n dir dir" }, { "answer_id": 293839, "author": "tommym", "author_id": 37607, "author_profile": "https://Stackoverflow.com/users/37607", "pm_score": 3, "selected": false, "text": "df -h M:\\>df -h\nFilesystem Size Used Avail Use% Mounted on\nC:/cygwin/bin 932G 78G 855G 9% /usr/bin\nC:/cygwin/lib 932G 78G 855G 9% /usr/lib\nC:/cygwin 932G 78G 855G 9% /\nC: 932G 78G 855G 9% /cygdrive/c\nE: 1.9T 1.3T 621G 67% /cygdrive/e\nF: 1.9T 201G 1.7T 11% /cygdrive/f\nH: 1.5T 524G 938G 36% /cygdrive/h\nM: 1.5T 524G 938G 36% /cygdrive/m\nP: 98G 67G 31G 69% /cygdrive/p\nR: 98G 14G 84G 15% /cygdrive/r\n M:\\>df -h | grep M: | awk '{print $4}'\n" }, { "answer_id": 7304989, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 3, "selected": false, "text": "@setlocal enableextensions enabledelayedexpansion\n@echo off\nfor /f \"tokens=3\" %%a in ('dir c:\\') do (\n set bytesfree=%%a\n)\nset bytesfree=%bytesfree:,=%\necho %bytesfree%\nendlocal && set bytesfree=%bytesfree%\n dir 24 Dir(s) 34,071,691,264 bytes free for bytesfree tokens= , bytesfree dir" }, { "answer_id": 9129605, "author": "Zsolt Hidasi", "author_id": 1128025, "author_profile": "https://Stackoverflow.com/users/1128025", "pm_score": 1, "selected": false, "text": "@echo off\nsetlocal enableextensions enabledelayedexpansion\nset chkfile=drivechk.tmp\nif \"%1\" == \"\" goto :usage\nset drive=%1\nset drive=%drive:\\=%\nset drive=%drive::=%\ndir %drive%:>nul 2>%chkfile%\nfor %%? in (%chkfile%) do (\n set chksize=%%~z?\n)\nif %chksize% neq 0 (\n more %chkfile%\n del %chkfile%\n goto :eof\n)\ndel %chkfile%\nfor /f \"tokens=3\" %%a in ('dir %drive%:\\') do (\n set bytesfree=%%a\n)\nset bytesfree=%bytesfree:,=%\necho %bytesfree% byte(s) free on volume %drive%:\nendlocal\n\ngoto :eof\n:usage\n echo.\n echo usage: freedisk ^<driveletter^> (eg.: freedisk c)\n" }, { "answer_id": 16973715, "author": "lit", "author_id": 447901, "author_profile": "https://Stackoverflow.com/users/447901", "pm_score": 3, "selected": false, "text": "FOR /F \"usebackq tokens=3\" %%s IN (`DIR C:\\ /-C /-O /W`) DO (\n SET FREE_SPACE=%%s\n)\nECHO FREE_SPACE is %FREE_SPACE%\n SET EXITCODE=0\nSET NEEDED=100,000,000\nSET NEEDED=%NEEDED:,=%\n\nIF %FREE_SPACE% LSS %NEEDED% (\n ECHO Not enough.\n SET EXITCODE=1\n)\nEXIT /B %EXITCODE%\n powershell pwsh SET \"NEEDED=100,000,000\"\nSET \"NEEDED=%NEEDED:,=%\"\n\npowershell -NoLogo -NoProfile -Command ^\n $Free = (Get-PSDrive -Name 'C').Free; ^\n if ($Free -lt [int64]%NEEDED%) { exit $true } else { exit $false }\nIF ERRORLEVEL 1 (\n ECHO \"Not enough disk space available.\"\n) else (\n ECHO \"Available disk space is adequate.\"\n)\n" }, { "answer_id": 54494732, "author": "Dewsri De Mel", "author_id": 10049164, "author_profile": "https://Stackoverflow.com/users/10049164", "pm_score": 4, "selected": false, "text": "wmic logicaldisk get size, freespace, caption" }, { "answer_id": 61583378, "author": "Pedro Robson Leão", "author_id": 4163901, "author_profile": "https://Stackoverflow.com/users/4163901", "pm_score": 1, "selected": false, "text": "volume C: - 49 GB total space / 29512314880 byte(s) free @echo off\nsetlocal enableextensions enabledelayedexpansion\nset chkfile=drivechk.tmp\nif \"%1\" == \"\" goto :usage\nset drive=%1\nset drive=%drive:\\=%\nset drive=%drive::=%\ndir %drive%:>nul 2>%chkfile%\nfor %%? in (%chkfile%) do (\n set chksize=%%~z?\n)\nif %chksize% neq 0 (\n more %chkfile%\n del %chkfile%\n goto :eof\n)\ndel %chkfile%\necho list volume | diskpart | find /I \" %drive% \" >%chkfile%\nfor /f \"tokens=6\" %%a in ('type %chkfile%' ) do (\n set dsksz=%%a\n)\nfor /f \"tokens=7\" %%a in ('type %chkfile%' ) do (\n set dskunit=%%a\n)\ndel %chkfile%\nfor /f \"tokens=3\" %%a in ('dir %drive%:\\') do (\n set bytesfree=%%a\n)\nset bytesfree=%bytesfree:,=%\necho volume %drive%: - %dsksz% %dskunit% total space / %bytesfree% byte(s) free\nendlocal\n\ngoto :eof\n:usage\n echo.\n echo usage: freedisk ^<driveletter^> (eg.: freedisk c)\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
293,790
<p>I am trying to wire up dependency injection with Windsor to standard asp.net web forms. I think I have achieved this using a HttpModule and a CustomAttribute (code shown below), although the solution seems a little clunky and was wondering if there is a better supported solution out of the box with Windsor?</p> <p>There are several files all shown together here</p> <pre><code> // index.aspx.cs public partial class IndexPage : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Logger.Write("page loading"); } [Inject] public ILogger Logger { get; set; } } // WindsorHttpModule.cs public class WindsorHttpModule : IHttpModule { private HttpApplication _application; private IoCProvider _iocProvider; public void Init(HttpApplication context) { _application = context; _iocProvider = context as IoCProvider; if(_iocProvider == null) { throw new InvalidOperationException("Application must implement IoCProvider"); } _application.PreRequestHandlerExecute += InitiateWindsor; } private void InitiateWindsor(object sender, System.EventArgs e) { Page currentPage = _application.Context.CurrentHandler as Page; if(currentPage != null) { InjectPropertiesOn(currentPage); currentPage.InitComplete += delegate { InjectUserControls(currentPage); }; } } private void InjectUserControls(Control parent) { if(parent.Controls != null) { foreach (Control control in parent.Controls) { if(control is UserControl) { InjectPropertiesOn(control); } InjectUserControls(control); } } } private void InjectPropertiesOn(object currentPage) { PropertyInfo[] properties = currentPage.GetType().GetProperties(); foreach(PropertyInfo property in properties) { object[] attributes = property.GetCustomAttributes(typeof (InjectAttribute), false); if(attributes != null &amp;&amp; attributes.Length &gt; 0) { object valueToInject = _iocProvider.Container.Resolve(property.PropertyType); property.SetValue(currentPage, valueToInject, null); } } } } // Global.asax.cs public class Global : System.Web.HttpApplication, IoCProvider { private IWindsorContainer _container; public override void Init() { base.Init(); InitializeIoC(); } private void InitializeIoC() { _container = new WindsorContainer(); _container.AddComponent&lt;ILogger, Logger&gt;(); } public IWindsorContainer Container { get { return _container; } } } public interface IoCProvider { IWindsorContainer Container { get; } } </code></pre>
[ { "answer_id": 969668, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "ILogger Logger = ResolveType.Of<ILogger>();\n" }, { "answer_id": 21038393, "author": "Mike Chamberlain", "author_id": 289319, "author_profile": "https://Stackoverflow.com/users/289319", "pm_score": 2, "selected": false, "text": "// global.asax.cs\npublic class Global : HttpApplication\n{\n private static IWindsorContainer _container;\n\n protected void Application_Start(object sender, EventArgs e)\n {\n _container = new WindsorContainer();\n _container.Install(FromAssembly.This());\n }\n\n internal static object Resolve(Type type)\n {\n return _container.Resolve(type);\n }\n\n internal static void Release(object component)\n {\n _container.Release(component);\n }\n\n //...\n}\n\n// WindsorHttpModule.cs\npublic class WindsorHttpModule : IHttpModule\n{\n // cache the properties to inject for each page\n private static readonly ConcurrentDictionary<Type, PropertyInfo[]> InjectedProperties = new ConcurrentDictionary<Type, PropertyInfo[]>();\n private HttpApplication _context;\n\n public void Init(HttpApplication context)\n {\n _context = context;\n _context.PreRequestHandlerExecute += InjectProperties;\n _context.EndRequest += ReleaseComponents;\n }\n\n private void InjectProperties(object sender, EventArgs e)\n {\n var currentPage = _context.Context.CurrentHandler as Page;\n if (currentPage != null)\n {\n InjectProperties(currentPage);\n currentPage.InitComplete += delegate { InjectUserControls(currentPage); };\n }\n }\n\n private void InjectUserControls(Control parent)\n {\n foreach (Control control in parent.Controls)\n {\n if (control is UserControl)\n {\n InjectProperties(control);\n }\n InjectUserControls(control);\n }\n }\n\n private void InjectProperties(Control control)\n {\n ResolvedComponents = new List<object>();\n var pageType = control.GetType();\n\n PropertyInfo[] properties;\n if (!InjectedProperties.TryGetValue(pageType, out properties))\n {\n properties = control.GetType().GetProperties()\n .Where(p => p.GetCustomAttributes(typeof(InjectAttribute), false).Length > 0)\n .ToArray();\n InjectedProperties.TryAdd(pageType, properties);\n }\n\n foreach (var property in properties)\n {\n var component = Global.Resolve(property.PropertyType);\n property.SetValue(control, component, null);\n ResolvedComponents.Add(component);\n }\n }\n\n private void ReleaseComponents(object sender, EventArgs e)\n {\n var resolvedComponents = ResolvedComponents;\n if (resolvedComponents != null)\n {\n foreach (var component in ResolvedComponents)\n {\n Global.Release(component);\n }\n }\n }\n\n private List<object> ResolvedComponents\n {\n get { return (List<object>)HttpContext.Current.Items[\"ResolvedComponents\"]; }\n set { HttpContext.Current.Items[\"ResolvedComponents\"] = value; }\n }\n\n public void Dispose()\n { }\n\n}\n" }, { "answer_id": 42363648, "author": "Remus.A", "author_id": 4233146, "author_profile": "https://Stackoverflow.com/users/4233146", "pm_score": 1, "selected": false, "text": "<system.webServer>\n <modules>\n <add name=\"ClassNameForHttpModuleHere\" type=\"NamespaceForClass\"/>\n </modules>\n </system.webServer>\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4642/" ]
293,794
<p>Greetings,</p> <p>I have data stored on mysql with delimiter "," in 1 table. I have rows and column stored on database too. Now i have to output the data using rows and column number stored on database to draw the table.</p> <p>Rows and column number are user input, so it may varies.</p> <p>Let say, there is number 3 on column and 3 on rows.</p> <p>I need to do it like display like,</p> <pre><code>|___d1__|___d2__|___d3__| |___d4__|___d5__|___d6__| |___d7__|___d8__|___d9__| </code></pre> <p>Where d1-d9 would be the data stored on mysql database with delimiter "," in one table.</p> <p>Thanks for helping me.</p>
[ { "answer_id": 293876, "author": "foxy", "author_id": 30119, "author_profile": "https://Stackoverflow.com/users/30119", "pm_score": 4, "selected": true, "text": "<?php\n $result = mysql_query('SELECT rows, columns, data from table_name where id=1');\n $record = mysql_fetch_assoc($result);\n\n $rows = $record['rows'];\n $columns = $record['columns'];\n\n $data = explode(',' , $record['data']);\n\n if (sizeof($data) != $rows * $columns) die('invalid data');\n?>\n <table>\n<?php for ($row = 0; $row < $rows; $row++) : ?>\n <tr>\n <?php for ($column = 0; $column < $columns; $column++) : ?>\n <td>\n <?php echo $data[$row * $columns + $column]; ?>\n </td>\n <?php endfor ?>\n </tr>\n<?php endfor ?>\n</table>\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37922/" ]
293,799
<p>The <em>VS2008 SP1</em> documentation talks about <strong><code>std::tr1::mem_fun</code></strong>.</p> <p>So why, when I try and use <strong><code>std::tr1::mem_fun</code></strong>, why do I get this compile error?:</p> <pre><code>'mem_fun' : is not a member of 'std::tr1' </code></pre> <p>At the same time, I can use <strong><code>std::tr1::function</code></strong> without problems.</p> <p>Here is the sample code I am trying to compile, which is supposed to call <code>TakesInt</code> on an instance of <code>Test</code>, via a <code>function&lt;void (int)&gt;</code>:</p> <pre><code>#include "stdafx.h" #include &lt;iostream&gt; #include &lt;functional&gt; #include &lt;memory&gt; struct Test { void TakesInt(int i) { std::cout &lt;&lt; i; } }; void _tmain() { Test* t = new Test(); //error C2039: 'mem_fun' : is not a member of 'std::tr1' std::tr1::function&lt;void (int)&gt; f = std::tr1::bind(std::tr1::mem_fun(&amp;Test::TakesInt), t); f(2); } </code></pre> <p>I'm trying to use the tr1 version of <strong><code>mem_fun</code></strong>, because when using <strong><code>std::mem_fun</code></strong> my code doesn't compile either! I can't tell from the compiler error whether the problem is with my code or whether it would be fixed by using tr1's <strong><code>mem_fun</code></strong>. That's C++ compiler errors for you (or maybe it's just me!).</p> <p><HR/></p> <h2>Update: Right. The answer is to spell it correctly as mem_fn!</h2> <p>However when I fix that, the code still doesn't compile. </p> <p>Here's the compiler error:</p> <pre><code>error C2562: 'std::tr1::_Callable_obj&lt;_Ty,_Indirect&gt;::_ApplyX' : 'void' function returning a value </code></pre>
[ { "answer_id": 293872, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 1, "selected": false, "text": " std::tr1::mem_fun<Test,void (Test::*)(Test*),&Test::TakesInt>()\n std::tr1::mem_fn(&Test::TakesInt)\n f= std::bind1st(std::tr1::mem_fn(&Test::TakesInt), t);\n" }, { "answer_id": 293971, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 3, "selected": true, "text": "std::tr1::function<void (int)> f =\n std::tr1::bind(std::tr1::mem_fn(&Test::TakesInt), t, std::tr1::placeholders::_1);\nf(2);\n std::tr1::function<void (int)> f =\n std::tr1::bind(&Test::TakesInt, t, std::tr1::placeholders::_1);\nf(2);\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25457/" ]
293,806
<p>What I would like to do is have VS2008, when I open a code file, collapse all members of the classes/interfaces in the file by default (including, crucially, any XML documentation and comments).</p> <p>I do <em>not</em> want to use regions, at all.</p> <p>I would also like to be able to use the ctrl+m, ctrl+l chord to toggle all <em>member</em> outlining (for example, if everything is collapsed, I would like it to expand all of the members, but not the comments or XML documentation).</p> <p>Possible? How?</p>
[ { "answer_id": 296891, "author": "Brody", "author_id": 17131, "author_profile": "https://Stackoverflow.com/users/17131", "pm_score": 4, "selected": true, "text": "\n switch (connectMode)\n {\n case ext_ConnectMode.ext_cm_UISetup:\n case ext_ConnectMode.ext_cm_Startup:\n //Do nothing OnStartup will be called once IDE is initialised.\n break;\n case ext_ConnectMode.ext_cm_AfterStartup:\n //The addin was started post startup so we need to call its initialisation manually\n InitialiseHandlers();\n break;\n }\n \n private void InitialiseHandlers()\n {\n this._openHandler = new OnOpenHandler(_applicationObject);\n }\n \n public void OnStartupComplete(ref Array custom)\n {\n InitialiseHandlers();\n }\n \n using System;\n using System.Collections.Generic;\n using System.Text;\n using EnvDTE80;\n using EnvDTE;\n using System.Threading;\n\n namespace Collapser\n {\n internal class OnOpenHandler\n {\n DTE2 _application = null;\n EnvDTE.Events events = null;\n EnvDTE.DocumentEvents docEvents = null;\n\n internal OnOpenHandler(DTE2 application)\n {\n _application = application;\n events = _application.Events;\n docEvents = events.get_DocumentEvents(null);\n docEvents.DocumentOpened +=new _dispDocumentEvents_DocumentOpenedEventHandler(OnOpenHandler_DocumentOpened);\n }\n\n void OnOpenHandler_DocumentOpened(EnvDTE.Document document)\n {\n if (_application.Debugger.CurrentMode != dbgDebugMode.dbgBreakMode)\n {\n ThreadPool.QueueUserWorkItem(new WaitCallback(Collapse));\n }\n }\n\n private void Collapse(object o)\n {\n System.Threading.Thread.Sleep(150);\n _application.ExecuteCommand(\"Edit.CollapsetoDefinitions\", \"\");\n }\n }\n }\n" }, { "answer_id": 1050267, "author": "Sarah Vessels", "author_id": 38743, "author_profile": "https://Stackoverflow.com/users/38743", "pm_score": 0, "selected": false, "text": "EnvironmentEvents" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20971/" ]
293,814
<p>Helo!</p> <p>Is this possible to use string value of one node which tells what type of field is presented in another node using LINQ to XML?</p> <p>For example:</p> <pre><code>&lt;node&gt; &lt;name&gt;nodeName&lt;/name&gt; &lt;type&gt;string&lt;/type&gt; &lt;/node&gt; &lt;node&gt; &lt;name&gt;0&lt;/name&gt; &lt;type&gt;bool&lt;/type&gt; &lt;/node&gt; &lt;node&gt; &lt;name&gt;42&lt;/name&gt; &lt;type&gt;int&lt;/type&gt; &lt;/node&gt; </code></pre> <p>Thanks in advance</p>
[ { "answer_id": 293891, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": true, "text": "System.Object public static object ParseValue(this XElement element)\n{\n XElement name = element.Element(\"name\");\n XElement type = element.Element(\"type\");\n // Insert error handling here :)\n\n switch (type.Value)\n {\n case \"int\":\n return int.Parse(name.Value);\n case \"string\":\n return name.Value;\n case \"bool\":\n return name.Value == \"1\"; // Or whatever\n default:\n throw new ArgumentException(\"Unknown element type \" + type.Value);\n }\n}\n" }, { "answer_id": 293896, "author": "jyoung", "author_id": 14841, "author_profile": "https://Stackoverflow.com/users/14841", "pm_score": 2, "selected": false, "text": "public static void Main() {\n var xmlNodes = new XElement( \"Nodes\",\n new XElement( \"Node\",\n new XElement( \"Name\", \"nodeName\" ),\n new XElement( \"Type\", \"string\" )\n ),\n new XElement( \"Node\",\n new XElement( \"Name\", \"True\" ),\n new XElement( \"Type\", \"bool\" )\n ),\n new XElement( \"Node\",\n new XElement( \"Name\", \"42\" ),\n new XElement( \"Type\", \"int\" )\n )\n );\n\n var converters = new Dictionary<string,Func<string,object> > {\n { \"string\", val => val },\n { \"bool\", val => Boolean.Parse( val ) },\n { \"int\", val => Int32.Parse( val ) }\n };\n\n var values = \n from node in xmlNodes.Elements( \"Node\" )\n select converters[ node.Element( \"Type\" ).Value ]( node.Element( \"Name\" ).Value );\n\n foreach( var value in values )\n Console.WriteLine( value.GetType().ToString() + \": \" + value );\n}\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23280/" ]
293,831
<p>For example, I make extensive use of the session in my ASP.NET application but have heard somewhere that objects stored in session can be removed by the system where server memory runs low. Is this true? Is there any session 'callback' functionality to allow you to re-populate scavenged objects? </p> <p>More generally, what other potential problems of using session state are there, and what are the suggested best practices for dealing with them?</p>
[ { "answer_id": 293962, "author": "Corbin March", "author_id": 7625, "author_profile": "https://Stackoverflow.com/users/7625", "pm_score": 2, "selected": false, "text": "Dim sessionObj As Object = CType(Session(\"SessionKey\"), Object)\nIf sessionObj Is Nothing\n sessionObj = ReCreateObj()\n Session(\"SessionKey\") = sessionObj\nEnd If\n\nobject sessionObj = Session[\"SessionKey\"] as object ;\nif(sessionObj == null)\n{\n sessionObj = ReCreateObj();\n Session[\"SessionKey\"] = sessionObj;\n}\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27805/" ]
293,832
<p>I am currently building an application using ASP.NET MVC. The data entry pages are fairly easy to code, I just make the Model for the page of the type of my business object:</p> <pre><code>namespace MyNameSpace.Web.Views.ProjectEdit { public partial class MyView : ViewPage&lt;Project&gt; { } } </code></pre> <p>Where I am struggling is figuring out the best way to implement a dashboard like interface, with stand-alone parts, using ASP.NET MVC, where the Model for each part would be different? I'm <strong>assuming</strong> that each part would be an MVC user control. </p> <p>Also, how could I make it so each part is testable?</p>
[ { "answer_id": 293902, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 4, "selected": true, "text": "<% MyUserControlModel model = ViewData[\"MyUserControlModel\"]\n as MyUserControlModel; %>\n\n<div id=\"myUserControl_dashboard\" class=\"dashboard\">\n Name: <%= model.Name %><br />\n Count: <%$ model.Count %>\n</div>\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1768/" ]
293,840
<p>This is probably a simple question. Suppose I have a object called Users and it contains a lot of protected variables. </p> <p>Inside that Users class I have a method that creates a temporary Users object, does something with it, and if successful, transfers all the variables from the temp Users object into the one I have. </p> <p>Is there some fast way to transfer all the variables from one Users object into another Users object without doing this using C#?</p> <pre><code>this.FirstName = temp.FirstName; this.LastName = temp.LastName; ........75 variables later...... this.FavoriteColor = temp.FavoriteColor </code></pre>
[ { "answer_id": 293851, "author": "MusiGenesis", "author_id": 14606, "author_profile": "https://Stackoverflow.com/users/14606", "pm_score": 0, "selected": false, "text": "_User = tmpUser;\n" }, { "answer_id": 6693578, "author": "Mr. Graves", "author_id": 171518, "author_profile": "https://Stackoverflow.com/users/171518", "pm_score": 0, "selected": false, "text": "public static void Copy(object source, object target)\n {\n foreach (System.Reflection.PropertyInfo pi in source.GetType().GetProperties())\n {\n System.Reflection.PropertyInfo tpi = target.GetType().GetProperty(pi.Name);\n if (tpi != null && tpi.PropertyType.IsAssignableFrom(pi.PropertyType))\n {\n tpi.SetValue(target, pi.GetValue(source, null), null);\n }\n\n }\n }\n class sourceTester\n{\n public bool Hello { get; set; }\n public string World { get; set; }\n public int Foo { get; set; }\n public List<object> Bar { get; set; }\n}\n\nclass targetTester\n{\n public int Hello {get; set;}\n public string World { get; set; }\n public double Foo { get; set; }\n public List<object> Bar { get; set; }\n}\n\nstatic void Main(string[] args)\n {\n\n\n sourceTester src = new sourceTester { \n Hello = true, \n World = \"Testing\",\n Foo = 123,\n Bar = new List<object>()\n };\n\n targetTester tgt = new targetTester();\n\n Copy(src, tgt);\n\n //Immediate Window shows the following:\n //tgt.Hello\n //0\n //tgt.World\n //\"Testing\"\n //tgt.Foo\n //0.0\n //tgt.Bar\n //Count = 0\n //src.Bar.GetHashCode()\n //59129387\n //tgt.Bar.GetHashCode()\n //59129387\n }\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10352/" ]
293,853
<p>I would like to add custom tooltips to emacs. More specifically, whenever I hover on a symbol (function/variable) name with my mouse of I would like to see a tooltip with the symbol's definition. I know that I can find this kind of info with a tool like cscope but I have no idea how to attach the output of cscope to a tooltip. does anyone have a partial (how to link a callback to a tooltip in emacs in general) or a full (how do I actually link the output of cscope to a tooltip) solution to this?</p> <p>Thanks, Nir</p>
[ { "answer_id": 293887, "author": "Jouni K. Seppänen", "author_id": 26575, "author_profile": "https://Stackoverflow.com/users/26575", "pm_score": 5, "selected": true, "text": "i tooltip help-echo (insert (propertize \"foo\\n\" 'help-echo \"Tooltip!\"))\n *scratch* C-j" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33707/" ]
293,857
<pre><code>class String { private: char* rep; public: String (const char*); void toUpper() const; }; String :: String (const char* s) { rep = new char [strlen(s)+1]; strcpy (rep, s); } void String :: toUpper () const { for (int i = 0; rep [i]; i++) rep[i] = toupper(rep[i]); } int main () { const String lower ("lower"); lower.toUpper(); cout &lt;&lt; lower &lt;&lt; endl; return 0; } </code></pre>
[ { "answer_id": 293867, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 1, "selected": false, "text": "class String\n{\n std::string rep;\n\n void toUpper() const\n { \n for (int i = 0; rep [i]; i++)\n rep[i] = toupper(rep[i]);\n\n // Can only use const member functions on rep.\n // So here we use 'char const& std::string::operator[](size_t) const'\n // There is a non const version but we are not allowed to use it\n // because this method is const.\n\n // So the return type is 'char const&'\n // This can be used in the call to toupper()\n // But not on the lhs of the assignemnt statement\n\n }\n}\n" }, { "answer_id": 293868, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 5, "selected": true, "text": "int x;\nchar c;\nchar *p;\n const int x;\nconst char c;\nchar * const p; //<-- means you cannot change what p points to, but you can change the data p points to\n char * rep;\n char rep[1024];\n rep = new char [strlen(s)+1];\n class String\n{\n\n private:\n char rep2[1024];\n char* rep;\n\n ...\n\n\n String :: String (const char* s)\n {\n rep = rep2;\n strcpy (rep, s); \n }\n" }, { "answer_id": 293875, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 2, "selected": false, "text": "rep rep = ...; char*const rep;\n const char* rep;\n rep[i] = ...; *(rep + i) = ...; physical constness logical const const-correctness std::string" }, { "answer_id": 294006, "author": "JohnMcG", "author_id": 1674, "author_profile": "https://Stackoverflow.com/users/1674", "pm_score": 1, "selected": false, "text": "const char* rep;\n const char* const rep;\n char* const rep;\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38038/" ]
293,882
<p>i need to check whether the user clicking the browser Refresh button and redirect to error page. Can we do this in javascript or any server side methods in ASP.net</p>
[ { "answer_id": 293933, "author": "José Leal", "author_id": 37190, "author_profile": "https://Stackoverflow.com/users/37190", "pm_score": 1, "selected": false, "text": "if (Session[\"synctoken\"] != null) {\n if (Request.QueryString[\"synctoken\"] != null) {\n if (Request.QueryString[\"synctoken\"].ToString().Equals(Session[\"synctoken\"].ToString())) {\n // Refresh! Goto Error!\n MyUtil.GotoError();\n }\n else {\n // It is ok, store the token and go on!\n Session[\"synctoken\"] = Request.QueryString[\"synctoken\"];\n }\n }\n else {\n MyUtil.GotoErrorPage();\n }\n}\nelse {\n Session[\"synctoken\"] = MyUtil.GenerateToken();\n}\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293882", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22162/" ]
293,900
<p>It's 5 button clicks to get eclipse to create a deployable war file for my eclipse project, I figure there's probably some eclipse command line option to do the same thing, so I can just write it into a script, but I'm not seeing it.</p>
[ { "answer_id": 293907, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": true, "text": "war" }, { "answer_id": 18686657, "author": "Honza", "author_id": 1576461, "author_profile": "https://Stackoverflow.com/users/1576461", "pm_score": 0, "selected": false, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project name=\"Deploy From Eclipse to JBoss\" basedir=\".\" default=\"deploy\">\n\n <!-- This replace with yours project name and JBoss location: -->\n <property name=\"warfile\" value=\"MyProject\"/>\n <property name=\"deploy\" value=\"/home/honza/jboss-as-7.1.1.Final/standalone/deployments\"/>\n\n <target name=\"create\">\n <war destfile=\"${warfile}.war\" webxml=\"WebContent/WEB-INF/web.xml\" update=\"true\">\n <classes dir=\"build\\classes\"/>\n <fileset dir=\"WebContent\">\n <exclude name=\"WEB-INF/web.xml\"/>\n </fileset>\n </war>\n </target>\n <target name=\"copy\">\n <copy todir=\"${deploy}\" overwrite=\"true\">\n <fileset dir=\".\">\n <include name=\"${warfile}.war\"/>\n </fileset>\n </copy>\n </target>\n <target name=\"clear\">\n <delete includeemptydirs=\"true\">\n <fileset dir=\"${deploy}\" defaultexcludes=\"false\">\n <include name=\"${warfile}.*/**\" />\n </fileset>\n </delete>\n </target>\n <target name=\"deploy\">\n <antcall target=\"create\"/>\n <antcall target=\"clear\"/>\n <antcall target=\"copy\"/>\n </target>\n</project>\n MyProject - Properties - New - Ant builder\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293900", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12386/" ]
293,905
<p>If I have the following code:</p> <pre><code>MyType&lt;int&gt; anInstance = new MyType&lt;int&gt;(); Type type = anInstance.GetType(); </code></pre> <p>How can I find out which type argument(s) &quot;anInstance&quot; was instantiated with, by looking at the type variable? Is it possible?</p>
[ { "answer_id": 293908, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 7, "selected": true, "text": "using System;\nusing System.Collections.Generic;\n\npublic class Test\n{\n static void Main()\n {\n var dict = new Dictionary<string, int>();\n\n Type type = dict.GetType();\n Console.WriteLine(\"Type arguments:\");\n foreach (Type arg in type.GetGenericArguments())\n {\n Console.WriteLine(\" {0}\", arg);\n }\n }\n}\n Type arguments:\n System.String\n System.Int32\n" }, { "answer_id": 293910, "author": "Hans Passant", "author_id": 17034, "author_profile": "https://Stackoverflow.com/users/17034", "pm_score": 4, "selected": false, "text": "using System;\nusing System.Reflection;\n\nnamespace ConsoleApplication1 {\n class Program {\n static void Main(string[] args) {\n MyType<int> anInstance = new MyType<int>();\n Type type = anInstance.GetType();\n foreach (Type t in type.GetGenericArguments())\n Console.WriteLine(t.Name);\n Console.ReadLine();\n }\n }\n public class MyType<T> { }\n}\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13627/" ]
293,915
<p>I have a VS solution, with the following projects.</p> <p>-GUI<br> -DataAccess<br> -BusinessLogic<br> -BusinessObjects </p> <p>but where should the main model class reside? This is usually a cache of a set of objects which are the results from the data access layer and the GUI using virtual grids to view data inside the model. The question would be the same using MVC or MVP</p> <p>thoughts?</p>
[ { "answer_id": 294015, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 1, "selected": false, "text": "Justice.Project.Core Justice.Project.Data Justice.Project.Services Justice.Project.(Web|UI)" }, { "answer_id": 294120, "author": "Kyle West", "author_id": 34133, "author_profile": "https://Stackoverflow.com/users/34133", "pm_score": 0, "selected": false, "text": "IRespoistory<Client> repository = new Repository<Client>();\nIList<Client> clients = repository.GetAllClients();\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4653/" ]
293,916
<p>given the following class ...</p> <pre><code>public class Category { public string Name {get;set;} public Category ParentCategory {get;set;} } </code></pre> <p>What the most efficient way to output the following from a collection (<code>IList&lt;Category&gt;</code>) of Category objects?</p> <pre><code>+ Parent Category ++ Sub Category ++ Sub Category 2 + Parent Category 2 ++ Sub ... ++ Sub .. ++ Sub .... </code></pre> <p>EDIT: Perhaps the real question should be, how should I represent this model in the database and retrieve it using NHibernate? </p>
[ { "answer_id": 293942, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 2, "selected": false, "text": "static void recurseCategories(ref List<Category> cl, Category start, int level)\n{\n foreach (Category child in cl)\n {\n if (child.ParentCategory == start)\n {\n Console.WriteLine(new String(' ', level) + child.Name);\n recurseCategories(ref cl, child, level + 1);\n }\n }\n}\n List Category null recurseCategories(ref myCategoryList, null, 0)" }, { "answer_id": 294042, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 0, "selected": false, "text": "class Program\n{\n static void Main(string[] args)\n {\n var foo = new List<Category>();\n\n // Example structure from Question\n var fail1 = new Category() { Name = \"test1\" };\n var fail2 = new Category() { Name = \"test2\", ParentCategory = fail1 };\n var fail3 = new Category() { Name = \"test3\", ParentCategory = fail1 };\n var fail4 = new Category() { Name = \"test4\"};\n var fail5 = new Category() { Name = \"test5\", ParentCategory = fail4 };\n var fail6 = new Category() { Name = \"test6\", ParentCategory = fail4 };\n var fail7 = new Category() { Name = \"test7\", ParentCategory = fail4 };\n\n foo.Add(fail1);\n foo.Add(fail4);\n\n recurseCategories(ref foo, null, 0);\n\n }\n\n static void recurseCategories(ref List<Category> cl, Category start, int level)\n {\n foreach (Category child in cl)\n {\n if (child.ParentCategory == start)\n {\n Console.WriteLine(new String(' ', level) + child.Name);\n recurseCategories(ref cl, child, level + 1);\n }\n }\n }\n\n public class Category\n {\n public string Name { get; set; }\n public Category ParentCategory { get; set; }\n }\n\n}\n test1\ntest4\n test1\n test 2\n test 3\ntest 4\n test 5\n test 6\n test 7\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34133/" ]
293,929
<p>I'd like to play sound file which loaded from internet, so I tried to start from iPhone SDK SpeakHere sample. I recorded the sound, then saved and uploaded to the internet, I could download that file and play without problem from sound tools. But when I tried to play that URL from SpeakHere, I am getting error <code>Program received signal: “EXC_BAD_ACCESS”</code>.</p> <p>After trace around, I found that the in <code>-[AudioPlayer calculateSizesFor:]</code>, it set <code>bufferByteSize</code> to a huge number 806128768, which caused buffer allocation failed.</p> <p>And that because in</p> <pre><code>AudioFileGetProperty(audioFileID, kAudioFilePropertyPacketSizeUpperBound, &amp;propertySize, &amp;maxPacketSize); </code></pre> <p>The <code>maxPacketSize</code> returned is 806128768.</p> <p>I am wondering how to make <code>AudioFileGetProperty</code> work.</p> <p>My sound file is <a href="http://chineseresume.com/localbiz/uploads/myfilename_7_Recording.caf" rel="nofollow noreferrer">here</a>, you could right-click and download from <a href="http://chineseresume.com/test.html" rel="nofollow noreferrer">here</a>.</p> <p>I am using this way to set the URL in the <code>-[AudioViewController playOrStop]</code> method:</p> <pre><code>// AudioPlayer *thePlayer = [[AudioPlayer alloc] initWithURL: self.soundFileURL]; AudioPlayer *thePlayer = [[AudioPlayer alloc] initWithURL: [NSURL URLWithString: @"http://chineseresume.com/localbiz/uploads/myfilename_7_Recording.caf"]]; </code></pre> <p>Any suggestion is highly welcome.</p>
[ { "answer_id": 294722, "author": "BlueDolphin", "author_id": 32096, "author_profile": "https://Stackoverflow.com/users/32096", "pm_score": 1, "selected": false, "text": "-(CFURLRef)saveURL:(NSString *)urlString {\n NSURL *url = (NSURL*)[[NSURL alloc] initWithString:urlString];\n NSData *data = [[NSData alloc] initWithContentsOfURL:url];\n NSArray *filePaths = NSSearchPathForDirectoriesInDomains ( NSDocumentDirectory, NSUserDomainMask, YES ); \n\n NSString *recordingDirectory = [filePaths objectAtIndex: 0];\n\n CFStringRef fileString = (CFStringRef) [NSString stringWithFormat: @\"%@/BufferFile.caf\", recordingDirectory];\n NSLog(@\"fileString = %@\" , fileString);\n // create the file URL that identifies the file that the recording audio queue object records into\n CFURLRef fileURL = CFURLCreateWithFileSystemPath ( NULL, fileString, kCFURLPOSIXPathStyle, false);\n SInt32 err = 0;\n\n CFURLWriteDataAndPropertiesToResource (\n fileURL, (CFDataRef)data, nil, &err);\n return fileURL;\n}\n" }, { "answer_id": 309514, "author": "Marc Novakowski", "author_id": 27020, "author_profile": "https://Stackoverflow.com/users/27020", "pm_score": 2, "selected": false, "text": "AudioFileStreamOpen AudioFileStreamParseBytes" }, { "answer_id": 315303, "author": "amrox", "author_id": 4468, "author_profile": "https://Stackoverflow.com/users/4468", "pm_score": 3, "selected": true, "text": "/Developer/Examples/CoreAudio/Services/AudioFileStreamExample/\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32096/" ]
293,946
<p>In this query:</p> <pre><code>SELECT COUNT(*) AS UserCount, Company.* FROM Company LEFT JOIN User ON User.CompanyId = Company.Id WHERE Company.CanAccessSystem= true AND(User.CanAccessSystem IS null OR User.CanAccessSystem = true) GROUP BY Company.Id </code></pre> <p>I want to query a list of companies that can access a particular system as well as the number of users who can access the system inside the company. </p> <p>This query works for all cases except for one very important one. If a company can access a the system but none of the users can, the Company disappears completely from the query (i.e.: Users.CanAccessSystem = false). In that case, I just want the UserCount = 0. </p> <p>Example From Companies that Can Access the System:</p> <pre><code>Users Company Name 1 WidgetWorks 3 WidgetCompany 0 WidgesRUs </code></pre> <p>This system is on MySQL</p> <p>Query Edit: Fixed a Typo "ON User.CompanyId = Company.Id"</p>
[ { "answer_id": 293993, "author": "bart", "author_id": 19966, "author_profile": "https://Stackoverflow.com/users/19966", "pm_score": 0, "selected": false, "text": " count(case when User.CanAccessSystem then true end)\n count(expr) SELECT COUNT(case when User.CanAccessSystem then true end) AS UserCount, Company.*\nFROM Company LEFT JOIN User\nON Company.id = user.companyId -- I had to guess, this seems to be missing in your query\nWHERE Company.CanAccessSystem= true\nGROUP BY Company.Id\n" }, { "answer_id": 294047, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 2, "selected": false, "text": "User.CanAccessSystem IS NULL SELECT Company.ID, COUNT(*) AS UserCount\n FROM Company, User\n WHERE Company.ID = User.CompanyID\n AND User.CanAccessSystem = true\nUNION\nSELECT Company.ID, 0 AS UserCount\n FROM Company\n WHERE NOT EXISTS (SELECT * FROM User\n WHERE Company.ID = User.CompanyID\n AND User.CanAccessSystem = true)\n SELECT UserCount, Company.*\n FROM Company JOIN\n (SELECT Company.ID AS ID, COUNT(*) AS UserCount\n FROM Company, User\n WHERE Company.ID = User.CompanyID\n AND User.CanAccessSystem = true\n UNION\n SELECT Company.ID AS ID, 0 AS UserCount\n FROM Company\n WHERE NOT EXISTS (SELECT * FROM User\n WHERE Company.ID = User.CompanyID\n AND User.CanAccessSystem = true)\n ) AS NumUsers\n ON Company.ID = NumUsers.ID\n WHERE Company.CanAccessSystem = true\n" }, { "answer_id": 294107, "author": "Leon Tayson", "author_id": 18413, "author_profile": "https://Stackoverflow.com/users/18413", "pm_score": 0, "selected": false, "text": "SELECT c.CompanyID, c.CompanyName, SUM(CASE u.CanAccessSystem WHEN 1 then 1 else 0 end) \nFROM Company c LEFT OUTER JOIN\n [User] u\nON u.CompanyID = c.CompanyID\nWHERE c.CanAccessSystem = 1\nGROUP BY c.CompanyID, c.CompanyName\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293946", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10352/" ]
293,948
<p>I have a question to the submit- button behavior of internet explorer. If I load the page everything is fine - the submit button looks as it should. </p> <p><a href="http://img58.imageshack.us/img58/7214/inactiveci9.jpg" rel="nofollow noreferrer">Inactive state http://img58.imageshack.us/img58/7214/inactiveci9.jpg</a></p> <p>But if I click inside the FORM, the submit button gets some additional style which I don't like (see image for more information).</p> <p><a href="https://i.stack.imgur.com/y9hpz.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/y9hpz.jpg" alt="Active state"></a></p> <p>How can I disable this behavior. I'm using IE7 under Vista.</p>
[ { "answer_id": 293991, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 2, "selected": false, "text": "blur()" }, { "answer_id": 294022, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 4, "selected": true, "text": "input:focus, \ninput:active, \ninput:hover \n{ \n outline: none; \n border: 1px solid; \n} \n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2078/" ]
293,956
<p>I've been working with jQuery for a pair of weeks and I've noticed it works fine with objects that are in the original HTML document, but when I generate a new element using jQuery the library doesn't get any of its events.</p> <p>Let's say I try to run something like this:</p> <pre><code>$('.whatever').click(function() { alert("ALERT!"); }); </code></pre> <p>If the HTML does have something like this:</p> <pre><code>&lt;span class="whatever"&gt;Whatever&lt;/span&gt; </code></pre> <p>Then clicking on the word <code>Whatever</code> gets me a nice alert.</p> <p>But if the <code>span</code> element is added dynamically using jQuery, nothing happens when clicking on it.</p> <p>Is there a way to make jQuery work with those elements, somehow?</p>
[ { "answer_id": 293973, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "function bindme(){\n $('.whatever').click(function(){\n alert('binded');\n });\n};\n\nbindme();\n\n//function that will generate something\n\nfunction foo(){\n $('.whatever').val('oryt');\n bindme();//rebind itagain\n}\n" }, { "answer_id": 293985, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 4, "selected": true, "text": "$('.whatever').click(function() {\n alert(\"ALERT!\");\n}); \n var x = document.createElement(\"span\"); \n $(x).click(function(){ }); //etc \n $(somcontiner).append(x); \n $(x).click(foo); \n$(x).click(bar); //foo and bar should both execute. \n $(x).unbind(\"click\");\n$(x).click(foo); \n" }, { "answer_id": 1538491, "author": "Alex Angas", "author_id": 6651, "author_profile": "https://Stackoverflow.com/users/6651", "pm_score": 3, "selected": false, "text": "$('.whatever').live(\"click\", function() {\n alert(\"ALERT!\");\n});\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/440/" ]
293,959
<p>with jquery, or with simple just javascript, I want to populate a 2nd dropdown from the choice of the first dropdown. The value of the first dropdown is the condition to get rows for the second dropdown.</p> <p>How does the onChange event look like?</p>
[ { "answer_id": 2925943, "author": "Aaron", "author_id": 352461, "author_profile": "https://Stackoverflow.com/users/352461", "pm_score": 3, "selected": true, "text": "$('#s_country').change(function() {\n $('#s_state .state_CA').hide();\n $('#s_state .state_US').hide();\n $('#s_state').val('');\n var value = $.trim($(\"#s_country\").val());\n $('#s_state').show();\n $('#s_state .state_'+ value).show();\n});\n <select name=\"s_state\" id=\"s_state\">\n<option value=\"none\"></option>\n<? foreach ($states_us as $v):\n $selected = ($v->state_code == $current_state)?'selected=\"selected\"':''; ?>\n <option class=\"state_US\" value=\"<?=$v->state_code?>\" <?=$selected?> ><?=ucfirst($v->state)?></option>\n<? endforeach;?>\n<? foreach ($states_ca as $v):\n $selected = ($v->state_code == set_value('s_state'))?'selected=\"selected\"':''; ?>\n <option class=\"state_CA\" value=\"<?=$v->state_code?>\" <?=$selected;?>><?=ucfirst($v->state)?></option>\n<? endforeach; ?> \n</select>\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30759/" ]
293,967
<p>Should operations that could take some time be performed in a constructor or should the object be constructed and then initialised later.</p> <p>For example when constructing an object that represents a directory structure should the population of the object and its children be done in the constructor. Clearly, a directory can contain directories and which in turn can contain directories and so on.</p> <p>What is the elegant solution to this?</p>
[ { "answer_id": 2004685, "author": "Neil T.", "author_id": 235288, "author_profile": "https://Stackoverflow.com/users/235288", "pm_score": 3, "selected": true, "text": "public class Company\n{\n public int Company_ID { get; set; }\n public string CompanyName { get; set; }\n public Address MailingAddress { get; set; }\n public Phones CompanyPhones { get; set; }\n public Contact ContactPerson { get; set; }\n}\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32153/" ]
293,972
<p>There's a HTML:</p> <pre><code>&lt;div class="test"&gt; &lt;ul&gt; &lt;li&gt;Item 1&lt;/li&gt; &lt;li&gt;Item 2&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>And a bit of JS:</p> <pre><code>$(document).ready(function() { // do stuff when DOM is ready $(".test ul").append('&lt;li&gt;Foo&lt;/li&gt;'); }); </code></pre> <p>Why does it add nothing, but if I remove html from append's argument string,</p> <pre><code>.append('Foo') </code></pre> <p>it works - but that's not the point - new text is added as anonymous block, not li item as I wanted.</p> <p>Anu suggestions?</p> <p><em>edit:</em> Argh, I've found the problem. I modified a file saved from Firefox's "Save page" option, the extension was .xhtml - and here's the problem. I renamed it and it works fine.</p> <p>Thanks :)</p>
[ { "answer_id": 293983, "author": "Frans-Willem", "author_id": 34014, "author_profile": "https://Stackoverflow.com/users/34014", "pm_score": 1, "selected": false, "text": "var li=document.createElement(\"li\");\nli.appendChild(document.createTextNode(\"Dupa\"));\n$(\".text ul\").appendChild(li);\n" }, { "answer_id": 294010, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 0, "selected": false, "text": "jQuery(function($){\n /* This is exactly the same as that document ready thing */\n var li=document.createElement(\"li\");\n $(li).text(\"Dupa\");\n $(\".text ul\").append(li);\n}); \n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16917/" ]
293,981
<p>I'd like to mark a method as deprecated, so the people using it can easily check their code and catch up. In Java you set @Deprecated and everybody knows what this means.</p> <p>So is there a preferred way (or even tools) to mark and check for deprecations in Ruby?</p>
[ { "answer_id": 293994, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 3, "selected": false, "text": "libdeprecated-ruby D require 'lib/deprecated.rb'\nrequire 'test/unit'\n\n# this class is used to test the deprecate functionality\nclass DummyClass\n def monkey\n return true\n end\n\n deprecate :monkey\nend\n\n# we want exceptions for testing here.\nDeprecate.set_action(:throw)\n\nclass DeprecateTest < Test::Unit::TestCase\n def test_set_action\n\n assert_raise(DeprecatedError) { raise StandardError.new unless DummyClass.new.monkey }\n\n Deprecate.set_action(proc { |msg| raise DeprecatedError.new(\"#{msg} is deprecated.\") })\n\n assert_raise(DeprecatedError) { raise StandardError.new unless DummyClass.new.monkey }\n\n\n # set to warn and make sure our return values are getting through.\n Deprecate.set_action(:warn)\n\n assert_nothing_raised(DeprecatedError) { raise StandardError.new unless DummyClass.new.monkey } \n end\nend\n" }, { "answer_id": 294114, "author": "Ryan McGeary", "author_id": 8985, "author_profile": "https://Stackoverflow.com/users/8985", "pm_score": 8, "selected": true, "text": "Kernel#warn class Foo\n # <b>DEPRECATED:</b> Please use <tt>useful</tt> instead.\n def useless\n warn \"[DEPRECATION] `useless` is deprecated. Please use `useful` instead.\"\n useful\n end\n\n def useful\n # ...\n end\nend\n # @deprecated Please use {#useful} instead\n # Deprecated: Please use `useful` instead\n" }, { "answer_id": 2908993, "author": "Adam French", "author_id": 350393, "author_profile": "https://Stackoverflow.com/users/350393", "pm_score": 4, "selected": false, "text": "warn Kernel.caller.first + \" whatever deprecation message here\"\n" }, { "answer_id": 9172078, "author": "Alex Djioev", "author_id": 244569, "author_profile": "https://Stackoverflow.com/users/244569", "pm_score": 2, "selected": false, "text": "class Module \n def deprecate(old_method, new_method)\n define_method(old_method) do |*args, &block|\n warn \"Method #{old_method}() depricated. Use #{new_method}() instead\"\n send(new_method, *args, &block)\n end\n end\nend\n\n\nclass Test\n def my_new_method\n p \"My method\"\n end\n\n deprecate :my_old_method, :my_method\nend\n" }, { "answer_id": 17339794, "author": "Kris", "author_id": 22237, "author_profile": "https://Stackoverflow.com/users/22237", "pm_score": 4, "selected": false, "text": "ActiveSupport::Deprecation require 'active_support/deprecation'\nrequire 'active_support/core_ext/module/deprecation'\n\nclass MyGem\n def self.deprecator\n ActiveSupport::Deprecation.new('2.0', 'MyGem')\n end\n\n def old_method\n end\n\n def new_method\n end\n\n deprecate old_method: :new_method, deprecator: deprecator\nend\n\nMyGem.new.old_method\n# => DEPRECATION WARNING: old_method is deprecated and will be removed from MyGem 2.0 (use new_method instead). (called from <main> at file.rb:18)\n" }, { "answer_id": 23554720, "author": "Ricardo Valeriano", "author_id": 332429, "author_profile": "https://Stackoverflow.com/users/332429", "pm_score": 6, "selected": false, "text": "# my_file.rb\n\nclass MyFile\n extend Gem::Deprecate\n\n def no_more\n close\n end\n deprecate :no_more, :close, 2015, 5\n\n def close\n # new logic here\n end\nend\n\nMyFile.new.no_more\n# => NOTE: MyFile#no_more is deprecated; use close instead. It will be removed on or after 2015-05-01.\n# => MyFile#no_more called from my_file.rb:16.\n" }, { "answer_id": 37824395, "author": "Matt Whipple", "author_id": 1655332, "author_profile": "https://Stackoverflow.com/users/1655332", "pm_score": 1, "selected": false, "text": "def deprecate(msg)\n method = caller_locations(1, 1).first.label\n source = caller(2, 1).first\n warn \"#{method} is deprecated: #{msg}\\ncalled at #{source}\"\nend\n def foo\n deprecate 'prefer bar, will be removed in version 3'\n ...\nend\n" }, { "answer_id": 38739746, "author": "Artur INTECH", "author_id": 2987689, "author_profile": "https://Stackoverflow.com/users/2987689", "pm_score": 4, "selected": false, "text": "class Player < ActiveRecord::Base\n def to_s\n ActiveSupport::Deprecation.warn('Use presenter instead')\n partner_uid\n end\nend\n" }, { "answer_id": 57789434, "author": "E V N Raja", "author_id": 4314483, "author_profile": "https://Stackoverflow.com/users/4314483", "pm_score": 0, "selected": false, "text": "class Foo\n def get_a; puts \"I'm an A\" end\n def get_b; puts \"I'm an B\" end\n def get_c; puts \"I'm an C\" end def self.deprecate(old_method, new_method)\n define_method(old_method) do |*args, &block|\n puts \"Warning: #{old_method} is deprecated! Use #{new_method} instead\"\n send(new_method, *args, &block) \n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293981", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38045/" ]
293,988
<p>Is there a good way in C++ to implement (or fake) a type for a generic vector of vectors?</p> <p>Ignore the issue of when a vector of vectors is a good idea (unless there's something equivalent which is always better). Assume that it does accurately model the problem, and that a matrix does not accurately model the problem. Assume also that templated functions taking these things as parameters do need to manipulate the structure (e.g. calling push_back), so they can't just take a generic type supporting <code>[][]</code>.</p> <p>What I want to do is:</p> <pre><code>template&lt;typename T&gt; typedef vector&lt; vector&lt;T&gt; &gt; vecvec; vecvec&lt;int&gt; intSequences; vecvec&lt;string&gt; stringSequences; </code></pre> <p>but of course that's not possible, since typedef can't be templated.</p> <pre><code>#define vecvec(T) vector&lt; vector&lt;T&gt; &gt; </code></pre> <p>is close, and would save duplicating the type across every templated function which operates on vecvecs, but would not be popular with most C++ programmers.</p>
[ { "answer_id": 293996, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 7, "selected": true, "text": "template<typename T>\nstruct vecvec {\n typedef std::vector< std::vector<T> > type;\n};\n\nint main() {\n vecvec<int>::type intSequences;\n vecvec<std::string>::type stringSequences;\n}\n template<typename T>\nusing vecvec = std::vector< std::vector<T> >;\n" }, { "answer_id": 297223, "author": "Rexxar", "author_id": 10016, "author_profile": "https://Stackoverflow.com/users/10016", "pm_score": 3, "selected": false, "text": "#include <string>\n#include <vector>\n\ntemplate<typename T>\nstruct vecvec : public std::vector< std::vector<T> > {};\n\nint main() \n{\n vecvec<int> intSequences;\n vecvec<std::string> stringSequences;\n}\n void test()\n{\n std::vector< std::vector<int> >* pvv = new vecvec<int>;\n delete pvv;\n}\n" }, { "answer_id": 2211411, "author": "mloskot", "author_id": 151641, "author_profile": "https://Stackoverflow.com/users/151641", "pm_score": 2, "selected": false, "text": "std::vector #include <iostream>\n#include <ostream>\n#include <vector>\nusing namespace std;\n\ntemplate <typename T>\nstruct vecvec\n{\n typedef vector<T> value_type;\n typedef vector<value_type> type;\n typedef typename type::size_type size_type;\n typedef typename type::reference reference;\n typedef typename type::const_reference const_reference;\n\n vecvec(size_type first, size_type second)\n : v_(first, value_type(second, T()))\n {}\n\n reference operator[](size_type n)\n { return v_[n]; }\n\n const_reference operator[](size_type n) const\n { return v_[n]; }\n\n size_type first_size() const\n { return v_.size(); }\n\n size_type second_size() const\n { return v_.empty() ? 0 : v_[0].size(); }\n\n // TODO: replicate std::vector interface if needed, like\n //iterator begin();\n //iterator end();\n\nprivate:\n type v_;\n\n};\n\n// for convenient printing only\ntemplate <typename T> \nostream& operator<<(ostream& os, vecvec<T> const& v)\n{\n typedef vecvec<T> v_t;\n typedef typename v_t::value_type vv_t;\n for (typename v_t::size_type i = 0; i < v.first_size(); ++i)\n {\n for (typename vv_t::size_type j = 0; j < v.second_size(); ++j)\n {\n os << v[i][j] << '\\t';\n }\n os << endl;\n }\n return os;\n}\n\nint main()\n{\n vecvec<int> v(2, 3);\n cout << v.first_size() << \" x \" << v.second_size() << endl;\n cout << v << endl;\n\n v[0][0] = 1; v[0][1] = 3; v[0][2] = 5;\n v[1][0] = 2; v[1][1] = 4; v[1][2] = 6;\n cout << v << endl;\n}\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13005/" ]
293,997
<p>I know postgres has a datatype for storing geographical coordinates. But I'm looking for a RDBMS agnostic solution. Currently I'm using Decimal(25,20) in MySQL. I may be using this data to lookup these locations based on a given distance from a given location later. Which would be the best approach to store this kind of data?</p>
[ { "answer_id": 294014, "author": "vfilby", "author_id": 24279, "author_profile": "https://Stackoverflow.com/users/24279", "pm_score": 3, "selected": false, "text": "# decmal places, example, precision\n5 51.22135 ± 0.8 m\n6 50.895132 ± 0.08 m\n" }, { "answer_id": 294096, "author": "geocar", "author_id": 37507, "author_profile": "https://Stackoverflow.com/users/37507", "pm_score": 1, "selected": false, "text": "_" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293997", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7883/" ]
294,009
<p>When comparing two objects (of the same type), it makes sense to have a compare function which takes another instance of the same class. If I implement this as a virtual function in the base class, then the signature of the function has to reference the base class in derived classes also. What is the elegant way to tackle this? Should the Compare not be virtual?</p> <pre><code>class A { A(); ~A(); virtual int Compare(A Other); } class B: A { B(); ~B(); int Compare(A Other); } class C: A { C(); ~C(); int Compare(A Other); } </code></pre>
[ { "answer_id": 294026, "author": "Federico A. Ramponi", "author_id": 18770, "author_profile": "https://Stackoverflow.com/users/18770", "pm_score": 0, "selected": false, "text": "int B::Compare(A *ptr)\n{\n other = dynamic_cast <B*> (ptr);\n if(other)\n ... // Ok, it was a pointer to B\n}\n" }, { "answer_id": 294037, "author": "Hugo", "author_id": 972, "author_profile": "https://Stackoverflow.com/users/972", "pm_score": 0, "selected": false, "text": "let a = new A\nlet b = new B (inherits from A)\n\nif (a.equals(b))\n then b.equals(a) must be true!\n a.equals(b) b.equals(a)" }, { "answer_id": 294039, "author": "David Norman", "author_id": 34502, "author_profile": "https://Stackoverflow.com/users/34502", "pm_score": 0, "selected": false, "text": "class B: public A\n{\n B();\n virtual ~B();\n virtual int Compare(const A &Other) const;\n};\n\n\nint B::Compare(const A &Other) const\n{\n const B *other = dynamic_cast <const B*> (&Other);\n if(other) {\n // compare\n }\n else {\n return 0;\n }\n}\n" }, { "answer_id": 294146, "author": "P Daddy", "author_id": 36388, "author_profile": "https://Stackoverflow.com/users/36388", "pm_score": 1, "selected": false, "text": "class A{\n int a;\n\npublic:\n virtual int Compare(A *other);\n};\n\n\nclass B : A{\n int b;\n\npublic:\n /*override*/ int Compare(A *other);\n};\n\nint A::Compare(A *other){\n if(!other)\n return 1; /* let's just say that non-null > null */\n\n if(a > other->a)\n return 1;\n\n if(a < other->a)\n return -1;\n\n return 0;\n}\n\nint B::Compare(A *other){\n int cmp = A::Compare(other);\n if(cmp)\n return cmp;\n\n B *b_other = dynamic_cast<B*>(other);\n if(!b_other)\n throw \"Must be a B object\";\n\n if(b > b_other->b)\n return 1;\n\n if(b < b_other->b)\n return -1;\n\n return 0;\n}\n IComparable a.Compare(b) a b b.Compare(a) Compare type_info Compare int A::Compare(A *other){\n if(!other)\n return 1; /* let's just say that non-null > null */\n\n if(typeid(this) != typeid(other))\n throw \"Must be the same type\";\n\n if(a > other->a)\n return 1;\n\n if(a < other->a)\n return -1;\n\n return 0;\n}\n Compare Compare type_info dynamic_cast Compare static_cast" }, { "answer_id": 294181, "author": "coppro", "author_id": 16855, "author_profile": "https://Stackoverflow.com/users/16855", "pm_score": 1, "selected": false, "text": "class A\n{\n public:\n virtual int Compare (const A& rhs) const\n {\n // do some comparisons\n }\n};\n\nclass B\n{\n public:\n virtual int Compare (const A& rhs) const\n {\n try\n {\n B& b = dynamic_cast<A&>(rhs)\n if (A::Compare(b) == /* equal */)\n {\n // do some comparisons\n }\n else\n return /* not equal */;\n }\n catch (std::bad_cast&)\n {\n return /* non-equal */\n }\n }\n};\n" }, { "answer_id": 294254, "author": "wimh", "author_id": 33499, "author_profile": "https://Stackoverflow.com/users/33499", "pm_score": 0, "selected": false, "text": "class A\n{\n public:\n A(){};\n int Compare(A const & Other) {cout << \"A::Compare()\" << endl; return 0;};\n};\n\nclass B: public A\n{\n public:\n B(){};\n int Compare(B const & Other) {cout << \"B::Compare()\" << endl; return 0;};\n};\n\nclass C: public A\n{\n public:\n C(){};\n int Compare(C const & Other) {cout << \"C::Compare()\" << endl; return 0;};\n};\n\nint main(int argc, char* argv[])\n{\n A a1;\n B b1, b2;\n C c1;\n\n a1.Compare(b1); // A::Compare()\n b1.A::Compare(a1); // A::Compare()\n b1.Compare(b2); // B::Compare()\n c1.A::Compare(b1); // A::Compare()\n\n return 0;\n}\n" }, { "answer_id": 840996, "author": "Kyle Simek", "author_id": 91447, "author_profile": "https://Stackoverflow.com/users/91447", "pm_score": 2, "selected": true, "text": "class Object \n{\n virtual int compare(const Object& ) = 0;\n float volume;\n};\n\nclass Animal : Object \n{\n virtual int compare(const Object& );\n float age;\n};\n\nclass Zebra : Animal \n{\n int compare(const Object& );\n};\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/294009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32153/" ]
294,018
<p>What are some C++ related idioms, misconceptions, and gotchas that you've learnt from experience?</p> <p>An example:</p> <pre><code>class A { public: char s[1024]; char *p; A::A() { p = s; } void changeS() const { p[0] = 'a'; } }; </code></pre> <p>Even know changeS is a const member function, it is changing the value of the object. So a const member function only means that it will treat all variables as const, and it does not mean that it will actually keep all members const. (why? the const keyword on the member function treats char *p; as char * const p; And not as const char *p;</p> <p>Which therefore means that p can't point to something else. And not that you can't change p's data. </p>
[ { "answer_id": 294023, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 5, "selected": true, "text": "assert(condition || !\"Something has gone wrong!\");\n assert(!\"Something has gone wrong!\");\n assert((\"Something has gone wrong!\", condition)); \n" }, { "answer_id": 294041, "author": "jalf", "author_id": 33213, "author_profile": "https://Stackoverflow.com/users/33213", "pm_score": 3, "selected": false, "text": "std::cout << a << a++ << --a;\ni = ++i;\n void foo(bar* b1, bar* b2);\n\nint main() {\n foo(shared_ptr<bar>(new bar()), shared_ptr<bar>(new bar()));\n}\n int* arr = new int[10];\narr + 11;\n" }, { "answer_id": 294054, "author": "Assaf Lavie", "author_id": 11208, "author_profile": "https://Stackoverflow.com/users/11208", "pm_score": 6, "selected": false, "text": "typedef C &(__cdecl C::* const CB )(const C &) const;\n struct C {\n const C& Callback(const C&) const { }\n};\n char c = &C::Callback;\n “… cannot convert from 'const C &(__cdecl C::* )(const C &) const' to 'char'”\n" }, { "answer_id": 294130, "author": "Procedural Throwback", "author_id": 24404, "author_profile": "https://Stackoverflow.com/users/24404", "pm_score": 3, "selected": false, "text": "class Sample\n{ \n const char * ptr;\n const bool freeable;\n\n Sample(const char * optional):\n ptr( optional ? optional : new char [32]),\n freeable( optional ? false : true ) {}\n ~Sample( ) { if (freeable) delete[] ptr; }\n} \n" }, { "answer_id": 294223, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 4, "selected": false, "text": "char int2hex(int x) {\n return \"-0123456789abcdef\"[(x >= 0 && x < 16) ? (x + 1) : 0];\n}\n" }, { "answer_id": 294389, "author": "fizzer", "author_id": 18167, "author_profile": "https://Stackoverflow.com/users/18167", "pm_score": 3, "selected": false, "text": "#include <cassert>\n#include <functional>\n#include <stdexcept>\n#include <boost/shared_ptr.hpp>\nusing namespace std;\nusing namespace boost;\n\nclass Foo\n{\npublic:\n Foo() : even(0)\n {\n // Check on start up...\n Invariant();\n }\n\n void BrokenFunc()\n {\n // ...and on exit from public non-const member functions.\n // Any more is wasteful.\n shared_ptr<Foo> checker(this, mem_fun(&Foo::Invariant));\n\n even += 1;\n throw runtime_error(\"didn't expect this!\");\n even += 1;\n }\n\nprivate:\n void Invariant() { assert(even % 2 == 0); }\n int even;\n};\n" }, { "answer_id": 294406, "author": "AntonioCS", "author_id": 8715, "author_profile": "https://Stackoverflow.com/users/8715", "pm_score": 0, "selected": false, "text": "m[i*dim2+j]\n" }, { "answer_id": 629705, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 4, "selected": false, "text": "#define max(a, b) (a > b ? a : b)\n windows.h void myfunction() {\n ....\n (max)(c, d);\n}\n" }, { "answer_id": 629760, "author": "Lucas", "author_id": 74660, "author_profile": "https://Stackoverflow.com/users/74660", "pm_score": 0, "selected": false, "text": "#include <iostream>\nusing namespace std;\n\nint& strangeFunction(int& x){return x;}\n\n\nint main(){\n int a=0;\n strangeFunction(a) = 5; //<------- I found this very confusing\n cout << a <<endl;\n return 0;\n}\n" }, { "answer_id": 14357773, "author": "amit kumar", "author_id": 19501, "author_profile": "https://Stackoverflow.com/users/19501", "pm_score": 0, "selected": false, "text": "shared_ptr unique_ptr shared_ptr shared_ptr" }, { "answer_id": 14357942, "author": "amit kumar", "author_id": 19501, "author_profile": "https://Stackoverflow.com/users/19501", "pm_score": 0, "selected": false, "text": "std::noncopyable clone() explicit clone()" }, { "answer_id": 14358095, "author": "amit kumar", "author_id": 19501, "author_profile": "https://Stackoverflow.com/users/19501", "pm_score": 0, "selected": false, "text": "boost::spirit::hold_any boost::any" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/294018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ]
294,040
<p>Maybe this is an easy question, maybe not. I have a select box where I hardcode with width. Say 120px.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;select style="width: 120px"&gt; &lt;option&gt;REALLY LONG TEXT, REALLY LONG TEXT, REALLY LONG TEXT&lt;/option&gt; &lt;option&gt;ABC&lt;/option&gt; &lt;/select&gt;</code></pre> </div> </div> </p> <p>I want to be able to show the second option so that the user can see the full length of the text.</p> <p>Like everything else. This works fine in Firefox, but doesn't work with Internet Explorer6.</p>
[ { "answer_id": 294051, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 5, "selected": true, "text": "<select> title" }, { "answer_id": 294058, "author": "Pim Jager", "author_id": 35197, "author_profile": "https://Stackoverflow.com/users/35197", "pm_score": 1, "selected": false, "text": "$(document).ready( function() {\n$('#select').change( function() {\n $('#hiddenDiv').html( $('#select').val() );\n $('#select').width( $('#hiddenDiv').width() );\n }\n }\n <div id=\"hiddenDiv\" style=\"visibility:hidden\"></div>\n" }, { "answer_id": 564605, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<div style=\"width: 180px; overflow: hidden;\">\n <select style=\"width: auto;\" name=\"abc\" id=\"10\">\n <option value=\"-1\">AAAAAAAAAAA</option>\n <option value=\"123\">123</option>\n </select>\n</div>" }, { "answer_id": 1077314, "author": "Saeed", "author_id": 97095, "author_profile": "https://Stackoverflow.com/users/97095", "pm_score": 0, "selected": false, "text": "<html>\n<head>\n\n<style>\n .wrapper{\n display: inline;\n float: left; \n width: 180px; \n overflow: hidden; \n }\n .selectArrow{\n display: inline;\n float: left;\n width: 17px;\n height: 20px;\n border:1px solid #7f9db9;\n border-left: none;\n background: url('selectArrow.png') no-repeat 1px 1px;\n }\n .selectArrow-mousedown{background: url('selectArrow-mousedown.png') no-repeat 1px 1px;}\n .selectArrow-mouseover{background: url('selectArrow-mouseover.png') no-repeat 1px 1px;}\n</style>\n<script language=\"javascript\" src=\"jquery-1.3.2.min.js\"></script>\n\n<script language=\"javascript\">\n $(document).ready(function(){\n $('#w1').wrap(\"<div class='wrapper'></div>\");\n $('.wrapper').after(\"<div class='selectArrow'/>\");\n $('.wrapper').find('select').mousedown(function(){\n $(this).parent().next().addClass('selectArrow-mousedown').removeClass('selectArrow-mouseover');\n }).\n mouseup(function(){\n $(this).parent().next().removeClass('selectArrow-mousedown').addClass('selectArrow-mouseover');\n }).\n hover(function(){\n $(this).parent().next().addClass('selectArrow-mouseover');\n }, function(){\n $(this).parent().next().removeClass('selectArrow-mouseover');\n });\n\n $('.selectArrow').click(function(){\n $(this).prev().find('select').focus();\n });\n\n $('.selectArrow').mousedown(function(){\n $(this).addClass('selectArrow-mousedown').removeClass('selectArrow-mouseover');\n }).\n mouseup(function(){\n $(this).removeClass('selectArrow-mousedown').addClass('selectArrow-mouseover');\n }).\n hover(function(){\n $(this).addClass('selectArrow-mouseover');\n }, function(){\n $(this).removeClass('selectArrow-mouseover');\n });\n });\n\n</script>\n</head>\n<body>\n <select id=\"w1\">\n <option value=\"0\">AnyAnyAnyAnyAnyAnyAny</option>\n <option value=\"1\">AnyAnyAnyAnyAnyAnyAnyAnyAnyAnyAnyAnyAnyAny</option>\n </select>\n\n</body>\n</html>\n" }, { "answer_id": 3868168, "author": "Eric", "author_id": 194290, "author_profile": "https://Stackoverflow.com/users/194290", "pm_score": 1, "selected": false, "text": "eventListener if (jQuery.browser.msie) {\n jQuery('#mySelect').focus(function() {\n jQuery(this).width('auto');\n }).bind('blur change', function() {\n jQuery(this).width('100%');\n });\n};\n var cWidth = jQuery('#mySelect').width();" }, { "answer_id": 5034269, "author": "Doug Peil", "author_id": 622075, "author_profile": "https://Stackoverflow.com/users/622075", "pm_score": 2, "selected": false, "text": " <!--\n\n I found this works fairly well.\n\n -->\n\n <!-- On page load, be sure that something else has focus. -->\n <body onload=\"document.getElementById('name').focus();\">\n <input id=name type=text>\n\n <!-- This div is for demonstration only. The parent container may be anything -->\n <div style=\"height:50; width:100px; border:1px solid red;\">\n\n <!-- Note: static width, absolute position but no top or left specified, Z-Index +1 -->\n <select\n style=\"width:96px; position:absolute; z-index:+1;\"\n onactivate=\"this.style.width='auto';\"\n onchange=\"this.blur();\"\n onblur=\"this.style.width='96px';\">\n <!-- \"activate\" happens before all else and \"width='auto'\" expands per content -->\n <!-- Both making a selection and moving to another control should return static width -->\n\n <option>abc</option>\n <option>abcdefghij</option>\n <option>abcdefghijklmnop</option>\n <option>abcdefghijklmnopqrstuvwxyz</option>\n\n </select>\n\n </div>\n\n </body>\n\n </html>\n" }, { "answer_id": 7285239, "author": "tpham211", "author_id": 925497, "author_profile": "https://Stackoverflow.com/users/925497", "pm_score": 2, "selected": false, "text": "<div id=myForm>\n #myForm select { \nwidth:200px; }\n\n#myForm select:focus {\nwidth:auto; }\n" }, { "answer_id": 10819258, "author": "Doni", "author_id": 1215625, "author_profile": "https://Stackoverflow.com/users/1215625", "pm_score": 1, "selected": false, "text": "function PopulateDropdown() {\n $.ajax({\n type: \"POST\",\n url: \"../CommonWebService.asmx/GetData\",\n data: \"{}\",\n contentType: \"application/json; charset=utf-8\",\n dataType: \"json\",\n success: function (msg) {\n $(\"select[id^='MyDropDown']\").empty();\n $.each(msg.d, function () {\n $(\"select[id^='MyDropDownSelect']\").append($(\"<option></option>\").val(this['IdIndexDataType']).html(this['DataTypeName']));\n }); \n $(\"select[id^='MyDropDown']\").css(\"width\", \"auto\"); \n },\n error: function (e1) {\n alert(\"Error - \" + e1.toString());\n }\n });\n}\n $(\"select[id^='MyDropDown']\").css(\"width\", \"auto\");\n" }, { "answer_id": 12615538, "author": "Web Designer cum Promoter", "author_id": 1012591, "author_profile": "https://Stackoverflow.com/users/1012591", "pm_score": 0, "selected": false, "text": "select{ width:80px;text-overflow:'...';-ms-text-overflow:ellipsis;position:absolute; z-index:+1;}\nselect:focus{ width:100%;}\n" }, { "answer_id": 30605916, "author": "iansoccer9", "author_id": 4966973, "author_profile": "https://Stackoverflow.com/users/4966973", "pm_score": 2, "selected": false, "text": "select {\n min-width: 120px;\n max-width: 120px;\n}\nselect:focus {\n width: auto;\n} <select style=\"width: 120px\">\n <option>REALLY LONG TEXT, REALLY LONG TEXT, REALLY LONG TEXT</option>\n <option>ABC</option>\n</select>" }, { "answer_id": 55343177, "author": "João Pimentel Ferreira", "author_id": 1243247, "author_profile": "https://Stackoverflow.com/users/1243247", "pm_score": 3, "selected": false, "text": "jquery select select $('select').change(function(){\n var text = $(this).find('option:selected').text()\n var $aux = $('<select/>').append($('<option/>').text(text))\n $(this).after($aux)\n $(this).width($aux.width())\n $aux.remove()\n}).change() <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n<select>\n <option>ABC</option>\n <option>REALLY LONG TEXT, REALLY LONG TEXT, REALLY LONG TEXT</option>\n</select>" }, { "answer_id": 67240166, "author": "kilian", "author_id": 4168960, "author_profile": "https://Stackoverflow.com/users/4168960", "pm_score": 2, "selected": false, "text": "selectedIndex position: fixed visibility: hidden getBoundingClientRect().width const select = document.querySelector('select')\n\nselect.addEventListener('change', (event) => {\n let tempSelect = document.createElement('select'),\n tempOption = document.createElement('option');\n\n tempOption.textContent = event.target.options[event.target.selectedIndex].text;\n tempSelect.style.cssText += `\n visibility: hidden;\n position: fixed;\n `;\n tempSelect.appendChild(tempOption);\n event.target.after(tempSelect);\n \n const tempSelectWidth = tempSelect.getBoundingClientRect().width;\n event.target.style.width = `${tempSelectWidth}px`;\n tempSelect.remove();\n});\n\nselect.dispatchEvent(new Event('change')); <select>\n <option>Short option</option>\n <option>Some longer option</option>\n <option>An very long option with a lot of text</option>\n</select>" }, { "answer_id": 71225835, "author": "Bartek", "author_id": 5339410, "author_profile": "https://Stackoverflow.com/users/5339410", "pm_score": 1, "selected": false, "text": "Array.from(document.querySelectorAll('.js-select-auto-expand'), (input) => {\n let parent = input.parentNode;\n \n function updateSize() {\n parent.dataset.selectAutoExpand = input.value\n }\n \n input.addEventListener('input', updateSize);\n \n updateSize();\n}); *,\n*::before,\n*::after {\n box-sizing: border-box;\n}\n\nbody {\n padding: 2rem 4rem;\n line-height: 1.5;\n color: gray;\n}\n\n.article-test {\n line-height: 2.5;\n}\n\n.select-auto-expand {\n position: relative;\n display: inline-block;\n min-width: 2rem;\n width: auto;\n height: 30px;\n line-height: 28px;\n padding: 0 10px;\n vertical-align: baseline;\n border: 1px solid black;\n background-color: transparent;\n color: #fafafa;\n font-size: 1rem;\n}\n.select-auto-expand .select-auto-expand__select {\n position: absolute;\n top: 0px;\n bottom: 0;\n left: 0;\n right: 0;\n width: 100%;\n min-width: 1em;\n height: 100%;\n margin: 0 2px;\n padding: 0 8px;\n -webkit-appearance: none;\n -moz-appearance: none;\n appearance: none;\n border-radius: 0;\n border: 0;\n background: transparent;\n font: inherit;\n}\n.select-auto-expand::after {\n content: attr(data-select-auto-expand);\n display: inline-block;\n width: 100%;\n min-width: 1em;\n white-space: pre-wrap;\n font: inherit;\n line-height: inherit;\n color: inherit;\n background: transparent;\n visibility: hidden;\n opacity: 0;\n}\n.select-auto-expand:focus-within {\n outline: 3px solid rgba(0, 0, 255, 0.3);\n}\n.select-auto-expand:focus-within input:focus {\n outline: none;\n} <form action=\"#\" class=\"article-test\">\n\n <p>\n Adipisci ipsum debitis quaerat commodi tenetur? Amet consectetur adipisicing elit. Lorem ipsum dolor sit, \n <label class=\"select-auto-expand\" for=\"pet-select\">\n <select name=\"pets\" id=\"pet-select\" class=\"select-auto-expand__select js-select-auto-expand\">\n <option value=\"select ...\">select ...</option>\n <option value=\"sed qui\">sed qui</option>\n <option value=\"veniam iste quis\">veniam iste quis</option>\n <option value=\"ipsum debitis\">ipsum debitis</option>\n <option value=\"officia excepturi repellendus aperiam\">officia excepturi repellendus aperiam</option>\n </select>\n </label>\n veniam iste quis, sed qui non dolores. Porro, soluta. Officia excepturi repellendus aperiam cumque consectetur distinctio, veniam iste quis, sed qui non dolores. Adipisci ipsum debitis quaerat commodi tenetur?\n </p>\n\n</form>" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/294040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10522/" ]
294,077
<p>I have a large amount of rows in the database from which I need to create an XML document. I am using hibernate 3. The basic list() method in Criteria and Query interfaces looks dangerous: I quess it pretty much has to read all the records into memory even if I only iterate over them. Or is there some lazy loading magic? If not, I seem to have two options left: using scroll() or iterate() from Query (scroll is also present in Criteria). iterate doesn't look all that great either if I want to have minimal SQL roundtrips: "The first SQL query returns identifiers only". So am I right, do I have to use scroll() for this?</p>
[ { "answer_id": 294124, "author": "Paul Croarkin", "author_id": 18995, "author_profile": "https://Stackoverflow.com/users/18995", "pm_score": 1, "selected": false, "text": "Criteria crit = sess.createCriteria(Cat.class);\ncrit.setMaxResults(maxResults);\ncrit.setFirstResult(firstResultIndex);\nList cats = crit.list();\n" }, { "answer_id": 1269112, "author": "Justin", "author_id": 148607, "author_profile": "https://Stackoverflow.com/users/148607", "pm_score": 0, "selected": false, "text": "Insert into BatchTable (ID, Seq) Select (O.ID, Sequence.Next) \nFrom MyObject O Where ...\n Select Min(B.Seq), Max(B.Seq) From BatchTable;\n\nfor (batch = minBatch; batch <= maxBatch; batch += size) {\n beginTransaction();\n results = query(\"Select O From MyObject O, BatchTable B \n Where O.ID = B.ID and (? <= B.Seq AND B.Seq < ?)\");\n\n exportXML(results);\n for (MyObject O : results) {\n O.setProcessed(True);\n O.update();\n }\n commit();\n}\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/294077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4110/" ]
294,080
<p>I use [Dllimport("DllName.dll")] where I'm sure a path to my dll exists in the process PATH environment variable, and still I get "DllName.dll could not be found"</p>
[ { "answer_id": 42168466, "author": "Roger Breton", "author_id": 3847487, "author_profile": "https://Stackoverflow.com/users/3847487", "pm_score": 1, "selected": false, "text": "const string lcms2Path = \"C:\\\\lcms2.dll\"; [DllImport(\"lcms2.dll\")]" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/294080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30324/" ]
294,092
<p>I've just written a small XBox 360 Wireless Controller managed interface that basically wraps around the low-lever <a href="http://slimdx.mdxinfo.com/wiki/index.php?title=Main_Page" rel="nofollow noreferrer">SlimDX</a> wrapper library and provides a easy, managed API for the XBOX 360 controller.</p> <p>Internally, the class polls the gamepad every N ms, and shoots events as it detects changes in the underlying state of the controller.</p> <p>I'm experiencing some what dead end with timers that is basiclly forcing to choose between the lesser of two evils:</p> <ul> <li><p>Either make my XBox360GamePad class UI framework specific (i.e. support WPF/WinForms will be hard-coded in the class, and the class has to reference these frameworks...)</p></li> <li><p>Make the class completely framework agnostic, but force the users to sprinkle their code with Dispatcher.Invoke / Invoke() calls to be able to update UI according to the events generated.</p></li> </ul> <p>If I choose the latter option (of making the code UI agnostic), then I basically use the "generic" System.Timers.Timer or any timer that has no UI dependency. In that case I end up having events generated/called from a thread that is incapable of directly updating the UI, i.e. in WPF, I would have to issue every update originated form the 360 controller class through the (ugly) use of Dispatcher.Invoke.</p> <p>On the other hand, If I use DispatcherTimer inside the XBox 360 Controller class I have a working component that can update the UI directly with no fuss, but now my whole controller class is coupled to WPF, and it can't be used without being dependent on WPF (i.e. in a pure console app)</p> <p>What I'm kind of looking is a some sort solution that would allow me to be both framework agnostic and also update UI without having to resort to all kinds of Dispatcher.Invoke() techniques... If for example there was a shared base class for all timers, I could somehow inject the timer as a dependency according to the relevant scenario.. Has anyone ever dealt successfully with this sort of problem?</p>
[ { "answer_id": 294233, "author": "damageboy", "author_id": 9172, "author_profile": "https://Stackoverflow.com/users/9172", "pm_score": 1, "selected": true, "text": "protected virtual void OnLeftThumbStickMove(ThumbStickEventArgs e)\n{\n if (LeftThumbStickMove == null) return;\n \n if (_syncObj == null || !_syncObj.InvokeRequired)\n LeftThumbStickMove(this, e);\n else\n _syncObj.BeginInvoke(LeftThumbStickMove, new object[] { this, e });\n}\n public XBox360GamePad(UserIndex controllerIndex, Func<int, Action, object> timerSetupAction)\n{\n CurrentController = new Controller(controllerIndex);\n _timerState = timerSetupAction(10, UpdateState);\n}\n public XBox360GamePad(UserIndex controllerIndex) : \n this(controllerIndex, (i,f) => new Timer(delegate { f(); }, null, i, i)) {}\n _gamePad = new XBox360GamePad(UserIndex.One, (i, f) => {\n var t = new DispatcherTimer(DispatcherPriority.Render) {Interval = new TimeSpan(0, 0, 0, 0, i) };\n t.Tick += delegate { f(); };\n t.Start();\n return t;\n });\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/294092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9172/" ]
294,113
<p>Is it possible to catch an recycle event in the global.asax?</p> <p>I know Application_End will be triggered but is there a way to know that it was triggered by a recycle of the application pool?</p> <p>thx, Lieven Cardoen aka Johlero</p>
[ { "answer_id": 294126, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 1, "selected": false, "text": "...\nAppDomain.CurrentDomain.ProcessExit += new EventHandler(OnExit);\n...\n\nvoid OnExit(object sender, EventArgs e) {\n // do something\n}\n" }, { "answer_id": 294160, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 3, "selected": true, "text": "app_domain_end_ok.tmp" }, { "answer_id": 302604, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 3, "selected": false, "text": "public void Application_End() {\n\n HttpRuntime runtime = \n (HttpRuntime) typeof(System.Web.HttpRuntime).InvokeMember(\"_theRuntime\",\n BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.GetField, \n null, null, null);\n\n if (runtime == null)\n return;\n\n string shutDownMessage = \n (string) runtime.GetType().InvokeMember(\"_shutDownMessage\",\n BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField,\n null, runtime, null);\n\n string shutDownStack = \n (string) runtime.GetType().InvokeMember(\"_shutDownStack\",\n BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField,\n null, runtime, null);\n\n if (!EventLog.SourceExists(\".NET Runtime\")) {\n EventLog.CreateEventSource(\".NET Runtime\", \"Application\");\n }\n\n EventLog log = new EventLog();\n log.Source = \".NET Runtime\";\n\n log.WriteEntry(String.Format(\n \"\\r\\n\\r\\n_shutDownMessage={0}\\r\\n\\r\\n_shutDownStack={1}\", \n shutDownMessage, shutDownStack),\n EventLogEntryType.Error);\n}\n" }, { "answer_id": 40526900, "author": "Maksymilian Mulawa", "author_id": 215401, "author_profile": "https://Stackoverflow.com/users/215401", "pm_score": 0, "selected": false, "text": "AppDomain.CurrentDomain.DomainUnload += this.CurrentDomainOnProcessExit;" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/294113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26521/" ]
294,136
<p>Is there any way to import a database backup from 2005 into 2008 express edition. What I've had to resort to is doing a script the database, then import all the data through DTS. Whenever I tried to import straight from a backup file it says something about not being to import into a new version of sql server or I'll get the below error.</p> <p>title: Microsoft SQL Server Management Studio</p> <p>Specified cast is not valid. (SqlManagerUI)</p>
[ { "answer_id": 2653369, "author": "ScaryDBA", "author_id": 196739, "author_profile": "https://Stackoverflow.com/users/196739", "pm_score": 0, "selected": false, "text": "RESTORE VERIFYONLY\nFROM yourbackupfile.bak\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/294136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37400/" ]
294,138
<p>What's the best way to merge 2 or more dictionaries (<code>Dictionary&lt;T1,T2&gt;</code>) in C#? (3.0 features like LINQ are fine).</p> <p>I'm thinking of a method signature along the lines of:</p> <pre><code>public static Dictionary&lt;TKey,TValue&gt; Merge&lt;TKey,TValue&gt;(Dictionary&lt;TKey,TValue&gt;[] dictionaries); </code></pre> <p>or</p> <pre><code>public static Dictionary&lt;TKey,TValue&gt; Merge&lt;TKey,TValue&gt;(IEnumerable&lt;Dictionary&lt;TKey,TValue&gt;&gt; dictionaries); </code></pre> <p><strong>EDIT:</strong> Got a cool solution from JaredPar and Jon Skeet, but I was thinking of something that handles duplicate keys. In case of collision, it doesn't matter which value is saved to the dict as long as it's consistent.</p>
[ { "answer_id": 294139, "author": "orip", "author_id": 37020, "author_profile": "https://Stackoverflow.com/users/37020", "pm_score": 6, "selected": false, "text": "using System.Collections.Generic;\n...\npublic static Dictionary<TKey, TValue>\n Merge<TKey,TValue>(IEnumerable<Dictionary<TKey, TValue>> dictionaries)\n{\n var result = new Dictionary<TKey, TValue>();\n foreach (var dict in dictionaries)\n foreach (var x in dict)\n result[x.Key] = x.Value;\n return result;\n}\n" }, { "answer_id": 294142, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 5, "selected": false, "text": "static Dictionary<TKey, TValue>\n Merge<TKey, TValue>(this IEnumerable<Dictionary<TKey, TValue>> enumerable)\n{\n return enumerable.SelectMany(x => x).ToDictionary(x => x.Key, y => y.Value);\n}\n" }, { "answer_id": 294145, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 10, "selected": true, "text": "var result = dictionaries.SelectMany(dict => dict)\n .ToDictionary(pair => pair.Key, pair => pair.Value);\n var result = dictionaries.SelectMany(dict => dict)\n .ToLookup(pair => pair.Key, pair => pair.Value)\n .ToDictionary(group => group.Key, group => group.First());\n SelectMany" }, { "answer_id": 294159, "author": "Bryan Watts", "author_id": 37815, "author_profile": "https://Stackoverflow.com/users/37815", "pm_score": 3, "selected": false, "text": "params IDictionary public static IDictionary<TKey, TValue> Merge<TKey, TValue>(IEnumerable<IDictionary<TKey, TValue>> dictionaries)\n{\n // ...\n}\n\npublic static IDictionary<TKey, TValue> Merge<TKey, TValue>(params IDictionary<TKey, TValue>[] dictionaries)\n{\n return Merge((IEnumerable<TKey, TValue>) dictionaries);\n}\n" }, { "answer_id": 1236968, "author": "Andrew Harry", "author_id": 30576, "author_profile": "https://Stackoverflow.com/users/30576", "pm_score": 4, "selected": false, "text": "using System.Collections.Generic;\nnamespace HelperMethods\n{\n public static class MergeDictionaries\n {\n public static void Merge<TKey, TValue>(this IDictionary<TKey, TValue> first, IDictionary<TKey, TValue> second)\n {\n if (second == null || first == null) return;\n foreach (var item in second) \n if (!first.ContainsKey(item.Key)) \n first.Add(item.Key, item.Value);\n }\n }\n}\n" }, { "answer_id": 2586092, "author": "ctrlalt313373", "author_id": 30889, "author_profile": "https://Stackoverflow.com/users/30889", "pm_score": 5, "selected": false, "text": "Dictionary<String, String> allTables = new Dictionary<String, String>();\nallTables = tables1.Union(tables2).ToDictionary(pair => pair.Key, pair => pair.Value);\n" }, { "answer_id": 2679857, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": false, "text": "public static class DictionaryExtensions\n{\n // Works in C#3/VS2008:\n // Returns a new dictionary of this ... others merged leftward.\n // Keeps the type of 'this', which must be default-instantiable.\n // Example: \n // result = map.MergeLeft(other1, other2, ...)\n public static T MergeLeft<T,K,V>(this T me, params IDictionary<K,V>[] others)\n where T : IDictionary<K,V>, new()\n {\n T newMap = new T();\n foreach (IDictionary<K,V> src in\n (new List<IDictionary<K,V>> { me }).Concat(others)) {\n // ^-- echk. Not quite there type-system.\n foreach (KeyValuePair<K,V> p in src) {\n newMap[p.Key] = p.Value;\n }\n }\n return newMap;\n }\n\n}\n" }, { "answer_id": 6695211, "author": "Jonas Stensved", "author_id": 348841, "author_profile": "https://Stackoverflow.com/users/348841", "pm_score": 8, "selected": false, "text": "dictionaryFrom.ToList().ForEach(x => dictionaryTo.Add(x.Key, x.Value));\n" }, { "answer_id": 14977564, "author": "toong", "author_id": 459406, "author_profile": "https://Stackoverflow.com/users/459406", "pm_score": 3, "selected": false, "text": "public static Dictionary<TKey, TValue> Merge<TKey, TValue>(this IEnumerable<Dictionary<TKey, TValue>> dicts, \n Func<IGrouping<TKey, TValue>, TValue> resolveDuplicates)\n{\n if (resolveDuplicates == null)\n resolveDuplicates = new Func<IGrouping<TKey, TValue>, TValue>(group => group.First());\n\n return dicts.SelectMany<Dictionary<TKey, TValue>, KeyValuePair<TKey, TValue>>(dict => dict)\n .ToLookup(pair => pair.Key, pair => pair.Value)\n .ToDictionary(group => group.Key, group => resolveDuplicates(group));\n}\n" }, { "answer_id": 15957795, "author": "gxtaillon", "author_id": 1275256, "author_profile": "https://Stackoverflow.com/users/1275256", "pm_score": 3, "selected": false, "text": "/// <summary>\n/// Merges a dictionary against an array of other dictionaries.\n/// </summary>\n/// <typeparam name=\"TResult\">The type of the resulting dictionary.</typeparam>\n/// <typeparam name=\"TKey\">The type of the key in the resulting dictionary.</typeparam>\n/// <typeparam name=\"TValue\">The type of the value in the resulting dictionary.</typeparam>\n/// <param name=\"source\">The source dictionary.</param>\n/// <param name=\"mergeBehavior\">A delegate returning the merged value. (Parameters in order: The current key, The current value, The previous value)</param>\n/// <param name=\"mergers\">Dictionaries to merge against.</param>\n/// <returns>The merged dictionary.</returns>\npublic static TResult MergeLeft<TResult, TKey, TValue>(\n this TResult source,\n Func<TKey, TValue, TValue, TValue> mergeBehavior,\n params IDictionary<TKey, TValue>[] mergers)\n where TResult : IDictionary<TKey, TValue>, new()\n{\n var result = new TResult();\n var sources = new List<IDictionary<TKey, TValue>> { source }\n .Concat(mergers);\n\n foreach (var kv in sources.SelectMany(src => src))\n {\n TValue previousValue;\n result.TryGetValue(kv.Key, out previousValue);\n result[kv.Key] = mergeBehavior(kv.Key, kv.Value, previousValue);\n }\n\n return result;\n}\n" }, { "answer_id": 19859243, "author": "Andrew Mikhailov", "author_id": 963384, "author_profile": "https://Stackoverflow.com/users/963384", "pm_score": 1, "selected": false, "text": "internal static class DictionaryExtensions\n{\n public static Dictionary<T1, T2> Merge<T1, T2>(this Dictionary<T1, T2> first, Dictionary<T1, T2> second)\n {\n if (first == null) throw new ArgumentNullException(\"first\");\n if (second == null) throw new ArgumentNullException(\"second\");\n\n var merged = new Dictionary<T1, T2>();\n first.ToList().ForEach(kv => merged[kv.Key] = kv.Value);\n second.ToList().ForEach(kv => merged[kv.Key] = kv.Value);\n\n return merged;\n }\n}\n Dictionary<string, string> merged = first.Merge(second);\n" }, { "answer_id": 23942968, "author": "BSharp", "author_id": 2237957, "author_profile": "https://Stackoverflow.com/users/2237957", "pm_score": 0, "selected": false, "text": "EqualityComparer KeyValuePair Key public class MappedEqualityComparer<T,U> : EqualityComparer<T>\n{\n Func<T,U> _map;\n\n public MappedEqualityComparer(Func<T,U> map)\n {\n _map = map;\n }\n\n public override bool Equals(T x, T y)\n {\n return EqualityComparer<U>.Default.Equals(_map(x), _map(y));\n }\n\n public override int GetHashCode(T obj)\n {\n return _map(obj).GetHashCode();\n }\n}\n // if dictA and dictB are of type Dictionary<int,string>\nvar dict = dictA.Concat(dictB)\n .Distinct(new MappedEqualityComparer<KeyValuePair<int,string>,int>(item => item.Key))\n .ToDictionary(item => item.Key, item=> item.Value);\n" }, { "answer_id": 24624302, "author": "codingatty", "author_id": 1564935, "author_profile": "https://Stackoverflow.com/users/1564935", "pm_score": 5, "selected": false, "text": "foreach (KeyValuePair<string,int> item in D2)\n{\n D1[item.Key] = item.Value;\n}\n" }, { "answer_id": 25213088, "author": "Ethan Reesor", "author_id": 762175, "author_profile": "https://Stackoverflow.com/users/762175", "pm_score": 4, "selected": false, "text": "public static IDictionary<TKey, TValue> Merge<TKey, TValue>(this IDictionary<TKey, TValue> dictA, IDictionary<TKey, TValue> dictB)\n where TValue : class\n{\n return dictA.Keys.Union(dictB.Keys).ToDictionary(k => k, k => dictA.ContainsKey(k) ? dictA[k] : dictB[k]);\n}\n" }, { "answer_id": 26347726, "author": "GoldPaintedLemons", "author_id": 1631216, "author_profile": "https://Stackoverflow.com/users/1631216", "pm_score": 3, "selected": false, "text": " public static void MergeOverwrite<T1, T2>(this IDictionary<T1, T2> dictionary, IDictionary<T1, T2> newElements)\n {\n if (newElements == null) return;\n\n foreach (var e in newElements)\n {\n dictionary.Remove(e.Key); //or if you don't want to overwrite do (if !.Contains()\n dictionary.Add(e);\n }\n }\n public static void MergeOverwrite<T1, T2>(this ConcurrentDictionary<T1, T2> dictionary, IDictionary<T1, T2> newElements)\n {\n if (newElements == null || newElements.Count == 0) return;\n\n foreach (var ne in newElements)\n {\n dictionary.AddOrUpdate(ne.Key, ne.Value, (key, value) => value);\n }\n }\n .Add() Contains() Count public static IDictionary<T1, T2> MergeAllOverwrite<T1, T2>(IList<IDictionary<T1, T2>> allDictionaries)\n {\n var initSize = allDictionaries.Sum(d => d.Count);\n var resultDictionary = new Dictionary<T1, T2>(initSize);\n allDictionaries.ForEach(resultDictionary.MergeOverwrite);\n return resultDictionary;\n }\n IList<T> IEnumerable<T>" }, { "answer_id": 29190972, "author": "keni", "author_id": 123043, "author_profile": "https://Stackoverflow.com/users/123043", "pm_score": 2, "selected": false, "text": "Dictionary<string, string> t1 = new Dictionary<string, string>();\nt1.Add(\"a\", \"aaa\");\nDictionary<string, string> t2 = new Dictionary<string, string>();\nt2.Add(\"b\", \"bee\");\nDictionary<string, string> t3 = new Dictionary<string, string>();\nt3.Add(\"c\", \"cee\");\nt3.Add(\"d\", \"dee\");\nt3.Add(\"b\", \"bee\");\nDictionary<string, string> merged = t1.MergeLeft(t2, t2, t3);\n public static Dictionary<K, V> MergeLeft<K, V>(this Dictionary<K, V> me, params IDictionary<K, V>[] others)\n {\n var newMap = new Dictionary<K, V>(me, me.Comparer);\n foreach (IDictionary<K, V> src in\n (new List<IDictionary<K, V>> { me }).Concat(others))\n {\n // ^-- echk. Not quite there type-system.\n foreach (KeyValuePair<K, V> p in src)\n {\n newMap[p.Key] = p.Value;\n }\n }\n return newMap;\n }\n" }, { "answer_id": 41878989, "author": "Cruces", "author_id": 1771187, "author_profile": "https://Stackoverflow.com/users/1771187", "pm_score": 2, "selected": false, "text": "Dictionary<T1,T2> merged;\nDictionary<T1,T2> mergee;\nmergee.ToList().ForEach(kvp => merged.Add(kvp.Key, kvp.Value));\n mergee.ToList().ForEach(kvp => merged.Append(kvp));\n" }, { "answer_id": 46697068, "author": "jtroconisa", "author_id": 674595, "author_profile": "https://Stackoverflow.com/users/674595", "pm_score": 0, "selected": false, "text": "public static IDictionary<TKey, TValue> Merge<TKey, TValue>( IDictionary<TKey, TValue> x, IDictionary<TKey, TValue> y)\n {\n return x\n .Except(x.Join(y, z => z.Key, z => z.Key, (a, b) => a))\n .Concat(y)\n .ToDictionary(z => z.Key, z => z.Value);\n }\n" }, { "answer_id": 52185235, "author": "Manohar Reddy Poreddy", "author_id": 984471, "author_profile": "https://Stackoverflow.com/users/984471", "pm_score": 2, "selected": false, "text": "{\n // 2 dictionaries, \"b\" key is common with different values\n\n var d1 = new Dictionary<string, int>() { { \"a\", 10 }, { \"b\", 21 } };\n var d2 = new Dictionary<string, int>() { { \"c\", 30 }, { \"b\", 22 } };\n\n var result1 = d1.Concat(d2).GroupBy(ele => ele.Key).ToDictionary(ele => ele.Key, ele => ele.First().Value);\n // result1 is a=10, b=21, c=30 That is, took the \"b\" value of the first dictionary\n\n var result2 = d1.Concat(d2).GroupBy(ele => ele.Key).ToDictionary(ele => ele.Key, ele => ele.Last().Value);\n // result2 is a=10, b=22, c=30 That is, took the \"b\" value of the last dictionary\n}\n {\n // 3 dictionaries, \"b\" key is common with different values\n\n var d1 = new Dictionary<string, int>() { { \"a\", 10 }, { \"b\", 21 } };\n var d2 = new Dictionary<string, int>() { { \"c\", 30 }, { \"b\", 22 } };\n var d3 = new Dictionary<string, int>() { { \"d\", 40 }, { \"b\", 23 } };\n\n var result1 = d1.Concat(d2).Concat(d3).GroupBy(ele => ele.Key).ToDictionary(ele => ele.Key, ele => ele.First().Value);\n // result1 is a=10, b=21, c=30, d=40 That is, took the \"b\" value of the first dictionary\n\n var result2 = d1.Concat(d2).Concat(d3).GroupBy(ele => ele.Key).ToDictionary(ele => ele.Key, ele => ele.Last().Value);\n // result2 is a=10, b=23, c=30, d=40 That is, took the \"b\" value of the last dictionary\n}\n" }, { "answer_id": 52292097, "author": "mattjs", "author_id": 10054848, "author_profile": "https://Stackoverflow.com/users/10054848", "pm_score": 2, "selected": false, "text": "using System.Collections.Generic;\nusing System.Linq;\n\npublic static class DictionaryExtensions\n{\n public enum MergeKind { SkipDuplicates, OverwriteDuplicates }\n public static void Merge<K, V>(this IDictionary<K, V> target, IDictionary<K, V> source, MergeKind kind = MergeKind.SkipDuplicates) =>\n source.ToList().ForEach(_ => { if (kind == MergeKind.OverwriteDuplicates || !target.ContainsKey(_.Key)) target[_.Key] = _.Value; });\n}\n" }, { "answer_id": 55655960, "author": "mattylantz", "author_id": 1883961, "author_profile": "https://Stackoverflow.com/users/1883961", "pm_score": 1, "selected": false, "text": "public static IDictionary<K, V> AddRange<K, V>(this IDictionary<K, V> one, IDictionary<K, V> two)\n {\n foreach (var kvp in two)\n {\n if (one.ContainsKey(kvp.Key))\n one[kvp.Key] = two[kvp.Key];\n else\n one.Add(kvp.Key, kvp.Value);\n }\n return one;\n }\n" }, { "answer_id": 56034062, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "var result = dictionary1.Union(dictionary2).ToDictionary(k => k.Key, v => v.Value)\n var result = dictionary1.Union(dictionary2.Where(k => !dictionary1.ContainsKey(k.Key))).ToDictionary(k => k.Key, v => v.Value)\n var result = dictionaries.SelectMany(dict => dict)\n .ToLookup(pair => pair.Key, pair => pair.Value)\n .ToDictionary(group => group.Key, group => group.First());\n" }, { "answer_id": 56149618, "author": "gorillapower", "author_id": 592449, "author_profile": "https://Stackoverflow.com/users/592449", "pm_score": 2, "selected": false, "text": "IEqualityComparer public static T MergeLeft<T, K, V>(this T me, params Dictionary<K, V>[] others)\n where T : Dictionary<K, V>, new()\n {\n return me.MergeLeft(me.Comparer, others);\n }\n\n public static T MergeLeft<T, K, V>(this T me, IEqualityComparer<K> comparer, params Dictionary<K, V>[] others)\n where T : Dictionary<K, V>, new()\n {\n T newMap = Activator.CreateInstance(typeof(T), new object[] { comparer }) as T;\n\n foreach (Dictionary<K, V> src in \n (new List<Dictionary<K, V>> { me }).Concat(others))\n {\n // ^-- echk. Not quite there type-system.\n foreach (KeyValuePair<K, V> p in src)\n {\n newMap[p.Key] = p.Value;\n }\n }\n return newMap;\n }\n" }, { "answer_id": 57490396, "author": "mattjs", "author_id": 10054848, "author_profile": "https://Stackoverflow.com/users/10054848", "pm_score": 3, "selected": false, "text": "using System.Collections.Generic;\nusing System.Linq;\n\npublic static partial class Extensions\n{\n public static void Merge<K, V>(this IDictionary<K, V> target, \n IDictionary<K, V> source, \n bool overwrite = false)\n {\n foreach (KeyValuePair _ in source)\n if (overwrite || !target.ContainsKey(_.Key))\n target[_.Key] = _.Value;\n }\n}\n" }, { "answer_id": 57571811, "author": "Andy", "author_id": 45062, "author_profile": "https://Stackoverflow.com/users/45062", "pm_score": 2, "selected": false, "text": "public static void Add<K, V>(this Dictionary<K, V> d, Dictionary<K, V> other) {\n foreach (var kvp in other)\n {\n if (!d.ContainsKey(kvp.Key))\n {\n d.Add(kvp.Key, kvp.Value);\n }\n }\n}\n\n\nvar s0 = new Dictionary<string, string> {\n { \"A\", \"X\"}\n};\nvar s1 = new Dictionary<string, string> {\n { \"A\", \"X\" },\n { \"B\", \"Y\" }\n};\n// Combine as many dictionaries and key pairs as needed\nvar a = new Dictionary<string, string> {\n s0, s1, s0, s1, s1, { \"C\", \"Z\" }\n};\n" }, { "answer_id": 67575310, "author": "idbrii", "author_id": 79125, "author_profile": "https://Stackoverflow.com/users/79125", "pm_score": 0, "selected": false, "text": "AddAll() Merge() using System.Collections.Generic;\n...\npublic static Dictionary<TKey, TValue>\n AddAll<TKey,TValue>(Dictionary<TKey, TValue> dest, Dictionary<TKey, TValue> source)\n{\n foreach (var x in source)\n dest[x.Key] = x.Value;\n}\n\npublic static Dictionary<TKey, TValue>\n Merge<TKey,TValue>(IEnumerable<Dictionary<TKey, TValue>> dictionaries)\n{\n var result = new Dictionary<TKey, TValue>();\n foreach (var dict in dictionaries)\n result.AddAll(dict);\n return result;\n}\n" }, { "answer_id": 70684990, "author": "Axel Samyn", "author_id": 4456593, "author_profile": "https://Stackoverflow.com/users/4456593", "pm_score": -1, "selected": false, "text": "Dictionary<string, object> customAttributes = \n HtmlHelper\n .AnonymousObjectToHtmlAttributes(htmlAttributes)\n .ToDictionary(\n ca => ca.Key, \n ca => ca.Value\n );\n\nDictionary<string, object> fixedAttributes = \n new RouteValueDictionary(\n new { \n @class = \"form-control\"\n }).ToDictionary(\n fa => fa.Key, \n fa => fa.Value\n );\n\n//appending the html class attributes\nIDictionary<string, object> editorAttributes = fixedAttributes.Merge(customAttributes, (leftValue, rightValue) => leftValue + \" \" + rightValue);\n ToDictionary() Merge() IDictionary public static class IDictionaryExtension\n {\n public static IDictionary<T, U> Merge<T, U>(this IDictionary<T, U> sourceLeft, IDictionary<T, U> sourceRight)\n {\n IDictionary<T, U> result = new Dictionary<T,U>();\n\n sourceLeft\n .Concat(sourceRight)\n .ToList()\n .ForEach(kvp => \n result[kvp.Key] = kvp.Value\n );\n\n return result;\n }\n\n public static IDictionary<T, U> Merge<T, U>(this IDictionary<T, U> sourceLeft, IDictionary<T, U> sourceRight, Func<U, U, U> mergeExpression)\n {\n IDictionary<T, U> result = new Dictionary<T,U>();\n\n //Merge expression example\n //(leftValue, rightValue) => leftValue + \" \" + rightValue;\n\n sourceLeft\n .Concat(sourceRight)\n .ToList()\n .ForEach(kvp => \n result[kvp.Key] =\n (!result.ContainsKey(kvp.Key))\n ? kvp.Value\n : mergeExpression(result[kvp.Key], kvp.Value)\n );\n\n return result;\n }\n\n\n public static IDictionary<T, U> Merge<T, U>(this IDictionary<T, U> sourceLeft, IEnumerable<IDictionary<T, U>> sourcesRight)\n {\n IDictionary<T, U> result = new Dictionary<T, U>();\n \n new[] { sourceLeft }\n .Concat(sourcesRight)\n .ToList()\n .ForEach(dic =>\n result = result.Merge(dic)\n );\n\n return result;\n }\n\n public static IDictionary<T, U> Merge<T, U>(this IDictionary<T, U> sourceLeft, IEnumerable<IDictionary<T, U>> sourcesRight, Func<U, U, U> mergeExpression)\n {\n IDictionary<T, U> result = new Dictionary<T, U>();\n\n new[] { sourceLeft }\n .Concat(sourcesRight)\n .ToList()\n .ForEach(dic =>\n result = result.Merge(dic, mergeExpression)\n );\n\n return result;\n }\n }\n mergeExpression" }, { "answer_id": 70788858, "author": "Sunday", "author_id": 1700939, "author_profile": "https://Stackoverflow.com/users/1700939", "pm_score": 2, "selected": false, "text": "dict.update() public static class DictionaryExtensions\n{\n public static void Update<K,V>(this IDictionary<K, V> me, IDictionary<K, V> other)\n {\n foreach (var x in other)\n {\n me[x.Key] = x.Value;\n }\n }\n}\n" }, { "answer_id": 74552898, "author": "Eldar Mahmudov", "author_id": 10423007, "author_profile": "https://Stackoverflow.com/users/10423007", "pm_score": 0, "selected": false, "text": "namespace Extentions\n{\n public static class DictionayExtensions\n {\n public static Dictionary<T, Y> MergeWith<T, Y>(this Dictionary<T, Y> dictA, Dictionary<T, Y> dictB)\n {\n\n foreach (var item in dictB)\n {\n if (dictA.ContainsKey(item.Key))\n dictA[item.Key] = item.Value;\n else\n dictA.Add(item.Key, item.Value);\n }\n return dictA;\n }\n }\n}\n var d1 = new Dictionary<string, string>();\n var d2=new Dictionary<string, string>();\n d1.MergeWith(d2);\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/294138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37020/" ]
294,171
<p>I have a delegate, say:</p> <pre><code>public delegate void MyDelegate(); </code></pre> <p>I have an event, say:</p> <pre><code>public MyDelegate MyEvent; </code></pre> <p>While invoking the event I am receiving an error message:</p> <blockquote> <p>"MyEvent += expected ....."</p> </blockquote> <p>How do I resolve this?</p>
[ { "answer_id": 294175, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "+= -=" }, { "answer_id": 294348, "author": "Geoff Cox", "author_id": 30505, "author_profile": "https://Stackoverflow.com/users/30505", "pm_score": 2, "selected": false, "text": "public **event** MyDelegate MyEvent;\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/294171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
294,172
<p>I have this piece of code:</p> <pre><code>$("#faq").click(function () { var url = $.get("faq", { pagina: "page" }); alert(url); }); </code></pre> <p>On "faq" responds to a Servlet that sets an attribute on the request </p> <pre><code>.... request.setAttribute("pageFAQ", pageFAQ); .... </code></pre> <p>After the get jQuery prints [object XmlHttpRequest].</p> <p>I would like to access to the attribute set in the Servlet but I don't know how to do it.</p>
[ { "answer_id": 294385, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 2, "selected": true, "text": "$(\"#faq\").click(function () { \n $.get(\n \"faq\", \n { pagina: \"page\" },\n function(data) { // callback function, executed on GET success\n alert(data);\n }\n );\n});\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/294172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38058/" ]
294,193
<p>I normally use scp to copy stuff, but now I'm trying to get used to the more powerful rsync command. It helps me use less bandwidth by copying up only files that have changed. However, rsync has a lot of complex parameters, so I thought, hey, I'll just make a little Bash script that makes it easy for me, and call the command 'rscp'. So, off I went building something like this. Note in the example below that my web host uses a different port number besides 22, so that's why the $1 is used for that.</p> <pre><code>#!/bin/bash rsync -avzp --progress --rsh='ssh -p$1' $2 $3 $4 $5 $6 $7 </code></pre> <p>So, its usage, I hoped, would be something like:</p> <pre><code>rscp 3822 --exclude=tiny_mce /var/www/mysite/* root@webhost.com:~/www/mysite </code></pre> <p>That would make it a little bit closer to my usage of the scp command, you see.</p> <p>However, when I ran this, I get this error:</p> <pre><code>building file list ... 4 files to consider ERROR: destination must be a directory when copying more than 1 file rsync error: errors selecting input/output files, dirs (code 3) at main.c(494) [receiver=2.6.9] rsync: connection unexpectedly closed (8 bytes received so far) [sender] rsync error: error in rsync protocol data stream (code 12) at io.c(454) [sender=2.6.9] </code></pre> <p>But if I go back to the regular rsync command, it works just fine.</p> <p>Can anyone figure out what I'm doing wrong in my Bash script?</p>
[ { "answer_id": 294240, "author": "Douglas Leeder", "author_id": 3978, "author_profile": "https://Stackoverflow.com/users/3978", "pm_score": 4, "selected": true, "text": "#!/bin/bash\nPORT=$1\nshift\nrsync -avzp --progress --rsh=\"ssh -p$PORT\" \"$@\"\n" }, { "answer_id": 41310369, "author": "Jamie Metzger", "author_id": 7096214, "author_profile": "https://Stackoverflow.com/users/7096214", "pm_score": 0, "selected": false, "text": " rscp() {\nrsync -avzp --progress --rsh=\"ssh -p$PORT\" \"$@\"\n}\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/294193", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
294,201
<p>Given 2 file revisions I want to know how many lines were added/modified/deleted. I want to have this information for the entire repository of thousand of files. Please point me to a script or tool as I am a total svn newbie</p> <p>I am working on windows</p> <p>Sample output</p> <p>File~NewRevision~OldRevision~Added~Modified~Deleted</p> <p>file1.c~#11~#10~1~2~0</p> <p>file1.c~#2~#1~2~2~0</p>
[ { "answer_id": 294229, "author": "Peter Bratton", "author_id": 37856, "author_profile": "https://Stackoverflow.com/users/37856", "pm_score": 4, "selected": true, "text": "svn diff -rOldRevision:NewRevision URL\n" }, { "answer_id": 294245, "author": "coppro", "author_id": 16855, "author_profile": "https://Stackoverflow.com/users/16855", "pm_score": 2, "selected": false, "text": "svn diff --diff-cmd diff -x -w -x -u -rOldRev:NewRev" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/294201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30546/" ]
294,216
<p>This causes a compile-time exception:</p> <pre><code>public sealed class ValidatesAttribute&lt;T&gt; : Attribute { } [Validates&lt;string&gt;] public static class StringValidation { } </code></pre> <p>I realize C# does not support generic attributes. However, after much Googling, I can't seem to find the reason.</p> <p>Does anyone know why generic types cannot derive from <code>Attribute</code>? Any theories?</p>
[ { "answer_id": 294248, "author": "ichiban", "author_id": 37081, "author_profile": "https://Stackoverflow.com/users/37081", "pm_score": 3, "selected": false, "text": "typeof(Validates<string>) typeof(Validates<SomeCustomType>) SomeCustomValidationDelegate ISomeCustomValidator" }, { "answer_id": 294438, "author": "GeekyMonkey", "author_id": 29900, "author_profile": "https://Stackoverflow.com/users/29900", "pm_score": 5, "selected": false, "text": "[AttributeUsage(AttributeTargets.Class)]\npublic class ClassDescriptionAttribute : Attribute\n{\n public ClassDescriptionAttribute(Type KeyDataType)\n {\n _KeyDataType = KeyDataType;\n }\n\n public Type KeyDataType\n {\n get { return _KeyDataType; }\n }\n private Type _KeyDataType;\n}\n\n\n[ClassDescriptionAttribute(typeof(string))]\nclass Program\n{\n ....\n}\n" }, { "answer_id": 19829612, "author": "nawfal", "author_id": 661933, "author_profile": "https://Stackoverflow.com/users/661933", "pm_score": 4, "selected": false, "text": "//an interface which means it can't have its own implementation. \n//You might need to use extension methods on this interface for that.\npublic interface ValidatesAttribute<T>\n{\n T Value { get; } //or whatever that is\n bool IsValid { get; } //etc\n}\n\npublic class ValidatesStringAttribute : Attribute, ValidatesAttribute<string>\n{\n //...\n}\npublic class ValidatesIntAttribute : Attribute, ValidatesAttribute<int>\n{\n //...\n}\n\n[ValidatesString]\npublic static class StringValidation\n{\n\n}\n[ValidatesInt]\npublic static class IntValidation\n{\n\n}\n" }, { "answer_id": 35078573, "author": "razon", "author_id": 908936, "author_profile": "https://Stackoverflow.com/users/908936", "pm_score": -1, "selected": false, "text": "public class DistinctType1IdValidation : ValidationAttribute\n{\n private readonly DistinctValidator<Type1> validator;\n\n public DistinctIdValidation()\n {\n validator = new DistinctValidator<Type1>(x=>x.Id);\n }\n\n public override bool IsValid(object value)\n {\n return validator.IsValid(value);\n }\n}\n\npublic class DistinctType2NameValidation : ValidationAttribute\n{\n private readonly DistinctValidator<Type2> validator;\n\n public DistinctType2NameValidation()\n {\n validator = new DistinctValidator<Type2>(x=>x.Name);\n }\n\n public override bool IsValid(object value)\n {\n return validator.IsValid(value);\n }\n}\n\n...\n[DataMember, DistinctType1IdValidation ]\npublic Type1[] Items { get; set; }\n\n[DataMember, DistinctType2NameValidation ]\npublic Type2[] Items { get; set; }\n" }, { "answer_id": 70370475, "author": "Hossein Ebrahimi", "author_id": 11627521, "author_profile": "https://Stackoverflow.com/users/11627521", "pm_score": 3, "selected": false, "text": "public class GenericType<T>\n{\n [GenericAttribute<T>()] // Not allowed! generic attributes must be fully closed types.\n public string Method() => default;\n}\n dynamic string? (int X, int Y) object dynamic string string? ValueTuple<int, int> (int X, int Y)" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/294216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37815/" ]
294,217
<p>In ARM assembly immediates are encoded by an 8-bit rotated value which means we can only encode </p> <pre><code>(0-256)^2n. </code></pre> <p>Now my problem is that I want to clear the upper 16-bits of r0 and replace it with the half-word stored r1. But because of the limited range of the immediates I have to do: -</p> <pre><code>bic r0, r0, #0xff000000 bic r0, r0, #0x00ff0000 add r0, r0, r1, LSL #16 </code></pre> <p>Is it possible to do replace the 2 bic instructions with a single instruction? 0xffff0000 is unencodable. Perhaps I should be using another logical operation to clear the upper 16-bits?</p> <p>Thanks</p> <p>EDIT: Sorry I forgot to say that the top 16-bits of r1 is empty, and I'm using an ARM7TDMI</p>
[ { "answer_id": 294227, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 0, "selected": false, "text": "xor" }, { "answer_id": 294284, "author": "Martin v. Löwis", "author_id": 33006, "author_profile": "https://Stackoverflow.com/users/33006", "pm_score": 0, "selected": false, "text": " (a<<16)|((short)b)\n mov r1, r1, asl #16\n mov r1, r1, asr #16\n orr r0, r1, r0, asl #16\n" }, { "answer_id": 294435, "author": "Martin v. Löwis", "author_id": 33006, "author_profile": "https://Stackoverflow.com/users/33006", "pm_score": 1, "selected": false, "text": " uxth r1, r1\n orr r0, r1, r0, asl #16\n" }, { "answer_id": 294456, "author": "moonshadow", "author_id": 11834, "author_profile": "https://Stackoverflow.com/users/11834", "pm_score": 2, "selected": false, "text": "add r0, r1, r0 lsl #16\nmov r0, r0 ror #16\n" }, { "answer_id": 294501, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "orr r0,r1,r0,lsl #16\nmov r0,r0,ror #16\n" }, { "answer_id": 295494, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 3, "selected": false, "text": "movt r0, #0\norr r0, r0, r1,lsl#16\n pkhbt r0, r0, r1,lsl#16\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/294217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27653/" ]
294,220
<p>I'm trying to create a WPF application where I can drag an image around.</p> <p>Currently I have an image placed in the center of the window, and I'm thinking of using the three mouseevents MouseDown, MouseMove and MouseUp to calculate the new position when dragging the image.</p> <p>Are there any other good ideas on how to do this? I'm totally new to WPF so my mindset is still in the Windows Forms world.</p> <p>As far as I can see I need to use a in order to have absolute positioning available.</p>
[ { "answer_id": 294412, "author": "deepcode.co.uk", "author_id": 20524, "author_profile": "https://Stackoverflow.com/users/20524", "pm_score": 6, "selected": true, "text": "public class DraggableExtender : DependencyObject\n{\n // This is the dependency property we're exposing - we'll \n // access this as DraggableExtender.CanDrag=\"true\"/\"false\"\n public static readonly DependencyProperty CanDragProperty =\n DependencyProperty.RegisterAttached(\"CanDrag\",\n typeof(bool),\n typeof(DraggableExtender),\n new UIPropertyMetadata(false, OnChangeCanDragProperty));\n\n // The expected static setter\n public static void SetCanDrag(UIElement element, bool o)\n {\n element.SetValue(CanDragProperty, o);\n }\n\n // the expected static getter\n public static bool GetCanDrag(UIElement element)\n {\n return (bool) element.GetValue(CanDragProperty);\n }\n\n // This is triggered when the CanDrag property is set. We'll\n // simply check the element is a UI element and that it is\n // within a canvas. If it is, we'll hook into the mouse events\n private static void OnChangeCanDragProperty(DependencyObject d, \n DependencyPropertyChangedEventArgs e)\n {\n UIElement element = d as UIElement;\n if (element == null) return;\n\n if (e.NewValue != e.OldValue)\n {\n if ((bool)e.NewValue)\n {\n element.PreviewMouseDown += element_PreviewMouseDown;\n element.PreviewMouseUp += element_PreviewMouseUp;\n element.PreviewMouseMove += element_PreviewMouseMove;\n }\n else\n {\n element.PreviewMouseDown -= element_PreviewMouseDown;\n element.PreviewMouseUp -= element_PreviewMouseUp;\n element.PreviewMouseMove -= element_PreviewMouseMove;\n }\n }\n }\n\n // Determine if we're presently dragging\n private static bool _isDragging = false;\n // The offset from the top, left of the item being dragged \n // and the original mouse down\n private static Point _offset;\n\n // This is triggered when the mouse button is pressed \n // on the element being hooked\n static void element_PreviewMouseDown(object sender,\n System.Windows.Input.MouseButtonEventArgs e)\n {\n // Ensure it's a framework element as we'll need to \n // get access to the visual tree\n FrameworkElement element = sender as FrameworkElement;\n if (element == null) return;\n\n // start dragging and get the offset of the mouse \n // relative to the element\n _isDragging = true;\n _offset = e.GetPosition(element);\n }\n\n // This is triggered when the mouse is moved over the element\n private static void element_PreviewMouseMove(object sender, \n MouseEventArgs e)\n {\n // If we're not dragging, don't bother - also validate the element\n if (!_isDragging) return;\n\n FrameworkElement element = sender as FrameworkElement;\n if (element == null) return;\n\n Canvas canvas = element.Parent as Canvas;\n if( canvas == null ) return;\n\n // Get the position of the mouse relative to the canvas\n Point mousePoint = e.GetPosition(canvas);\n\n // Offset the mouse position by the original offset position\n mousePoint.Offset(-_offset.X, -_offset.Y);\n\n // Move the element on the canvas\n element.SetValue(Canvas.LeftProperty, mousePoint.X);\n element.SetValue(Canvas.TopProperty, mousePoint.Y);\n }\n\n // this is triggered when the mouse is released\n private static void element_PreviewMouseUp(object sender, \n MouseButtonEventArgs e)\n {\n _isDragging = false;\n }\n\n}\n <Window x:Class=\"WPFFunWithDragging.Window1\"\n xmlns:local=\"clr-namespace:WPFFunWithDragging\" .. >\n <Canvas>\n <Image Source=\"Garden.jpg\" \n Width=\"50\" \n Canvas.Left=\"10\" Canvas.Top=\"10\" \n local:DraggableExtender.CanDrag=\"true\"/>\n</Canvas>\n" }, { "answer_id": 59535830, "author": "Tomáš Buchta", "author_id": 12387934, "author_profile": "https://Stackoverflow.com/users/12387934", "pm_score": 0, "selected": false, "text": " private void Element_PreviewMouseDown(object sender, MouseEventArgs e)\n {\n element.CaptureMouse();\n }\n\n private void Element_PreviewMouseUp(object sender, MouseButtonEventArgs e)\n {\n element.ReleaseMouseCapture();\n }\n if (mousePoint.X > 0 && mousePoint.X + element.ActualWidth <= canvas.ActualWidth &&\n mousePoint.Y > 0 && mousePoint.Y + element.ActualHeight <= canvas.ActualHeight)\n {\n element.SetValue(Canvas.LeftProperty, mousePoint.X);\n element.SetValue(Canvas.TopProperty, mousePoint.Y);\n }\n private void Element_PreviewMouseDown(object sender, MouseEventArgs e)\n {\n Panel.SetZIndex(element, 1);\n }\n\n private void Element_PreviewMouseUp(object sender, MouseButtonEventArgs e)\n {\n Panel.SetZIndex(element, 0);\n }\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/294220", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33431/" ]
294,234
<p>I'm working on an assignment that is telling me to assume that I have a singly linked list with a header and tail nodes. It wants me to insert an item y before position p. Can anybody please look over my code and tell me if I'm on the right track? If not, can you provide me with any tips or pointers (no pun intended)? </p> <pre><code>tmp = new Node(); tmp.element = p.element; tmp.next = p.next; p.element = y; p.next = tmp; </code></pre> <p>I think I may be wrong because I do not utilize the header and tail nodes at all even though they are specifically mentioned in the description of the problem. I was thinking of writing a while loop to traverse the list until it found p and tackle the problem that way but that wouldn't be constant-time, would it?</p>
[ { "answer_id": 294243, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 4, "selected": true, "text": "// First we have a pointer to a node containing element (elm) \n// with possible a next element.\n// Graphically drawn as:\n// p -> [elm] -> ???\n\ntmp = new Node();\n// A new node is created. Variable tmp points to the new node which \n// currently has no value.\n// p -> [elm] -> ???\n// tmp -> [?]\n\ntmp.element = p.element;\n\n// The new node now has the same element as the original.\n// p -> [elm] -> ???\n// tmp -> [elm]\n\ntmp.next = p.next;\n\n// The new node now has the same next node as the original.\n// p -> [elm] -> ???\n// tmp -> [elm] -> ???\n\np.element = y;\n\n// The original node now contains the element y.\n// p -> [y] -> ???\n// tmp -> [elm] -> ???\n\np.next = tmp;\n\n// The new node is now the next node from the following.\n// p -> [y] -> [elm] -> ???\n// tmp -> [elm] -> ???\n tmp = new Node();\ntmp.element = y;\ntmp.next = p;\np = tmp;\n" }, { "answer_id": 2554971, "author": "lakshmi", "author_id": 306227, "author_profile": "https://Stackoverflow.com/users/306227", "pm_score": 0, "selected": false, "text": "create a node ptr\nptr->info = item //item is the element to be inserted...\nptr->next = NULL\nif (start == NULL) //insertion at the end...\n start = ptr\nelse\n temp = ptr\n while (temp->next != NULL)\n temp = temp->next\n end while \nend if\nif (start == NULL) //insertion at the beginning...\n start = ptr\nelse\n temp = start\n ptr->info = item\n ptr->next = start\n start = ptr\nend if\ntemp = start //insertion at specified location...\nfor (i = 1; i < pos-1; i++)\n if (start == NULL)\n start = ptr\n else\n t = temp\n temp = temp->next\n end if\nend for\nt->next = ptr->next\nt->next = ptr\n" }, { "answer_id": 72067765, "author": "Debendra Nath Mukherjee", "author_id": 15778967, "author_profile": "https://Stackoverflow.com/users/15778967", "pm_score": 0, "selected": false, "text": "import java.io.*;\nimport java.util.*;\n\npublic class Solution {\n \n // class Solution is what should be called as the LINKEDLIST class but its ok\n \n Node head; // declaring a head for the LL\n \n class Node { // Node class\n \n int data; // the .data variable\n Node ref; // .ref aka .next \n\n Node(int data) { // constructor for initializing the values\n \n this.data = data;\n this.ref = null;\n \n }\n }\n \n public void append(int data) { // i call 'to join at the end' as append\n // O(N)\n \n Node newnode = new Node(data); // new node creation\n \n if (head == null) { // checking is head is null aka None in Py\n head = newnode;\n return;\n }\n \n Node curr = head; // assigning head to a curr node ready for traversal\n \n while (curr.ref != null) { // traversal begins\n curr = curr.ref;\n } // traversal ends\n \n curr.ref = newnode; // this is the last node where the join happens\n \n }\n \n public void p() { // i name printing function as p()\n \n if (head == null) { // if head is null then print empty\n System.out.println(\"Empty\");\n return;\n }\n \n Node curr = head; // same thing - traversal begins here\n \n while (curr != null) {\n System.out.println(curr.data);\n curr = curr.ref;\n } // by now all data values have been printed out already\n \n }\n\n public static void main(String[] args) {\n \n Scanner sc = new Scanner(System.in); // scanner class for input\n \n Solution l = new Solution(); // object creating for LL as Solution class name\n \n int numberOfNodes = sc.nextInt(); // input for number of NODEs in LL\n \n for (int i = 0; i < numberOfNodes; i++) { // loop for .data values\n \n int data = sc.nextInt(); \n l.append(data); // function append call for each (i)\n \n }\n \n l.p(); // finally print func call to display output LL\n \n }\n}\n\n\nclass PractGG {\n Node head;\n Node tail;\n\n class Node {\n int data;\n Node ref;\n Node(int data) {\n this.data = data;\n this.ref = null;\n }\n }\n public void push(int data) {\n Node newnode = new Node(data);\n if (head == null) {\n tail = head = newnode;\n return;\n }\n newnode.ref = head;\n head = newnode;\n }\n public void append(int data) {\n // O(1)\n Node newnode = new Node(data);\n if (tail == null) {\n tail = head = newnode;\n return;\n }\n tail.ref = newnode;\n tail = newnode;\n }\n \n public void p() {\n if (head == null) {\n System.out.println(\"Empty\");\n }\n Node curr = head;\n while (curr!=null) {\n System.out.print(curr.data + \"==>\");\n curr = curr.ref;\n }\n System.out.println();\n }\n public static void main(String[] args) {\n PractGG l = new PractGG();\n l.append(1);\n l.append(2);\n l.append(3);\n l.p();\n }\n}\n\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/294234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14013/" ]
294,250
<p>Suppose that I have a <code>&lt;div&gt;</code> that I wish to center in the browser's display (viewport). To do so, I need to calculate the width and height of the <code>&lt;div&gt;</code> element. </p> <p>What should I use? Please include information on browser compatibility.</p>
[ { "answer_id": 294268, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 6, "selected": false, "text": "height width outerHeight outerWidth var height = $(\"#myDiv\").height();\nvar width = $(\"#myDiv\").width();\n\nvar docHeight = $(document).height();\nvar docWidth = $(document).width();\n" }, { "answer_id": 294273, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 12, "selected": true, "text": ".offsetWidth .offsetHeight .style var width = document.getElementById('foo').offsetWidth;\n .getBoundingClientRect() > console.log(document.getElementById('foo').getBoundingClientRect())\nDOMRect {\n bottom: 177,\n height: 54.7,\n left: 278.5,​\n right: 909.5,\n top: 122.3,\n width: 631,\n x: 278.5,\n y: 122.3,\n}\n" }, { "answer_id": 294390, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 3, "selected": false, "text": "<style type=\"text/css\">\n html,body {display:table; height:100%;width:100%;margin:0;padding:0;}\n body {display:table-cell; vertical-align:middle;}\n div {display:table; margin:0 auto; background:red;}\n</style>\n<body><div>test<br>test</div></body>\n <div>" }, { "answer_id": 681171, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "var divID = document.getElementById(\"divid\");\n\nvar h = divID.style.pixelHeight;\n" }, { "answer_id": 9508887, "author": "sanecin", "author_id": 1241539, "author_profile": "https://Stackoverflow.com/users/1241539", "pm_score": 1, "selected": false, "text": "<style>\n .monitor {\n position:fixed;/* ... absolute possible if on :root */\n top:0;bottom:0;right:0;left:0;\n visibility:hidden;\n }\n .wrapper {\n width:200px;/* this is size range */\n height:100px;\n position:absolute;\n left:50%;top:50%;\n visibility:hidden;\n }\n\n .content {\n position:absolute;\n width: 100%;height:100%;\n left:-50%;top:-50%;\n visibility:visible;\n }\n\n</style>\n\n <div class=\"monitor\">\n <div class=\"wrapper\">\n <div class=\"content\">\n\n ... so you hav div 200px*100px on center ...\n\n </div>\n </div>\n</div>\n" }, { "answer_id": 32658882, "author": "Zach Lysobey", "author_id": 363701, "author_profile": "https://Stackoverflow.com/users/363701", "pm_score": 8, "selected": false, "text": "Element.getBoundingClientRect() width height {\n width: 960,\n height: 71,\n top: 603,\n bottom: 674,\n left: 360,\n right: 1320\n}\n var element = document.getElementById('foo');\nvar positionInfo = element.getBoundingClientRect();\nvar height = positionInfo.height;\nvar width = positionInfo.width;\n .offsetWidth .offsetHeight 0 getBoundingClientRect() .offsetWidth .offsetHeight getBoundingClientRect .offsetWidth .offsetHeight var height = element.offsetHeight;\nvar width = element.offsetWidth;\n Object.keys .offsetHeight .offsetWidth .getBoundingClientRect()" }, { "answer_id": 35505821, "author": "Graham", "author_id": 1180438, "author_profile": "https://Stackoverflow.com/users/1180438", "pm_score": 6, "selected": false, "text": "width:200px;\nheight:20px;\nborder:solid 1px #000;\npadding:2px;\n\n<input id=\"t\" type=\"text\" />\n<input id=\"b\" type=\"button\" />\n<div id=\"d\"></div>\n box-sizing:border-box <!DOCTYPE html> Firefox Chrome IE-Edge \n with w/o with w/o with w/o box-sizing\n\n$(\"#t\").width() 194 200 194 200 194 200\n$(\"#b\").width() 194 194 194 194 194 194\n$(\"#d\").width() 194 200 194 200 194 200\n\n$(\"#t\").outerWidth() 200 206 200 206 200 206\n$(\"#b\").outerWidth() 200 200 200 200 200 200\n$(\"#d\").outerWidth() 200 206 200 206 200 206\n\n$(\"#t\").innerWidth() 198 204 198 204 198 204\n$(\"#b\").innerWidth() 198 198 198 198 198 198\n$(\"#d\").innerWidth() 198 204 198 204 198 204\n\n$(\"#t\").css('width') 200px 200px 200px 200px 200px 200px\n$(\"#b\").css('width') 200px 200px 200px 200px 200px 200px\n$(\"#d\").css('width') 200px 200px 200px 200px 200px 200px\n\n$(\"#t\").css('border-left-width') 1px 1px 1px 1px 1px 1px\n$(\"#b\").css('border-left-width') 1px 1px 1px 1px 1px 1px\n$(\"#d\").css('border-left-width') 1px 1px 1px 1px 1px 1px\n\n$(\"#t\").css('padding-left') 2px 2px 2px 2px 2px 2px\n$(\"#b\").css('padding-left') 2px 2px 2px 2px 2px 2px\n$(\"#d\").css('padding-left') 2px 2px 2px 2px 2px 2px\n\ndocument.getElementById(\"t\").getBoundingClientRect().width 200 206 200 206 200 206\ndocument.getElementById(\"b\").getBoundingClientRect().width 200 200 200 200 200 200\ndocument.getElementById(\"d\").getBoundingClientRect().width 200 206 200 206 200 206\n\ndocument.getElementById(\"t\").offsetWidth 200 206 200 206 200 206\ndocument.getElementById(\"b\").offsetWidth 200 200 200 200 200 200\ndocument.getElementById(\"d\").offsetWidth 200 206 200 206 200 206\n" }, { "answer_id": 49058327, "author": "HarlemSquirrel", "author_id": 3446655, "author_profile": "https://Stackoverflow.com/users/3446655", "pm_score": 5, "selected": false, "text": "offsetWidth offsetHeight clientWidth clientHeight scrollWidth scrollHeight" }, { "answer_id": 50061930, "author": "Lekens", "author_id": 7575288, "author_profile": "https://Stackoverflow.com/users/7575288", "pm_score": 3, "selected": false, "text": "<head>\n <style> body { color: red; margin: 5px } </style>\n</head>\n<body>\n\n <script>\n let computedStyle = getComputedStyle(document.body);\n\n // now we can read the margin and the color from it\n\n alert( computedStyle.marginTop ); // 5px\n alert( computedStyle.color ); // rgb(255, 0, 0)\n </script>\n\n</body>\n window.onload = function() {\n\n var test = document.getElementById(\"test\");\n test.addEventListener(\"click\", select);\n\n\n function select(e) { \n var elementID = e.target.id;\n var element = document.getElementById(elementID);\n let computedStyle = getComputedStyle(element);\n var width = computedStyle.width;\n console.log(element);\n console.log(width);\n }\n\n}\n <style>\n body {\n margin: 30px;\n height: 900px;\n }\n</style>\n<script>\n let style = getComputedStyle(document.body);\n alert(style.margin); // empty string in Firefox\n</script>\n" }, { "answer_id": 50623678, "author": "Aleksey Mazurenko", "author_id": 821994, "author_profile": "https://Stackoverflow.com/users/821994", "pm_score": -1, "selected": false, "text": "let html = \"<body><span id=\\\"spanEl\\\" style=\\\"font-family: '\\(taskFont.fontName)'; font-size: \\(taskFont.pointSize - 4.0)pt; color: rgb(\\(red), \\(blue), \\(green))\\\">\\(textValue)</span></body>\"\nwebView.navigationDelegate = self\nwebView.loadHTMLString(taskHTML, baseURL: nil)\n\nfunc webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {\n webView.evaluateJavaScript(\"document.getElementById(\\\"spanEl\\\").getBoundingClientRect().height;\") { [weak self] (response, error) in\n if let nValue = response as? NSNumber {\n\n }\n }\n}\n" }, { "answer_id": 63494678, "author": "Kamil Kiełczewski", "author_id": 860099, "author_profile": "https://Stackoverflow.com/users/860099", "pm_score": 0, "selected": false, "text": "<div> <div> .box {\n width: 50px;\n height: 20px;\n background: red;\n}\n\n.container {\n display: flex;\n justify-content: center;\n align-items: center;\n height: 100vh;\n width: 100vw;\n position: fixed; /* remove this in case there is no content under div (and remember to set body margins to 0)*/\n} <div class=\"container\">\n <div class=\"box\">My div</div>\n</div>" }, { "answer_id": 64650777, "author": "user1767599", "author_id": 1767599, "author_profile": "https://Stackoverflow.com/users/1767599", "pm_score": -1, "selected": false, "text": " style={{\n width: \"80%\",\n paddingLeft: 100,\n paddingRight: 200,\n paddingTop: 30,\n paddingBottom: 30,\n border: \"3px solid lightGray\",\n }}\n" }, { "answer_id": 68187307, "author": "Venryx", "author_id": 2441655, "author_profile": "https://Stackoverflow.com/users/2441655", "pm_score": 0, "selected": false, "text": "export type Size = {width: number, height: number};\nexport enum GetSize_Method {\n /** Includes: content, padding. Excludes: border, margin, scroll-bar (if it has one), \"position:absolute\" descendants. */\n ClientSize = \"ClientSize\",\n /** Includes: content, padding, border, margin, scroll-bar (if it has one). Excludes: \"position:absolute\" descendants. */\n OffsetSize = \"OffsetSize\",\n /** Includes: content, padding, border, margin, scroll-bar (if it has one), \"position:absolute\" descendants. Excludes: none. */\n ScrollSize = \"ScrollSize\",\n /** Same as ScrollSize, except that it's calculated after the element's css transforms are applied. */\n BoundingClientRect = \"BoundingClientRect\",\n /** Lets you specify the exact list of components you want to include in the size calculation. */\n Custom = \"Custom\",\n}\nexport type SizeComp = \"content\" | \"padding\" | \"border\" | \"margin\" | \"scrollBar\" | \"posAbsDescendants\";\n\nexport function GetSize(el: HTMLElement, method = GetSize_Method.ClientSize, custom_sizeComps?: SizeComp[]) {\n let size: Size;\n if (method == GetSize_Method.ClientSize) {\n size = {width: el.clientWidth, height: el.clientHeight};\n } else if (method == GetSize_Method.OffsetSize) {\n size = {width: el.offsetWidth, height: el.offsetHeight};\n } else if (method == GetSize_Method.ScrollSize) {\n size = {width: el.scrollWidth, height: el.scrollHeight};\n } else if (method == GetSize_Method.BoundingClientRect) {\n const rect = el.getBoundingClientRect();\n size = {width: rect.width, height: rect.height};\n } else if (method == GetSize_Method.Custom) {\n const style = window.getComputedStyle(el, null);\n const styleProp = (name: string)=>parseFloat(style.getPropertyValue(name));\n\n const padding = {w: styleProp(\"padding-left\") + styleProp(\"padding-right\"), h: styleProp(\"padding-top\") + styleProp(\"padding-bottom\")};\n const base = {w: el.clientWidth - padding.w, h: el.clientHeight - padding.h};\n const border = {w: styleProp(\"border-left\") + styleProp(\"border-right\"), h: styleProp(\"border-top\") + styleProp(\"border-bottom\")};\n const margin = {w: styleProp(\"margin-left\") + styleProp(\"margin-right\"), h: styleProp(\"margin-top\") + styleProp(\"margin-bottom\")};\n const scrollBar = {w: (el.offsetWidth - el.clientWidth) - border.w - margin.w, h: (el.offsetHeight - el.clientHeight) - border.h - margin.h};\n const posAbsDescendants = {w: el.scrollWidth - el.offsetWidth, h: el.scrollHeight - el.offsetHeight};\n\n const sc = (name: SizeComp, valIfEnabled: number)=>custom_sizeComps.includes(name) ? valIfEnabled : 0;\n size = {\n width: sc(\"content\", base.w) + sc(\"padding\", padding.w) + sc(\"border\", border.w)\n + sc(\"margin\", margin.w) + sc(\"scrollBar\", scrollBar.w) + sc(\"posAbsDescendants\", posAbsDescendants.w),\n height: sc(\"content\", base.h) + sc(\"padding\", padding.h) + sc(\"border\", border.h)\n + sc(\"margin\", margin.h) + sc(\"scrollBar\", scrollBar.h) + sc(\"posAbsDescendants\", posAbsDescendants.h),\n };\n }\n return size;\n}\n const el = document.querySelector(\".my-element\");\nconsole.log(\"Size:\", GetSize(el, \"ClientSize\"));\nconsole.log(\"Size:\", GetSize(el, \"Custom\", [\"content\", \"padding\", \"border\"]));\n" }, { "answer_id": 70852511, "author": "fguillen", "author_id": 316700, "author_profile": "https://Stackoverflow.com/users/316700", "pm_score": 0, "selected": false, "text": "element.clientWidth -\nparseFloat(window.getComputedStyle(element, null).getPropertyValue(\"padding-left\")) -\nparseFloat(window.getComputedStyle(element, null).getPropertyValue(\"padding-right\"))\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/294250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/184350/" ]
294,261
<p>I have class with a member function that takes a default argument.</p> <pre><code>struct Class { void member(int n = 0) {} }; </code></pre> <p>By means of std::tr1::mem_fn I can invoke it:</p> <pre><code>Class object; std::tr1::mem_fn(&amp;Class::member)(object,10); </code></pre> <p>That said, if I want to invoke the <em>callable</em> member on the object with the default argument, what's the correct syntax?</p> <pre><code>std::tr1::mem_fn(&amp;Class::member)(object); // This does not work </code></pre> <p>g++ complains with the following error:</p> <pre><code>test.cc:17: error: no match for call to ‘(std::tr1::_Mem_fn&lt;void (Class::*)(int)&gt;) (Class&amp;)’ /usr/include/c++/4.3/tr1_impl/functional:551: note: candidates are: _Res std::tr1::_Mem_fn&lt;_Res (_Class::*)(_ArgTypes ...)&gt;::operator()(_Class&amp;, _ArgTypes ...) const [with _Res = void, _Class = Class, _ArgTypes = int] /usr/include/c++/4.3/tr1_impl/functional:556: note: _Res std::tr1::_Mem_fn&lt;_Res (_Class::*)(_ArgTypes ...)&gt;::operator()(_Class*, _ArgTypes ...) const [with _Res = void, _Class = Class, _ArgTypes = int] </code></pre> <p>Still, the I have the same problem when Class::member is overloaded by members that takes different arguments...</p>
[ { "answer_id": 294274, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 2, "selected": false, "text": "mem_fn &Class::member void(Class::*)(int) static_cast<void(Class::*)()>(&Class::member) &Class::member std::tr1::mem_fn<void()>(&Class::member)" }, { "answer_id": 294283, "author": "coppro", "author_id": 16855, "author_profile": "https://Stackoverflow.com/users/16855", "pm_score": 4, "selected": true, "text": "&Class::member mem_fn void (Class::*)(int) tr1::bind std::tr1::bind(&Class::member, 0) mem_fn mem_fn mem_fn<void(int)>(&Class::member)" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/294261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19630/" ]
294,270
<p>How would you call the constructor of the following class in these three situations: Global objects, arrays of objects, and objects contained in another class/struct?</p> <p>The class with the constructor (used in all three examples):</p> <pre><code>class Foo { public: Foo(int a) { b = a; } private: int b; }; </code></pre> <p>And here are my attempts at calling this constructor:</p> <h2>Global objects</h2> <pre><code>Foo global_foo(3); // works, but I can't control when the constructor is called. int main() { // ... } </code></pre> <h2>Arrays of objects</h2> <pre><code>int main() { // Array on stack Foo array_of_foos[30](3); // doesn't work // Array on heap Foo *pointer_to_another_array = new Foo(3) [30]; // doesn't work } </code></pre> <p>There I'm attempting to call the constructor for all elements of the arrays, but I'd also like to know how to call it on individual elements.</p> <h2>Objects contained in classes/structs</h2> <pre><code>class Bar { Foo foo(3); // doesn't work }; int main() { Bar bar; } </code></pre>
[ { "answer_id": 294278, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 5, "selected": true, "text": "std::fill std::uninitialized_fill class Bar {\n Foo foo;\n\n Bar() : foo(3) { }\n};\n class Bar {\n static Foo foo;\n};\n\nFoo Bar::foo(3);\n" }, { "answer_id": 294280, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 2, "selected": false, "text": "class Bar{\n Foo foo;\n Bar() : foo(3){}\n};\n" }, { "answer_id": 294308, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 3, "selected": false, "text": "Foo& getGlobalA() // passed parameters can be passed to constructor\n{\n static Foo A;\n return A;\n}\nFoo& getGlobalB()\n{\n static Foo B;\n return B;\n}\netc. \n" }, { "answer_id": 294329, "author": "andy.gurin", "author_id": 22388, "author_profile": "https://Stackoverflow.com/users/22388", "pm_score": 2, "selected": false, "text": "//allocate raw memory for our array\nvoid *rawMemory = operator new[](30 * sizeof(Foo))\n\n// point array_of_foos to this memory so we can use it as an array of Foo\nFoo *array_of_foos = static_cast<Foo *>(rawMemory);\n\n// and now we can create the array of objects(NOT pointers to the objects)\n// using the buffered new operator\nfor (int i = 0; i < 30; i++)\n new(array_of_foos[i])Foo(3);\n" }, { "answer_id": 294359, "author": "Alastair", "author_id": 31038, "author_profile": "https://Stackoverflow.com/users/31038", "pm_score": 0, "selected": false, "text": "class Foo {\npublic:\n Foo(int a) : b(a) {}\n\nprivate:\n int b;\n};\n\nclass Foo_3 : public Foo {\npublic:\n Foo_3() : Foo(3) {}\n};\n\nFoo_3 array_of_foos[30];\n Foo_3 Foo template <int i> \nclass Foo_n : public Foo {\npublic:\n Foo_n() : Foo(i) {}\n};\n\nFoo_n<3> array_of_foos[30];\n Foo" }, { "answer_id": 294494, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 1, "selected": false, "text": "struct foo {\n foo(int a): a(a) { }\n explicit foo(std::string s): s(s) { }\nprivate:\n int a;\n std::string s;\n};\n\n/* global */\nfoo f[] = { foo(\"global\"), foo(\"array\") };\n\nint main() {\n /* local */\n foo f[] = { 10, 20, 30, foo(\"a\"), foo(\"b\") };\n}\n struct bar {\n /* create a vector of 100 foo's, initialized with \"initial\" */\n bar(): f(100, foo(\"initial\")) { }\nprivate:\n std::vector<foo> f;\n};\n placement-new std::vector" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/294270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/813/" ]
294,285
<p>I want to automate several tasks (eg. simulate eclipse style <kbd>ctrl</kbd>-<kbd>shift</kbd>-<kbd>R</kbd> open dialog for other editors). The general pattern is: the user will press some key combination, my program will detect it and potentially pop up a dialog to get user input, and then run a corresponding command, typically by running an executable.</p> <p>My target environment is windows, although cross-platform would be nice. My program would be started once, read a configuration file, and sit in the background till triggered by a key combination or other event.</p> <p>Basically autohotkey.</p> <p>Why not just use autohotkey? I actually have quite a few autohotkey macros, but I'd prefer to use a saner language.</p> <p>My question is: is there a good way to have a background python process detect key combinations?</p> <p>Update: found the answer using pyHook and the win32 extensions:</p> <pre><code>import pyHook import pythoncom def OnKeyboardEvent(event): print event.Ascii hm = pyHook.HookManager() hm.KeyDown = OnKeyboardEvent hm.HookKeyboard() while True: pythoncom.PumpMessages() </code></pre>
[ { "answer_id": 557543, "author": "Parand", "author_id": 13055, "author_profile": "https://Stackoverflow.com/users/13055", "pm_score": 4, "selected": true, "text": "import pyHook\nimport pythoncom\n\ndef OnKeyboardEvent(event):\n print event.Ascii\n\nhm = pyHook.HookManager()\nhm.KeyDown = OnKeyboardEvent\nhm.HookKeyboard()\n\nwhile True:\n pythoncom.PumpMessages()\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/294285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13055/" ]
294,286
<p>I want to use svn command line with beyond compare and get the following output</p> <pre><code>Text Compare Produced: 11/16/2008 11:45:34 AM SourceFile,CompareFile,IOriginal,IAdded,IDeleted,IChanged,UOriginal,UAdded,UDeleted,UChanged "E:\Downloads\eeli\eel\1.c","E:\Downloads\eeli\eel\2.c",967,192,501,270,368,113,205,89 </code></pre> <p>What is the exact commandline?</p>
[ { "answer_id": 294344, "author": "Ned Batchelder", "author_id": 14343, "author_profile": "https://Stackoverflow.com/users/14343", "pm_score": 4, "selected": true, "text": "@REM To configure this as the Subversion diff command, add these lines to\n@REM c:\\Documents and Settings\\username\\Application Data\\Subversion\\config:\n@REM\n@REM [helpers]\n@REM diff-cmd = c:\\bin\\bcsvn.bat\n@REM\n@\"C:\\Progra~1\\Beyond~1\\bcomp.exe\" \"%6\" /title1=%3 \"%7\" /title2=%5\n@exit 0\n" }, { "answer_id": 56224648, "author": "Travis Heeter", "author_id": 1152809, "author_profile": "https://Stackoverflow.com/users/1152809", "pm_score": 2, "selected": false, "text": "... BCompare.exe C:\\Program Files\\Beyond Compare 4\\" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/294286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30546/" ]
294,292
<p>How can I change the master volume level? Using this code</p> <pre><code>[DllImport ("winmm.dll")] public static extern int waveOutSetVolume (IntPtr hwo, uint dwVolume); waveOutSetVolume (IntPtr.Zero, (((uint)uint.MaxValue &amp; 0x0000ffff) | ((uint)uint.MaxValue &lt;&lt; 16))); </code></pre> <p>I can set the wave volume but if the master volume is too low this won't have any effect.</p> <p>Thanks for any help.</p>
[ { "answer_id": 294330, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 3, "selected": false, "text": "BOOL CVolumeDlg::amdInitialize()\n{\n ASSERT(m_hMixer == NULL);\n\n // get the number of mixer devices present in the system\n m_nNumMixers = ::mixerGetNumDevs();\n\n m_hMixer = NULL;\n ::ZeroMemory(&m_mxcaps, sizeof(MIXERCAPS));\n\n m_strDstLineName.Empty();\n m_strVolumeControlName.Empty();\n m_dwMinimum = 0;\n m_dwMaximum = 0;\n m_dwVolumeControlID = 0;\n\n // open the first mixer\n // A \"mapper\" for audio mixer devices does not currently exist.\n if (m_nNumMixers != 0)\n {\n if (::mixerOpen(&m_hMixer,\n 0,\n reinterpret_cast<DWORD>(this->GetSafeHwnd()),\n NULL,\n MIXER_OBJECTF_MIXER | CALLBACK_WINDOW)\n != MMSYSERR_NOERROR)\n {\n return FALSE;\n }\n\n if (::mixerGetDevCaps(reinterpret_cast<UINT>(m_hMixer),\n &m_mxcaps, sizeof(MIXERCAPS))\n != MMSYSERR_NOERROR)\n {\n return FALSE;\n }\n }\n\n return TRUE;\n}\n\nBOOL CVolumeDlg::amdUninitialize()\n{\n BOOL bSucc = TRUE;\n\n if (m_hMixer != NULL)\n {\n bSucc = (::mixerClose(m_hMixer) == MMSYSERR_NOERROR);\n m_hMixer = NULL;\n }\n\n return bSucc;\n}\n\nBOOL CVolumeDlg::amdGetMasterVolumeControl()\n{\n if (m_hMixer == NULL)\n {\n return FALSE;\n }\n\n // get dwLineID\n MIXERLINE mxl;\n mxl.cbStruct = sizeof(MIXERLINE);\n mxl.dwComponentType = MIXERLINE_COMPONENTTYPE_DST_SPEAKERS;\n if (::mixerGetLineInfo(reinterpret_cast<HMIXEROBJ>(m_hMixer),\n &mxl,\n MIXER_OBJECTF_HMIXER |\n MIXER_GETLINEINFOF_COMPONENTTYPE)\n != MMSYSERR_NOERROR)\n {\n return FALSE;\n }\n\n // get dwControlID\n MIXERCONTROL mxc;\n MIXERLINECONTROLS mxlc;\n mxlc.cbStruct = sizeof(MIXERLINECONTROLS);\n mxlc.dwLineID = mxl.dwLineID;\n mxlc.dwControlType = MIXERCONTROL_CONTROLTYPE_VOLUME;\n mxlc.cControls = 1;\n mxlc.cbmxctrl = sizeof(MIXERCONTROL);\n mxlc.pamxctrl = &mxc;\n if (::mixerGetLineControls(reinterpret_cast<HMIXEROBJ>(m_hMixer),\n &mxlc,\n MIXER_OBJECTF_HMIXER |\n MIXER_GETLINECONTROLSF_ONEBYTYPE)\n != MMSYSERR_NOERROR)\n {\n return FALSE;\n }\n\n // store dwControlID\n m_strDstLineName = mxl.szName;\n m_strVolumeControlName = mxc.szName;\n m_dwMinimum = mxc.Bounds.dwMinimum;\n m_dwMaximum = mxc.Bounds.dwMaximum;\n m_dwVolumeControlID = mxc.dwControlID;\n\n return TRUE;\n}\n\nBOOL CVolumeDlg::amdGetMasterVolumeValue(DWORD &dwVal) const\n{\n if (m_hMixer == NULL)\n {\n return FALSE;\n }\n\n MIXERCONTROLDETAILS_UNSIGNED mxcdVolume;\n MIXERCONTROLDETAILS mxcd;\n mxcd.cbStruct = sizeof(MIXERCONTROLDETAILS);\n mxcd.dwControlID = m_dwVolumeControlID;\n mxcd.cChannels = 1;\n mxcd.cMultipleItems = 0;\n mxcd.cbDetails = sizeof(MIXERCONTROLDETAILS_UNSIGNED);\n mxcd.paDetails = &mxcdVolume;\n if (::mixerGetControlDetails(reinterpret_cast<HMIXEROBJ>(m_hMixer),\n &mxcd,\n MIXER_OBJECTF_HMIXER |\n MIXER_GETCONTROLDETAILSF_VALUE)\n != MMSYSERR_NOERROR)\n {\n return FALSE;\n }\n\n dwVal = mxcdVolume.dwValue;\n\n return TRUE;\n}\n\nBOOL CVolumeDlg::amdSetMasterVolumeValue(DWORD dwVal) const\n{\n if (m_hMixer == NULL)\n {\n return FALSE;\n }\n\n MIXERCONTROLDETAILS_UNSIGNED mxcdVolume = { dwVal };\n MIXERCONTROLDETAILS mxcd;\n mxcd.cbStruct = sizeof(MIXERCONTROLDETAILS);\n mxcd.dwControlID = m_dwVolumeControlID;\n mxcd.cChannels = 1;\n mxcd.cMultipleItems = 0;\n mxcd.cbDetails = sizeof(MIXERCONTROLDETAILS_UNSIGNED);\n mxcd.paDetails = &mxcdVolume;\n if (::mixerSetControlDetails(reinterpret_cast<HMIXEROBJ>(m_hMixer),\n &mxcd,\n MIXER_OBJECTF_HMIXER |\n MIXER_SETCONTROLDETAILSF_VALUE)\n != MMSYSERR_NOERROR)\n {\n return FALSE;\n }\n\n return TRUE;\n}\n" }, { "answer_id": 294525, "author": "P Daddy", "author_id": 36388, "author_profile": "https://Stackoverflow.com/users/36388", "pm_score": 6, "selected": true, "text": "const int MAXPNAMELEN = 32;\nconst int MIXER_SHORT_NAME_CHARS = 16;\nconst int MIXER_LONG_NAME_CHARS = 64;\n\n[Flags] enum MIXERLINE_LINEF : uint{\n ACTIVE = 0x00000001,\n DISCONNECTED = 0x00008000,\n SOURCE = 0x80000000\n}\n[Flags] enum MIXER : uint{\n GETLINEINFOF_DESTINATION = 0x00000000,\n GETLINEINFOF_SOURCE = 0x00000001,\n GETLINEINFOF_LINEID = 0x00000002,\n GETLINEINFOF_COMPONENTTYPE = 0x00000003,\n GETLINEINFOF_TARGETTYPE = 0x00000004,\n GETLINEINFOF_QUERYMASK = 0x0000000F,\n\n GETLINECONTROLSF_ALL = 0x00000000,\n GETLINECONTROLSF_ONEBYID = 0x00000001,\n GETLINECONTROLSF_ONEBYTYPE = 0x00000002,\n GETLINECONTROLSF_QUERYMASK = 0x0000000F,\n\n GETCONTROLDETAILSF_VALUE = 0x00000000,\n GETCONTROLDETAILSF_LISTTEXT = 0x00000001,\n GETCONTROLDETAILSF_QUERYMASK = 0x0000000F,\n\n OBJECTF_MIXER = 0x00000000,\n OBJECTF_WAVEOUT = 0x10000000,\n OBJECTF_WAVEIN = 0x20000000,\n OBJECTF_MIDIOUT = 0x30000000,\n OBJECTF_MIDIIN = 0x40000000,\n OBJECTF_AUX = 0x50000000,\n OBJECTF_HANDLE = 0x80000000,\n OBJECTF_HMIXER = OBJECTF_HANDLE | OBJECTF_MIXER,\n OBJECTF_HWAVEOUT = OBJECTF_HANDLE | OBJECTF_WAVEOUT,\n OBJECTF_HWAVEIN = OBJECTF_HANDLE | OBJECTF_WAVEIN,\n OBJECTF_HMIDIOUT = OBJECTF_HANDLE | OBJECTF_MIDIOUT,\n OBJECTF_HMIDIIN = OBJECTF_HANDLE | OBJECTF_MIDIIN\n}\n[Flags] enum MIXERCONTROL_CT : uint{\n CLASS_MASK = 0xF0000000,\n CLASS_CUSTOM = 0x00000000,\n CLASS_METER = 0x10000000,\n CLASS_SWITCH = 0x20000000,\n CLASS_NUMBER = 0x30000000,\n CLASS_SLIDER = 0x40000000,\n CLASS_FADER = 0x50000000,\n CLASS_TIME = 0x60000000,\n CLASS_LIST = 0x70000000,\n\n SUBCLASS_MASK = 0x0F000000,\n\n SC_SWITCH_BOOLEAN = 0x00000000,\n SC_SWITCH_BUTTON = 0x01000000,\n\n SC_METER_POLLED = 0x00000000,\n\n SC_TIME_MICROSECS = 0x00000000,\n SC_TIME_MILLISECS = 0x01000000,\n\n SC_LIST_SINGLE = 0x00000000,\n SC_LIST_MULTIPLE = 0x01000000,\n\n UNITS_MASK = 0x00FF0000,\n UNITS_CUSTOM = 0x00000000,\n UNITS_BOOLEAN = 0x00010000,\n UNITS_SIGNED = 0x00020000,\n UNITS_UNSIGNED = 0x00030000,\n UNITS_DECIBELS = 0x00040000, /* in 10ths */\n UNITS_PERCENT = 0x00050000, /* in 10ths */\n}\n[Flags] enum MIXERCONTROL_CONTROLTYPE : uint{\n CUSTOM = MIXERCONTROL_CT.CLASS_CUSTOM | MIXERCONTROL_CT.UNITS_CUSTOM,\n BOOLEANMETER = MIXERCONTROL_CT.CLASS_METER | MIXERCONTROL_CT.SC_METER_POLLED | MIXERCONTROL_CT.UNITS_BOOLEAN,\n SIGNEDMETER = MIXERCONTROL_CT.CLASS_METER | MIXERCONTROL_CT.SC_METER_POLLED | MIXERCONTROL_CT.UNITS_SIGNED,\n PEAKMETER = SIGNEDMETER + 1,\n UNSIGNEDMETER = MIXERCONTROL_CT.CLASS_METER | MIXERCONTROL_CT.SC_METER_POLLED | MIXERCONTROL_CT.UNITS_UNSIGNED,\n BOOLEAN = MIXERCONTROL_CT.CLASS_SWITCH | MIXERCONTROL_CT.SC_SWITCH_BOOLEAN | MIXERCONTROL_CT.UNITS_BOOLEAN,\n ONOFF = BOOLEAN + 1,\n MUTE = BOOLEAN + 2,\n MONO = BOOLEAN + 3,\n LOUDNESS = BOOLEAN + 4,\n STEREOENH = BOOLEAN + 5,\n BASS_BOOST = BOOLEAN + 0x00002277,\n BUTTON = MIXERCONTROL_CT.CLASS_SWITCH | MIXERCONTROL_CT.SC_SWITCH_BUTTON | MIXERCONTROL_CT.UNITS_BOOLEAN,\n DECIBELS = MIXERCONTROL_CT.CLASS_NUMBER | MIXERCONTROL_CT.UNITS_DECIBELS,\n SIGNED = MIXERCONTROL_CT.CLASS_NUMBER | MIXERCONTROL_CT.UNITS_SIGNED,\n UNSIGNED = MIXERCONTROL_CT.CLASS_NUMBER | MIXERCONTROL_CT.UNITS_UNSIGNED,\n PERCENT = MIXERCONTROL_CT.CLASS_NUMBER | MIXERCONTROL_CT.UNITS_PERCENT,\n SLIDER = MIXERCONTROL_CT.CLASS_SLIDER | MIXERCONTROL_CT.UNITS_SIGNED,\n PAN = SLIDER + 1,\n QSOUNDPAN = SLIDER + 2,\n FADER = MIXERCONTROL_CT.CLASS_FADER | MIXERCONTROL_CT.UNITS_UNSIGNED,\n VOLUME = FADER + 1,\n BASS = FADER + 2,\n TREBLE = FADER + 3,\n EQUALIZER = FADER + 4,\n SINGLESELECT = MIXERCONTROL_CT.CLASS_LIST | MIXERCONTROL_CT.SC_LIST_SINGLE | MIXERCONTROL_CT.UNITS_BOOLEAN,\n MUX = SINGLESELECT + 1,\n MULTIPLESELECT = MIXERCONTROL_CT.CLASS_LIST | MIXERCONTROL_CT.SC_LIST_MULTIPLE | MIXERCONTROL_CT.UNITS_BOOLEAN,\n MIXER = MULTIPLESELECT + 1,\n MICROTIME = MIXERCONTROL_CT.CLASS_TIME | MIXERCONTROL_CT.SC_TIME_MICROSECS | MIXERCONTROL_CT.UNITS_UNSIGNED,\n MILLITIME = MIXERCONTROL_CT.CLASS_TIME | MIXERCONTROL_CT.SC_TIME_MILLISECS | MIXERCONTROL_CT.UNITS_UNSIGNED\n}\n\n[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]\nstruct MIXERLINE{\n [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]\n public struct TargetInfo{\n public uint dwType;\n public uint dwDeviceID;\n public ushort wMid;\n public ushort wPid;\n public uint vDriverVersion;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst=MAXPNAMELEN)]\n public string szPname;\n }\n\n public uint cbStruct;\n public uint dwDestination;\n public uint dwSource;\n public uint dwLineID;\n public MIXERLINE_LINEF fdwLine;\n public uint dwUser;\n public uint dwComponentType;\n public uint cChannels;\n public uint cConnection;\n public uint cControls;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst=MIXER_SHORT_NAME_CHARS)]\n public string szShortName;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst=MIXER_LONG_NAME_CHARS)]\n public string szName;\n public TargetInfo Target;\n}\n[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]\nstruct MIXERCONTROL{\n [StructLayout(LayoutKind.Explicit)]\n public struct BoundsInfo{\n [FieldOffset(0)]\n public int lMinimum;\n [FieldOffset(4)]\n public int lMaximum;\n [FieldOffset(0)]\n public uint dwMinimum;\n [FieldOffset(4)]\n public uint dwMaximum;\n [FieldOffset(8), MarshalAs(UnmanagedType.ByValArray, SizeConst=4)]\n public uint[] dwReserved;\n }\n [StructLayout(LayoutKind.Explicit)]\n public struct MetricsInfo{\n [FieldOffset(0)]\n public uint cSteps;\n [FieldOffset(0)]\n public uint cbCustomData;\n [FieldOffset(4), MarshalAs(UnmanagedType.ByValArray, SizeConst=5)]\n public uint[] dwReserved;\n }\n\n public uint cbStruct;\n public uint dwControlID;\n public MIXERCONTROL_CONTROLTYPE dwControlType;\n public uint fdwControl;\n public uint cMultipleItems;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst=MIXER_SHORT_NAME_CHARS)]\n public string szShortName;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst=MIXER_LONG_NAME_CHARS)]\n public string szName;\n public BoundsInfo Bounds;\n public MetricsInfo Metrics;\n}\n[StructLayout(LayoutKind.Explicit)]\nstruct MIXERLINECONTROLS{\n [FieldOffset(0)]\n public uint cbStruct;\n [FieldOffset(4)]\n public uint dwLineID;\n [FieldOffset(8)]\n public uint dwControlID;\n [FieldOffset(8)] // not a typo! overlaps previous field\n public uint dwControlType;\n [FieldOffset(12)]\n public uint cControls;\n [FieldOffset(16)]\n public uint cbmxctrl;\n [FieldOffset(20)]\n public IntPtr pamxctrl;\n}\n[StructLayout(LayoutKind.Explicit)]\nstruct MIXERCONTROLDETAILS{\n [FieldOffset(0)]\n public uint cbStruct;\n [FieldOffset(4)]\n public uint dwControlID;\n [FieldOffset(8)]\n public uint cChannels;\n [FieldOffset(12)]\n public IntPtr hwndOwner;\n [FieldOffset(12)] // not a typo!\n public uint cMultipleItems;\n [FieldOffset(16)]\n public uint cbDetails;\n [FieldOffset(20)]\n public IntPtr paDetails;\n}\n[StructLayout(LayoutKind.Sequential)]\nstruct VOLUME{\n public int left;\n public int right;\n}\nstruct MixerInfo{\n public uint volumeCtl;\n public uint muteCtl;\n public int minVolume;\n public int maxVolume;\n}\n\n[DllImport(\"WinMM.dll\", CharSet=CharSet.Auto)]\nstatic extern uint mixerGetLineInfo (IntPtr hmxobj, ref MIXERLINE pmxl, MIXER flags);\n\n[DllImport(\"WinMM.dll\", CharSet=CharSet.Auto)]\nstatic extern uint mixerGetLineControls (IntPtr hmxobj, ref MIXERLINECONTROLS pmxlc, MIXER flags);\n\n[DllImport(\"WinMM.dll\", CharSet=CharSet.Auto)]\nstatic extern uint mixerGetControlDetails(IntPtr hmxobj, ref MIXERCONTROLDETAILS pmxcd, MIXER flags);\n\n[DllImport(\"WinMM.dll\", CharSet=CharSet.Auto)]\nstatic extern uint mixerSetControlDetails(IntPtr hmxobj, ref MIXERCONTROLDETAILS pmxcd, MIXER flags);\n\nstatic MixerInfo GetMixerControls(){\n MIXERLINE mxl = new MIXERLINE();\n MIXERLINECONTROLS mlc = new MIXERLINECONTROLS();\n mxl.cbStruct = (uint)Marshal.SizeOf(typeof(MIXERLINE));\n mlc.cbStruct = (uint)Marshal.SizeOf(typeof(MIXERLINECONTROLS));\n\n mixerGetLineInfo(IntPtr.Zero, ref mxl, MIXER.OBJECTF_MIXER | MIXER.GETLINEINFOF_DESTINATION);\n\n mlc.dwLineID = mxl.dwLineID;\n mlc.cControls = mxl.cControls;\n mlc.cbmxctrl = (uint)Marshal.SizeOf(typeof(MIXERCONTROL));\n mlc.pamxctrl = Marshal.AllocHGlobal((int)(mlc.cbmxctrl * mlc.cControls));\n\n mixerGetLineControls(IntPtr.Zero, ref mlc, MIXER.OBJECTF_MIXER | MIXER.GETLINECONTROLSF_ALL);\n\n MixerInfo rtn = new MixerInfo();\n\n for(int i = 0; i < mlc.cControls; i++){\n MIXERCONTROL mxc = (MIXERCONTROL)Marshal.PtrToStructure((IntPtr)((int)mlc.pamxctrl + (int)mlc.cbmxctrl * i), typeof(MIXERCONTROL));\n switch(mxc.dwControlType){\n case MIXERCONTROL_CONTROLTYPE.VOLUME:\n rtn.volumeCtl = mxc.dwControlID;\n rtn.minVolume = mxc.Bounds.lMinimum;\n rtn.maxVolume = mxc.Bounds.lMaximum;\n break;\n case MIXERCONTROL_CONTROLTYPE.MUTE:\n rtn.muteCtl = mxc.dwControlID;\n break;\n }\n }\n\n Marshal.FreeHGlobal(mlc.pamxctrl);\n\n return rtn;\n}\nstatic VOLUME GetVolume(MixerInfo mi){\n MIXERCONTROLDETAILS mcd = new MIXERCONTROLDETAILS();\n mcd.cbStruct = (uint)Marshal.SizeOf(typeof(MIXERCONTROLDETAILS));\n mcd.dwControlID = mi.volumeCtl;\n mcd.cMultipleItems = 0;\n mcd.cChannels = 2;\n mcd.cbDetails = (uint)Marshal.SizeOf(typeof(int));\n mcd.paDetails = Marshal.AllocHGlobal((int)mcd.cbDetails);\n\n mixerGetControlDetails(IntPtr.Zero, ref mcd, MIXER.GETCONTROLDETAILSF_VALUE | MIXER.OBJECTF_MIXER);\n\n VOLUME rtn = (VOLUME)Marshal.PtrToStructure(mcd.paDetails, typeof(VOLUME));\n\n Marshal.FreeHGlobal(mcd.paDetails);\n\n return rtn;\n}\nstatic bool IsMuted(MixerInfo mi){\n MIXERCONTROLDETAILS mcd = new MIXERCONTROLDETAILS();\n mcd.cbStruct = (uint)Marshal.SizeOf(typeof(MIXERCONTROLDETAILS));\n mcd.dwControlID = mi.muteCtl;\n mcd.cMultipleItems = 0;\n mcd.cChannels = 1;\n mcd.cbDetails = 4;\n mcd.paDetails = Marshal.AllocHGlobal((int)mcd.cbDetails);\n\n mixerGetControlDetails(IntPtr.Zero, ref mcd, MIXER.GETCONTROLDETAILSF_VALUE | MIXER.OBJECTF_MIXER);\n\n int rtn = Marshal.ReadInt32(mcd.paDetails);\n\n Marshal.FreeHGlobal(mcd.paDetails);\n\n return rtn != 0;\n}\nstatic void AdjustVolume(MixerInfo mi, int delta){\n VOLUME volume = GetVolume(mi);\n\n if(delta > 0){\n volume.left = Math.Min(mi.maxVolume, volume.left + delta);\n volume.right = Math.Min(mi.maxVolume, volume.right + delta);\n }else{\n volume.left = Math.Max(mi.minVolume, volume.left + delta);\n volume.right = Math.Max(mi.minVolume, volume.right + delta);\n }\n\n SetVolume(mi, volume);\n}\nstatic void SetVolume(MixerInfo mi, VOLUME volume){\n MIXERCONTROLDETAILS mcd = new MIXERCONTROLDETAILS();\n mcd.cbStruct = (uint)Marshal.SizeOf(typeof(MIXERCONTROLDETAILS));\n mcd.dwControlID = mi.volumeCtl;\n mcd.cMultipleItems = 0;\n mcd.cChannels = 2;\n mcd.cbDetails = (uint)Marshal.SizeOf(typeof(int));\n mcd.paDetails = Marshal.AllocHGlobal((int)mcd.cbDetails);\n\n Marshal.StructureToPtr(volume, mcd.paDetails, false);\n\n mixerSetControlDetails(IntPtr.Zero, ref mcd, MIXER.GETCONTROLDETAILSF_VALUE | MIXER.OBJECTF_MIXER);\n\n Marshal.FreeHGlobal(mcd.paDetails);\n}\nstatic void SetMute(MixerInfo mi, bool mute){\n MIXERCONTROLDETAILS mcd = new MIXERCONTROLDETAILS();\n mcd.cbStruct = (uint)Marshal.SizeOf(typeof(MIXERCONTROLDETAILS));\n mcd.dwControlID = mi.muteCtl;\n mcd.cMultipleItems = 0;\n mcd.cChannels = 1;\n mcd.cbDetails = 4;\n mcd.paDetails = Marshal.AllocHGlobal((int)mcd.cbDetails);\n\n Marshal.WriteInt32(mcd.paDetails, mute ? 1 : 0);\n\n mixerSetControlDetails(IntPtr.Zero, ref mcd, MIXER.GETCONTROLDETAILSF_VALUE | MIXER.OBJECTF_MIXER);\n\n Marshal.FreeHGlobal(mcd.paDetails);\n}\n MixerInfo mi = GetMixerControls();\nAdjustVolume(mi, 100); // add 100 to the current volume\n MixerInfo mi = GetMixerControls();\nAdjustVolume(mi, (mi.maxVolume - mi.minVolume) / 10); // increase the volume by 10% of total range\n MixerInfo mi = GetMixerControls();\nSetVolume(mi, mi.maxVolume); // let's get this party crunk'd!\n MixerInfo mi = GetMixerControls();\nSetMute(mi, true); // shhhh!!!!!!\n" }, { "answer_id": 40119029, "author": "Alessandro Muzzi", "author_id": 3395760, "author_profile": "https://Stackoverflow.com/users/3395760", "pm_score": -1, "selected": false, "text": " InputSimulator.SimulateKeyPress(VirtualKeyCode.VOLUME_UP);\n\n InputSimulator.SimulateKeyPress(VirtualKeyCode.VOLUME_DOWN);\n\n InputSimulator.SimulateKeyPress(VirtualKeyCode.VOLUME_MUTE);\n // volume update\n MMDevice defaultDevice = new MMDeviceEnumerator()\n .GetDefaultAudioEndpoint(DataFlow.Render‌​, Role.Multimedia);\n // veloce attesa per l'aggiornamento del volume\n Thread.Sleep(100);\n float level = defaultDevice.AudioEndpointVolume.MasterVolumeLevelScalar; \n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/294292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/894/" ]
294,297
<p>I'm writing a Web application that needs to store JSON data in a small, fixed-size server-side cache via AJAX (think: <a href="http://code.google.com/apis/opensocial/articles/persistence-0.8.html#restrictions-quotas" rel="noreferrer">Opensocial quotas</a>). I do not have control over the server.</p> <p>I need to reduce the size of the stored data to stay within a server-side quota, and was hoping to be able to gzip the stringified JSON in the browser before sending it up to the server.</p> <p>However, I cannot find much in the way of JavaScript implementations of Gzip. Any suggestions for how I can compress the data on the client side before sending it up?</p>
[ { "answer_id": 294421, "author": "Matthew Crumley", "author_id": 2214, "author_profile": "https://Stackoverflow.com/users/2214", "pm_score": 7, "selected": false, "text": "// LZW-compress a string\nfunction lzw_encode(s) {\n var dict = {};\n var data = (s + \"\").split(\"\");\n var out = [];\n var currChar;\n var phrase = data[0];\n var code = 256;\n for (var i=1; i<data.length; i++) {\n currChar=data[i];\n if (dict[phrase + currChar] != null) {\n phrase += currChar;\n }\n else {\n out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));\n dict[phrase + currChar] = code;\n code++;\n phrase=currChar;\n }\n }\n out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));\n for (var i=0; i<out.length; i++) {\n out[i] = String.fromCharCode(out[i]);\n }\n return out.join(\"\");\n}\n\n// Decompress an LZW-encoded string\nfunction lzw_decode(s) {\n var dict = {};\n var data = (s + \"\").split(\"\");\n var currChar = data[0];\n var oldPhrase = currChar;\n var out = [currChar];\n var code = 256;\n var phrase;\n for (var i=1; i<data.length; i++) {\n var currCode = data[i].charCodeAt(0);\n if (currCode < 256) {\n phrase = data[i];\n }\n else {\n phrase = dict[currCode] ? dict[currCode] : (oldPhrase + currChar);\n }\n out.push(phrase);\n currChar = phrase.charAt(0);\n dict[code] = oldPhrase + currChar;\n code++;\n oldPhrase = phrase;\n }\n return out.join(\"\");\n}\n" }, { "answer_id": 5633128, "author": "pcans", "author_id": 599805, "author_profile": "https://Stackoverflow.com/users/599805", "pm_score": 6, "selected": false, "text": "<!doctype html>\n</head>\n<title>Test gzip decompression page</title>\n<script src=\"jsxcompressor.js\"></script>\n</head>\n<body>\n<script>\n document.write(JXG.decompress('<?php \n echo base64_encode(gzencode(\"Try not. Do, or do not. There is no try.\")); \n ?>'));\n</script>\n</html>\n" }, { "answer_id": 22428819, "author": "Vitaly", "author_id": 1031804, "author_profile": "https://Stackoverflow.com/users/1031804", "pm_score": 5, "selected": false, "text": "var inflate = require('pako/lib/inflate').inflate; \nvar text = inflate(zipped, {to: 'string'});\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/294297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5309/" ]
294,299
<p>I created an Ajax website in Visual Studio, added a simple page with a textbox and button, when I click the button once everything works, when I click it twice I get the error</p> <p>Sys.WebForms.PageRequestManagerServerErrorException: An unknown error occurred while processing the request on the server. The status code returned from the server was: 500</p> <p>Here is my page</p> <pre><code>&lt;form id="form1" runat="server"&gt; &lt;asp:ScriptManager ID="ScriptManager1" runat="server" /&gt; &lt;div&gt; &lt;asp:UpdatePanel ID="UpdatePanel1" runat="server"&gt; &lt;ContentTemplate&gt; &lt;asp:TextBox ID="TextBox1" runat="server"&gt;&lt;/asp:TextBox&gt; &lt;asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /&gt; &lt;/ContentTemplate&gt; &lt;/asp:UpdatePanel&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <pre> Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) TextBox1.Text = "aaa" End Sub </pre> <p>Edit ~ I added a second button to the page, outside of the update panel and when I clicked the one inside the update panel and then the one outside of the panel I got the error</p> <p>Cannot open database "ASPState" requested by the login. The login failed. Login failed for user 'server\user'. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. </p> <p>Exception Details: System.Data.SqlClient.SqlException: Cannot open database "ASPState" requested by the login. The login failed. Login failed for user 'server\user'.</p> <p>Why is this?</p> <p>Edit ~ To resolve my issue I did</p> <pre><code>&lt;sessionState mode="StateServer" stateConnectionString="tcpip=localhost:42424" cookieless="false" timeout="20"/&gt; </code></pre>
[ { "answer_id": 294421, "author": "Matthew Crumley", "author_id": 2214, "author_profile": "https://Stackoverflow.com/users/2214", "pm_score": 7, "selected": false, "text": "// LZW-compress a string\nfunction lzw_encode(s) {\n var dict = {};\n var data = (s + \"\").split(\"\");\n var out = [];\n var currChar;\n var phrase = data[0];\n var code = 256;\n for (var i=1; i<data.length; i++) {\n currChar=data[i];\n if (dict[phrase + currChar] != null) {\n phrase += currChar;\n }\n else {\n out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));\n dict[phrase + currChar] = code;\n code++;\n phrase=currChar;\n }\n }\n out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));\n for (var i=0; i<out.length; i++) {\n out[i] = String.fromCharCode(out[i]);\n }\n return out.join(\"\");\n}\n\n// Decompress an LZW-encoded string\nfunction lzw_decode(s) {\n var dict = {};\n var data = (s + \"\").split(\"\");\n var currChar = data[0];\n var oldPhrase = currChar;\n var out = [currChar];\n var code = 256;\n var phrase;\n for (var i=1; i<data.length; i++) {\n var currCode = data[i].charCodeAt(0);\n if (currCode < 256) {\n phrase = data[i];\n }\n else {\n phrase = dict[currCode] ? dict[currCode] : (oldPhrase + currChar);\n }\n out.push(phrase);\n currChar = phrase.charAt(0);\n dict[code] = oldPhrase + currChar;\n code++;\n oldPhrase = phrase;\n }\n return out.join(\"\");\n}\n" }, { "answer_id": 5633128, "author": "pcans", "author_id": 599805, "author_profile": "https://Stackoverflow.com/users/599805", "pm_score": 6, "selected": false, "text": "<!doctype html>\n</head>\n<title>Test gzip decompression page</title>\n<script src=\"jsxcompressor.js\"></script>\n</head>\n<body>\n<script>\n document.write(JXG.decompress('<?php \n echo base64_encode(gzencode(\"Try not. Do, or do not. There is no try.\")); \n ?>'));\n</script>\n</html>\n" }, { "answer_id": 22428819, "author": "Vitaly", "author_id": 1031804, "author_profile": "https://Stackoverflow.com/users/1031804", "pm_score": 5, "selected": false, "text": "var inflate = require('pako/lib/inflate').inflate; \nvar text = inflate(zipped, {to: 'string'});\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/294299", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23667/" ]
294,313
<p>Python provides the "*" operator for unpacking a list of tuples and giving them to a function as arguments, like so:</p> <pre><code>args = [3, 6] range(*args) # call with arguments unpacked from a list </code></pre> <p>This is equivalent to:</p> <pre><code>range(3, 6) </code></pre> <p>Does anyone know if there is a way to achieve this in PHP? Some googling for variations of "PHP Unpack" hasn't immediately turned up anything.. perhaps it's called something different in PHP?</p>
[ { "answer_id": 294325, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 5, "selected": true, "text": "call_user_func_array() call_user_func_array(\"range\", $args);" }, { "answer_id": 294335, "author": "andy.gurin", "author_id": 22388, "author_profile": "https://Stackoverflow.com/users/22388", "pm_score": 2, "selected": false, "text": "call_user_func_array(array(CLASS, METHOD), array(arg1, arg2, ....))\n" }, { "answer_id": 23164267, "author": "Salvador Dali", "author_id": 1090562, "author_profile": "https://Stackoverflow.com/users/1090562", "pm_score": 5, "selected": false, "text": "php5.6 ... call_user_func_array() function add($a, $b){\n return $a + $b;\n}\n $list = [4, 6]; ... echo add(...$list);\n" }, { "answer_id": 32401548, "author": "Oleg Belousov", "author_id": 1922258, "author_profile": "https://Stackoverflow.com/users/1922258", "pm_score": 3, "selected": false, "text": "unpacking list($min, $max) = [3, 6];\nrange($min, $max);\n PHP argument unpacking" }, { "answer_id": 58286746, "author": "lov3catch", "author_id": 2003137, "author_profile": "https://Stackoverflow.com/users/2003137", "pm_score": 2, "selected": false, "text": "<?php\n\nfunction add(int ...$arr) { // typehint ready\n return array_sum($arr);\n}\n\nvar_dump(add(1, 2, 3, ...[1, 2, 3])); // int(12)\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/294313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2327/" ]
294,342
<p>I have a TDbGrid, and I can easily tell how many columns are in it at runtime with the FieldCount property, but there doesn't seem to be a corresponding RowCount property to display how many records are being displayed. How can I find this out?</p>
[ { "answer_id": 294345, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 4, "selected": true, "text": "DBGrid1.DataSource.DataSet.RecordCount\n" }, { "answer_id": 294372, "author": "Steve", "author_id": 22712, "author_profile": "https://Stackoverflow.com/users/22712", "pm_score": 4, "selected": false, "text": "RowCount VisibleRowCount TCustomGrid TDBGrid type\n TDummyGrid = class(TDBGrid);\n\n RowCount := TDummyGrid(MyDBGrid).RowCount;\n VisibleRowCount := TDummyGrid(MyDBGrid).VisibleRowCount;\n" }, { "answer_id": 3155983, "author": "hassen", "author_id": 380857, "author_profile": "https://Stackoverflow.com/users/380857", "pm_score": 1, "selected": false, "text": "TDbGrid.ApproxCount\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/294342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32914/" ]
294,343
<p>I am looking for a simple C++ library for tokenizing and parsing RTF (Rich Text Format) files. I am planning to edit them with Qt's QTextEdit.</p> <p>More the Formatting preserved the better -- but actually I am planning to use Bold and Italics only.</p> <p>In perl I would use <a href="http://search.cpan.org/%7Esargie/RTF-Tokenizer-1.10/lib/RTF/Tokenizer.pm" rel="nofollow noreferrer">RTF::Tokenizer</a>.</p> <p>It would be nice if the module had some sort of interface for writing also, but I am able to brute force that with a template and some regular expressions.</p>
[ { "answer_id": 294728, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 2, "selected": false, "text": "#koffice irc.freenode.org kword" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/294343", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38075/" ]
294,349
<p>I am trying to create a sidebar for a site that will allow a user to select an item from a drop down menu and show an RSS Feed. The feed will change depending on which item is selected from the list. I am not sure how to acomplish this, but my first thought was to use z-index and show/hide layers. I have one layer and the menu set up, but it will not allow me to change the feed displayed when a different menu item is selected. Does anyone know how I can acomplish this?</p> <p>I have a live preview up of what I have gotten done so far. It's located on the site, <a href="http://www.chud.com/articles/templates/chud/new_sidebarhome.php" rel="nofollow noreferrer">CHUD</a>,</p>
[ { "answer_id": 294427, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 1, "selected": false, "text": "// load first feed on document load\n$(document).ready(\n function() {\n load_feed( $('select#feedSelect')[0], 'feedDiv' ) ); // pick first\n }\n);\n\nfunction load_feed( ctl, contentArea ) // load based on select\n{\n var content = $('#' + contentArea )[0]; //pick first\n\n content.html( 'Loading feed, please wait...' );\n\n var feedUrl = ctl.options[ctl.selectedIndex].value;\n\n $.getFeed( { url: feedUrl,\n function(feed) {\n content.html( '' );\n content.append( '<h1>' + feed.title + '</h1>' );\n feed.items.each( \n function(i,item) {\n content.append( '<h2><a href=\"'\n + item.link\n + '\">' \n + feed.title\n + '</a></h2>' );\n content.append( '<p>' + feed.description + '</p>' );\n }\n );\n }\n });\n }\n <div>\n <select id=feedSelect onchange=\"load_feed(this,'feedDiv');\" >\n <option value='url-to-first-feed' text='First Feed' selected=true />\n <option value='url-to-second-feed' text='Second Feed' />\n ...\n </select>\n <div id='feedDiv'>\n </div>\n</div>\n" }, { "answer_id": 294521, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 1, "selected": true, "text": "<ul> <select id=\"showRss\">\n <option name=\"feed1\">Feed 1</option>\n <option name=\"feed2\">Feed 2</option>\n</select>\n\n<div id=\"rssContainer\">\n <ul id=\"feed1\">\n <li>feed item 1</li>\n <li>...</li>\n </ul>\n <ul id=\"feed2\">\n <li>feed item 2</li>\n <li>...</li>\n </ul>\n <!-- etc... -->\n</div>\n var rss = document.getElementById('rssContainer'); // main container\nvar nodes = rss.getElementsByTagName('ul'); // collection of ul nodes\nvar select = document.getElementById('showRss'); // your select box\n\nfunction hideAll() { // hide all ul's\n for (i = 0; i < nodes.length; ++i) {\n nodes[i].style.display = 'none';\n }\n}\n\nselect.onchange = function() { // use the 'name' of each\n hideAll(); // option as the id of the ul\n var e = this[this.selectedIndex].getAttribute('name');\n var show = document.getElementById(e); // to show when selected\n show.style.display = 'block';\n}\n\nhideAll();\n $('#showRss').change(function() {\n $('#rssContainer ul').hide('slow'); // added a bit of animation\n var e = '#' + $(':selected', $(this)).attr('name');\n $(e).show('slow'); // while we change the feed\n});\n\n$('#rssContainer ul').hide();\n onchange" }, { "answer_id": 294526, "author": "Vordreller", "author_id": 11795, "author_profile": "https://Stackoverflow.com/users/11795", "pm_score": 1, "selected": false, "text": "<a>" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/294349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5509/" ]