id
int64
4
73.8M
title
stringlengths
10
150
body
stringlengths
17
50.8k
accepted_answer_id
int64
7
73.8M
answer_count
int64
1
182
comment_count
int64
0
89
community_owned_date
stringlengths
23
27
creation_date
stringlengths
23
27
favorite_count
int64
0
11.6k
last_activity_date
stringlengths
23
27
last_edit_date
stringlengths
23
27
last_editor_display_name
stringlengths
2
29
last_editor_user_id
int64
-1
20M
owner_display_name
stringlengths
1
29
owner_user_id
int64
1
20M
parent_id
null
post_type_id
int64
1
1
score
int64
-146
26.6k
tags
stringlengths
1
125
view_count
int64
122
11.6M
answer_body
stringlengths
19
51k
29,578,965
How do I populate two sections in a tableview with two different arrays using swift?
<p>I have two arrays Data1 and Data2 and I want to populate the data within each of these (they contain strings) into a tableview in two different sections.</p> <p>The first section should have a heading "Some Data 1" and the second section should be titled "KickAss".</p> <p>I have both sections populating with data from the first array (but with no headings either).</p> <p>Here is my code so far:</p> <pre><code>override func numberOfSectionsInTableView(tableView: UITableView) -&gt; Int { return 2 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int { var rowCount = 0 if section == 0 { rowCount = Data1.count } if section == 1 { rowCount = Data2.count } return rowCount } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -&gt; UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell let ip = indexPath cell.textLabel?.text = Data1[ip.row] as String return cell } </code></pre> <p>in the cellForRowAtIndexPath method, is it possible for me to identify the section somehow like I did in the numberOfRowsInSection method?</p> <p>Also, how do I give titles to each section?</p>
29,579,027
5
1
null
2015-04-11 14:24:16.457 UTC
25
2020-03-09 10:45:41.07 UTC
2019-12-07 01:31:26.37 UTC
null
1,265,393
null
4,374,672
null
1
38
arrays|uitableview|swift|sections
91,641
<p><strong>TableView Cells</strong></p> <p>You could use a multidimensional array. For example:</p> <pre><code>let data = [["0,0", "0,1", "0,2"], ["1,0", "1,1", "1,2"]] </code></pre> <p>For the number of sections use:</p> <pre><code>override func numberOfSectionsInTableView(tableView: UITableView) -&gt; Int { return data.count } </code></pre> <p>Then, to specify the number of rows in each section use:</p> <pre><code>override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int { return data[section].count } </code></pre> <p>Finally, you need to setup your cells:</p> <pre><code>override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -&gt; UITableViewCell { let cellText = data[indexPath.section][indexPath.row] // Now do whatever you were going to do with the title. } </code></pre> <p><strong>TableView Headers</strong></p> <p>You could again use an array, but with just one dimension this time:</p> <pre><code>let headerTitles = ["Some Data 1", "KickAss"] </code></pre> <p>Now to set the titles for the sections:</p> <pre><code>override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -&gt; String? { if section &lt; headerTitles.count { return headerTitles[section] } return nil } </code></pre> <p>The code above checks to see there's a title for that section and returns it, otherwise <code>nil</code> is returned. There won't be a title if the number of titles in <code>headerTitles</code> is smaller than the number of arrays in <code>data</code>.</p> <p><strong>The Result</strong></p> <p><img src="https://i.stack.imgur.com/XHYtS.png" alt="enter image description here"></p>
32,496,864
What is the monomorphism restriction?
<p>I'm puzzled by how the Haskell compiler sometimes infers types that are less polymorphic than what I'd expect, for example when using point-free definitions.</p> <p>It seems like the issue is the &quot;monomorphism restriction&quot;, which is on by default on older versions of the compiler.</p> <p>Consider the following Haskell program:</p> <pre><code>{-# LANGUAGE MonomorphismRestriction #-} import Data.List(sortBy) plus = (+) plus' x = (+ x) sort = sortBy compare main = do print $ plus' 1.0 2.0 print $ plus 1.0 2.0 print $ sort [3, 1, 2] </code></pre> <p>If I compile this with <code>ghc</code> I obtain no errors and the output of the executable is:</p> <pre><code>3.0 3.0 [1,2,3] </code></pre> <p>If I change the <code>main</code> body to:</p> <pre><code>main = do print $ plus' 1.0 2.0 print $ plus (1 :: Int) 2 print $ sort [3, 1, 2] </code></pre> <p>I get no compile time errors and the output becomes:</p> <pre><code>3.0 3 [1,2,3] </code></pre> <p>as expected. However if I try to change it to:</p> <pre><code>main = do print $ plus' 1.0 2.0 print $ plus (1 :: Int) 2 print $ plus 1.0 2.0 print $ sort [3, 1, 2] </code></pre> <p>I get a type error:</p> <pre class="lang-none prettyprint-override"><code>test.hs:13:16: No instance for (Fractional Int) arising from the literal ‘1.0’ In the first argument of ‘plus’, namely ‘1.0’ In the second argument of ‘($)’, namely ‘plus 1.0 2.0’ In a stmt of a 'do' block: print $ plus 1.0 2.0 </code></pre> <p>The same happens when trying to call <code>sort</code> twice with different types:</p> <pre><code>main = do print $ plus' 1.0 2.0 print $ plus 1.0 2.0 print $ sort [3, 1, 2] print $ sort &quot;cba&quot; </code></pre> <p>produces the following error:</p> <pre class="lang-none prettyprint-override"><code>test.hs:14:17: No instance for (Num Char) arising from the literal ‘3’ In the expression: 3 In the first argument of ‘sort’, namely ‘[3, 1, 2]’ In the second argument of ‘($)’, namely ‘sort [3, 1, 2]’ </code></pre> <ul> <li>Why does <code>ghc</code> suddenly think that <code>plus</code> isn't polymorphic and requires an <code>Int</code> argument? The only reference to <code>Int</code> is in <em>an application</em> of <code>plus</code>, how can that matter when the definition is clearly polymorphic?</li> <li>Why does <code>ghc</code> suddenly think that <code>sort</code> requires a <code>Num Char</code> instance?</li> </ul> <p>Moreover if I try to place the function definitions into their own module, as in:</p> <pre><code>{-# LANGUAGE MonomorphismRestriction #-} module TestMono where import Data.List(sortBy) plus = (+) plus' x = (+ x) sort = sortBy compare </code></pre> <p>I get the following error when compiling:</p> <pre class="lang-none prettyprint-override"><code>TestMono.hs:10:15: No instance for (Ord a0) arising from a use of ‘compare’ The type variable ‘a0’ is ambiguous Relevant bindings include sort :: [a0] -&gt; [a0] (bound at TestMono.hs:10:1) Note: there are several potential instances: instance Integral a =&gt; Ord (GHC.Real.Ratio a) -- Defined in ‘GHC.Real’ instance Ord () -- Defined in ‘GHC.Classes’ instance (Ord a, Ord b) =&gt; Ord (a, b) -- Defined in ‘GHC.Classes’ ...plus 23 others In the first argument of ‘sortBy’, namely ‘compare’ In the expression: sortBy compare In an equation for ‘sort’: sort = sortBy compare </code></pre> <ul> <li>Why isn't <code>ghc</code> able to use the polymorphic type <code>Ord a =&gt; [a] -&gt; [a]</code> for <code>sort</code>?</li> <li>And why does <code>ghc</code> treat <code>plus</code> and <code>plus'</code> differently? <code>plus</code> should have the polymorphic type <code>Num a =&gt; a -&gt; a -&gt; a</code> and I don't really see how this is different from the type of <code>sort</code> and yet only <code>sort</code> raises an error.</li> </ul> <p>Last thing: if I comment the definition of <code>sort</code> the file compiles. However if I try to load it into <code>ghci</code> and check the types I get:</p> <pre class="lang-none prettyprint-override"><code>*TestMono&gt; :t plus plus :: Integer -&gt; Integer -&gt; Integer *TestMono&gt; :t plus' plus' :: Num a =&gt; a -&gt; a -&gt; a </code></pre> <p>Why isn't the type for <code>plus</code> polymorphic?</p> <hr /> <sup> This is the canonical question about monomorphism restriction in Haskell as discussed in [the meta question](https://meta.stackoverflow.com/questions/294053/can-we-provide-a-canonical-questionanswer-for-haskells-monomorphism-restrictio). </sup>
32,496,865
1
3
null
2015-09-10 08:31:55.323 UTC
38
2022-05-14 07:20:38.25 UTC
2022-05-14 07:20:38.25 UTC
null
7,941,251
null
510,937
null
1
85
haskell|types|polymorphism|type-inference|monomorphism-restriction
7,305
<h1>What is the monomorphism restriction?</h1> <p>The <a href="https://wiki.haskell.org/Monomorphism_restriction" rel="nofollow noreferrer">monomorphism restriction</a> as stated by the Haskell wiki is:</p> <blockquote> <p>a counter-intuitive rule in Haskell type inference. If you forget to provide a type signature, sometimes this rule will fill the free type variables with specific types using &quot;type defaulting&quot; rules.</p> </blockquote> <p>What this means is that, <em>in some circumstances</em>, if your type is ambiguous (i.e. polymorphic) the compiler will choose to <em>instantiate</em> that type to something not ambiguous.</p> <h1>How do I fix it?</h1> <p>First of all you can always explicitly provide a type signature and this will avoid the triggering of the restriction:</p> <pre><code>plus :: Num a =&gt; a -&gt; a -&gt; a plus = (+) -- Okay! -- Runs as: Prelude&gt; plus 1.0 1 2.0 </code></pre> <p>Note that only normal type signatures on variables count for this purpose, not expression type signatures. For example, writing this would still result in the restriction being triggered:</p> <pre><code>plus = (+) :: Num a =&gt; a -&gt; a -&gt; a </code></pre> <p>Alternatively, if you are defining a function, you can <em>avoid</em> <a href="https://wiki.haskell.org/Pointfree" rel="nofollow noreferrer">point-free style</a>, and for example write:</p> <pre><code>plus x y = x + y </code></pre> <h2>Turning it off</h2> <p>It is possible to simply turn off the restriction so that you don't have to do anything to your code to fix it. The behaviour is controlled by two extensions: <code>MonomorphismRestriction</code> will enable it (which is the default) while <code>NoMonomorphismRestriction</code> will disable it.</p> <p>You can put the following line at the very top of your file:</p> <pre><code>{-# LANGUAGE NoMonomorphismRestriction #-} </code></pre> <p>If you are using GHCi you can enable the extension using the <code>:set</code> command:</p> <pre><code>Prelude&gt; :set -XNoMonomorphismRestriction </code></pre> <p>You can also tell <code>ghc</code> to enable the extension from the command line:</p> <pre><code>ghc ... -XNoMonomorphismRestriction </code></pre> <p><strong>Note:</strong> You should really prefer the first option over choosing extension via command-line options.</p> <p>Refer to <a href="https://downloads.haskell.org/%7Eghc/latest/docs/html/users_guide/other-type-extensions.html#monomorphism" rel="nofollow noreferrer">GHC's page</a> for an explanation of this and other extensions.</p> <h1>A complete explanation</h1> <p>I'll try to summarize below everything you need to know to understand what the monomorphism restriction is, why it was introduced and how it behaves.</p> <h3>An example</h3> <p>Take the following trivial definition:</p> <pre><code>plus = (+) </code></pre> <p>you'd think to be able to replace every occurrence of <code>+</code> with <code>plus</code>. In particular since <code>(+) :: Num a =&gt; a -&gt; a -&gt; a</code> you'd expect to also have <code>plus :: Num a =&gt; a -&gt; a -&gt; a</code>.</p> <p>Unfortunately this is not the case. For example if we try the following in GHCi:</p> <pre><code>Prelude&gt; let plus = (+) Prelude&gt; plus 1.0 1 </code></pre> <p>We get the following output:</p> <pre class="lang-none prettyprint-override"><code>&lt;interactive&gt;:4:6: No instance for (Fractional Integer) arising from the literal ‘1.0’ In the first argument of ‘plus’, namely ‘1.0’ In the expression: plus 1.0 1 In an equation for ‘it’: it = plus 1.0 1 </code></pre> <p><sup>You may need to <code>:set -XMonomorphismRestriction</code> in newer GHCi versions.</sup></p> <p>And in fact we can see that the type of <code>plus</code> is not what we would expect:</p> <pre><code>Prelude&gt; :t plus plus :: Integer -&gt; Integer -&gt; Integer </code></pre> <p>What happened is that the compiler saw that <code>plus</code> had type <code>Num a =&gt; a -&gt; a -&gt; a</code>, a polymorphic type. Moreover it happens that the above definition falls under the rules that I'll explain later and so he decided to make the type monomorphic by <em>defaulting</em> the type variable <code>a</code>. The default is <code>Integer</code> as we can see.</p> <p>Note that if you try to <em>compile</em> the above code using <code>ghc</code> you won't get any errors. This is due to how <code>ghci</code> handles (and <em>must</em> handle) the interactive definitions. Basically every statement entered in <code>ghci</code> must be <em>completely</em> type checked before the following is considered; in other words it's as if every statement was in a separate <em>module</em>. Later I'll explain why this matter.</p> <h3>Some other example</h3> <p>Consider the following definitions:</p> <pre><code>f1 x = show x f2 = \x -&gt; show x f3 :: (Show a) =&gt; a -&gt; String f3 = \x -&gt; show x f4 = show f5 :: (Show a) =&gt; a -&gt; String f5 = show </code></pre> <p>We'd expect all these functions to behave in the same way and have the same type, i.e. the type of <code>show</code>: <code>Show a =&gt; a -&gt; String</code>.</p> <p>Yet when compiling the above definitions we obtain the following errors:</p> <pre class="lang-none prettyprint-override"><code>test.hs:3:12: No instance for (Show a1) arising from a use of ‘show’ The type variable ‘a1’ is ambiguous Relevant bindings include x :: a1 (bound at blah.hs:3:7) f2 :: a1 -&gt; String (bound at blah.hs:3:1) Note: there are several potential instances: instance Show Double -- Defined in ‘GHC.Float’ instance Show Float -- Defined in ‘GHC.Float’ instance (Integral a, Show a) =&gt; Show (GHC.Real.Ratio a) -- Defined in ‘GHC.Real’ ...plus 24 others In the expression: show x In the expression: \ x -&gt; show x In an equation for ‘f2’: f2 = \ x -&gt; show x test.hs:8:6: No instance for (Show a0) arising from a use of ‘show’ The type variable ‘a0’ is ambiguous Relevant bindings include f4 :: a0 -&gt; String (bound at blah.hs:8:1) Note: there are several potential instances: instance Show Double -- Defined in ‘GHC.Float’ instance Show Float -- Defined in ‘GHC.Float’ instance (Integral a, Show a) =&gt; Show (GHC.Real.Ratio a) -- Defined in ‘GHC.Real’ ...plus 24 others In the expression: show In an equation for ‘f4’: f4 = show </code></pre> <p>So <code>f2</code> and <code>f4</code> don't compile. Moreover when trying to define these function in GHCi we get <em>no errors</em>, but the type for <code>f2</code> and <code>f4</code> is <code>() -&gt; String</code>!</p> <p>Monomorphism restriction is what makes <code>f2</code> and <code>f4</code> require a monomorphic type, and the different behaviour bewteen <code>ghc</code> and <code>ghci</code> is due to different <em>defaulting rules</em>.</p> <h1>When does it happen?</h1> <p>In Haskell, as defined by the <a href="https://www.haskell.org/onlinereport/haskell2010/" rel="nofollow noreferrer">report</a>, there are <em>two</em> distinct type of <a href="https://www.haskell.org/onlinereport/haskell2010/haskellch4.html#x10-830004.4.3" rel="nofollow noreferrer"><em>bindings</em></a>. Function bindings and pattern bindings. A function binding is nothing else than a definition of a function:</p> <pre><code>f x = x + 1 </code></pre> <p>Note that their syntax is:</p> <pre class="lang-none prettyprint-override"><code>&lt;identifier&gt; arg1 arg2 ... argn = expr </code></pre> <p><sup>Modulo guards and <code>where</code> declarations. But they don't really matter.</sup></p> <p>where there must be <em>at least one argument</em>.</p> <p>A pattern binding is a declaration of the form:</p> <pre><code>&lt;pattern&gt; = expr </code></pre> <p><sup>Again, modulo guards.</sup></p> <p>Note that <em>variables are patterns</em>, so the binding:</p> <pre><code>plus = (+) </code></pre> <p>is a <em>pattern</em> binding. It's binding the pattern <code>plus</code> (a variable) to the expression <code>(+)</code>.</p> <p>When a pattern binding consists of only a variable name it's called a <em>simple</em> pattern binding.</p> <p><strong>The monomorphism restriction applies to simple pattern bindings!</strong></p> <p>Well, formally we should say that:</p> <blockquote> <p><em>A declaration group</em> is a minimal set of mutually dependent bindings.</p> </blockquote> <p><sup>Section 4.5.1 of the <a href="https://www.haskell.org/onlinereport/haskell2010/" rel="nofollow noreferrer">report</a>.</sup></p> <p>And then (Section 4.5.5 of the <a href="https://www.haskell.org/onlinereport/haskell2010/" rel="nofollow noreferrer">report</a>):</p> <blockquote> <p>a given declaration group is <em>unrestricted</em> if and only if:</p> <ol> <li><p>every variable in the group is bound by a function binding (e.g. <code>f x = x</code>) or a simple pattern binding (e.g. <code>plus = (+)</code>; Section 4.4.3.2 ), and</p> </li> <li><p>an explicit type signature is given for every variable in the group that is bound by simple pattern binding. (e.g. <code>plus :: Num a =&gt; a -&gt; a -&gt; a; plus = (+)</code>).</p> </li> </ol> </blockquote> <p><sup>Examples added by me.</sup></p> <p>So a <em>restricted</em> declaration group is a group where, either there are <em>non-simple</em> pattern bindings (e.g. <code>(x:xs) = f something</code> or <code>(f, g) = ((+), (-))</code>) or there is some simple pattern binding without a type signature (as in <code>plus = (+)</code>).</p> <p><em>The monomorphism restriction affects <strong>restricted</strong> declaration groups.</em></p> <p>Most of the time you don't define mutual recursive functions and hence a declaration group becomes just <em>a</em> binding.</p> <h1>What does it do?</h1> <p>The monomorphism restriction is described by two rules in Section 4.5.5 of the <a href="https://www.haskell.org/onlinereport/haskell2010/" rel="nofollow noreferrer">report</a>.</p> <h2>First rule</h2> <blockquote> <p>The usual Hindley-Milner restriction on polymorphism is that only type variables that do not occur free in the environment may be generalized. In addition, <strong>the constrained type variables of a restricted declaration group may not be generalized in the generalization step for that group.</strong> (Recall that a type variable is constrained if it must belong to some type class; see Section 4.5.2 .)</p> </blockquote> <p>The highlighted part is what the monomorphism restriction introduces. It says that <em>if</em> the type is polymorphic (i.e. it contain some type variable) <em>and</em> that type variable is constrained (i.e. it has a class constraint on it: e.g. the type <code>Num a =&gt; a -&gt; a -&gt; a</code> is polymorphic because it contains <code>a</code> and also contrained because the <code>a</code> has the constraint <code>Num</code> over it.) <em>then</em> it cannot be generalized.</p> <p>In simple words <em>not generalizing</em> means that the <strong>uses</strong> of the function <code>plus</code> may change its type.</p> <p>If you had the definitions:</p> <pre><code>plus = (+) x :: Integer x = plus 1 2 y :: Double y = plus 1.0 2 </code></pre> <p>then you'd get a type error. Because when the compiler sees that <code>plus</code> is called over an <code>Integer</code> in the declaration of <code>x</code> it will unify the type variable <code>a</code> with <code>Integer</code> and hence the type of <code>plus</code> becomes:</p> <pre><code>Integer -&gt; Integer -&gt; Integer </code></pre> <p>but then, when it will type check the definition of <code>y</code>, it will see that <code>plus</code> is applied to a <code>Double</code> argument, and the types don't match.</p> <p>Note that you can still use <code>plus</code> without getting an error:</p> <pre><code>plus = (+) x = plus 1.0 2 </code></pre> <p>In this case the type of <code>plus</code> is first inferred to be <code>Num a =&gt; a -&gt; a -&gt; a</code> but then its use in the definition of <code>x</code>, where <code>1.0</code> requires a <code>Fractional</code> constraint, will change it to <code>Fractional a =&gt; a -&gt; a -&gt; a</code>.</p> <h3>Rationale</h3> <p>The report says:</p> <blockquote> <p>Rule 1 is required for two reasons, both of which are fairly subtle.</p> <ul> <li><p>Rule 1 prevents computations from being unexpectedly repeated. For example, <code>genericLength</code> is a standard function (in library <code>Data.List</code>) whose type is given by</p> <pre><code> genericLength :: Num a =&gt; [b] -&gt; a </code></pre> <p>Now consider the following expression:</p> <pre><code> let len = genericLength xs in (len, len) </code></pre> <p>It looks as if <code>len</code> should be computed only once, but <strong>without Rule 1 it might be computed twice, once at each of two different overloadings.</strong> If the programmer does actually wish the computation to be repeated, an explicit type signature may be added:</p> <pre><code> let len :: Num a =&gt; a len = genericLength xs in (len, len) </code></pre> </li> </ul> </blockquote> <p>For this point the example from the <a href="https://wiki.haskell.org/Monomorphism_restriction" rel="nofollow noreferrer">wiki</a> is, I believe, clearer. Consider the function:</p> <pre><code>f xs = (len, len) where len = genericLength xs </code></pre> <p>If <code>len</code> was polymorphic the type of <code>f</code> would be:</p> <pre><code>f :: Num a, Num b =&gt; [c] -&gt; (a, b) </code></pre> <p>So the two elements of the tuple <code>(len, len)</code> could actually be <em>different</em> values! But this means that the computation done by <code>genericLength</code> <em>must</em> be repeated to obtain the two different values.</p> <p>The rationale here is: the code contains <em>one</em> function call, but not introducing this rule could produce <em>two</em> hidden function calls, which is counter intuitive.</p> <p>With the monomorphism restriction the type of <code>f</code> becomes:</p> <pre><code>f :: Num a =&gt; [b] -&gt; (a, a) </code></pre> <p>In this way there is no need to perform the computation multiple times.</p> <blockquote> <ul> <li><p>Rule 1 prevents ambiguity. For example, consider the declaration group</p> <pre><code> [(n,s)] = reads t </code></pre> <p>Recall that <code>reads</code> is a standard function whose type is given by the signature</p> <pre><code> reads :: (Read a) =&gt; String -&gt; [(a,String)] </code></pre> <p>Without Rule 1, <code>n</code> would be assigned the type <code>∀ a. Read a ⇒ a</code> and <code>s</code> the type <code>∀ a. Read a ⇒ String</code>. The latter is an invalid type, because it is inherently ambiguous. It is not possible to determine at what overloading to use <code>s</code>, nor can this be solved by adding a type signature for <code>s</code>. Hence, when non-simple pattern bindings are used (Section 4.4.3.2 ), the types inferred are always monomorphic in their constrained type variables, irrespective of whether a type signature is provided. In this case, both <code>n</code> and <code>s</code> are monomorphic in <code>a</code>.</p> </li> </ul> </blockquote> <p>Well, I believe this example is self-explanatory. There are situations when not applying the rule results in type ambiguity.</p> <p>If you disable the extension as suggest above you <em>will</em> get a type error when trying to compile the above declaration. However this isn't really a problem: you already know that when using <code>read</code> you have to somehow tell the compiler which type it should try to parse...</p> <h2>Second rule</h2> <blockquote> <ol start="2"> <li>Any monomorphic type variables that remain when type inference for an entire module is complete, are considered ambiguous, and are resolved to particular types using the defaulting rules (Section 4.3.4 ).</li> </ol> </blockquote> <p>This means that. If you have your usual definition:</p> <pre><code>plus = (+) </code></pre> <p>This will have a type <code>Num a =&gt; a -&gt; a -&gt; a</code> where <code>a</code> is a <em>monomorphic</em> type variable due to rule 1 described above. Once the whole module is inferred the compiler will simply choose a type that will replace that <code>a</code> according to the defaulting rules.</p> <p>The final result is: <code>plus :: Integer -&gt; Integer -&gt; Integer</code>.</p> <p>Note that this is done <em>after</em> the whole module is inferred.</p> <p>This means that if you have the following declarations:</p> <pre><code>plus = (+) x = plus 1.0 2.0 </code></pre> <p>inside a module, <em>before</em> type defaulting the type of <code>plus</code> will be: <code>Fractional a =&gt; a -&gt; a -&gt; a</code> (see rule 1 for why this happens). At this point, following the defaulting rules, <code>a</code> will be replaced by <code>Double</code> and so we will have <code>plus :: Double -&gt; Double -&gt; Double</code> and <code>x :: Double</code>.</p> <h1>Defaulting</h1> <p>As stated before there exist some <em>defaulting</em> rules, described in <a href="https://www.haskell.org/onlinereport/haskell2010/haskellch4.html#x10-790004.3.4" rel="nofollow noreferrer">Section 4.3.4 of the Report</a>, that the inferencer can adopt and that will replace a polymorphic type with a monomorphic one. This happens whenever a type is <em>ambiguous</em>.</p> <p>For example in the expression:</p> <pre><code>let x = read &quot;&lt;something&gt;&quot; in show x </code></pre> <p>here the expression is ambiguous because the types for <code>show</code> and <code>read</code> are:</p> <pre><code>show :: Show a =&gt; a -&gt; String read :: Read a =&gt; String -&gt; a </code></pre> <p>So the <code>x</code> has type <code>Read a =&gt; a</code>. But this constraint is satisfied by a lot of types: <code>Int</code>, <code>Double</code> or <code>()</code> for example. Which one to choose? There's nothing that can tell us.</p> <p>In this case we can resolve the ambiguity by telling the compiler which type we want, adding a type signature:</p> <pre><code>let x = read &quot;&lt;something&gt;&quot; :: Int in show x </code></pre> <p>Now the problem is: since Haskell uses the <code>Num</code> type class to handle numbers, there are <em>a lot</em> of cases where numerical expressions contain ambiguities.</p> <p>Consider:</p> <pre><code>show 1 </code></pre> <p>What should the result be?</p> <p>As before <code>1</code> has type <code>Num a =&gt; a</code> and there are many type of numbers that could be used. Which one to choose?</p> <p>Having a compiler error almost every time we use a number isn't a good thing, and hence the defaulting rules were introduced. The rules can be controlled using a <code>default</code> declaration. By specifying <code>default (T1, T2, T3)</code> we can change how the inferencer defaults the different types.</p> <p>An ambiguous type variable <code>v</code> is defaultable if:</p> <ul> <li><code>v</code> appears only in contraints of the kind <code>C v</code> were <code>C</code> is a class (i.e. if it appears as in: <code>Monad (m v)</code> then it is <strong>not</strong> defaultable).</li> <li>at least one of these classes is <code>Num</code> or a subclass of <code>Num</code>.</li> <li>all of these classes are defined in the Prelude or a standard library.</li> </ul> <p>A defaultable type variable is replaced by the <em>first</em> type in the <code>default</code> list that is an instance of all the ambiguous variable’s classes.</p> <p>The default <code>default</code> declaration is <code>default (Integer, Double)</code>.</p> <p>For example:</p> <pre><code>plus = (+) minus = (-) x = plus 1.0 1 y = minus 2 1 </code></pre> <p>The types inferred would be:</p> <pre><code>plus :: Fractional a =&gt; a -&gt; a -&gt; a minus :: Num a =&gt; a -&gt; a -&gt; a </code></pre> <p>which, by defaulting rules, become:</p> <pre><code>plus :: Double -&gt; Double -&gt; Double minus :: Integer -&gt; Integer -&gt; Integer </code></pre> <p>Note that this explains why in the example in the question only the <code>sort</code> definition raises an error. The type <code>Ord a =&gt; [a] -&gt; [a]</code> cannot be defaulted because <code>Ord</code> isn't a numeric class.</p> <h3>Extended defaulting</h3> <p>Note that GHCi comes with <a href="https://downloads.haskell.org/%7Eghc/7.8.4/docs/html/users_guide/interactive-evaluation.html#extended-default-rules" rel="nofollow noreferrer"><em>extended</em> defaulting rules</a> (or <a href="https://downloads.haskell.org/%7Eghc/8.0.2/docs/html/users_guide/ghci.html#type-defaulting-in-ghci" rel="nofollow noreferrer">here for GHC8</a>), which can be enabled in files as well using the <code>ExtendedDefaultRules</code> extensions.</p> <p>The defaultable type variables need not <em>only</em> appear in contraints where all the classes are standard and there must be at least one class that is among <code>Eq</code>, <code>Ord</code>, <code>Show</code> or <code>Num</code> and its subclasses.</p> <p>Moreover the default <code>default</code> declaration is <code>default ((), Integer, Double)</code>.</p> <p>This may produce odd results. Taking the example from the question:</p> <pre class="lang-none prettyprint-override"><code>Prelude&gt; :set -XMonomorphismRestriction Prelude&gt; import Data.List(sortBy) Prelude Data.List&gt; let sort = sortBy compare Prelude Data.List&gt; :t sort sort :: [()] -&gt; [()] </code></pre> <p>in ghci we don't get a type error but the <code>Ord a</code> constraints results in a default of <code>()</code> which is pretty much useless.</p> <h3>Useful links</h3> <p>There are <em>a lot</em> of resources and discussions about the monomorphism restriction.</p> <p>Here are some links that I find useful and that may help you understand or deep further into the topic:</p> <ul> <li>Haskell's wiki page: <a href="https://wiki.haskell.org/Monomorphism_restriction" rel="nofollow noreferrer">Monomorphism Restriction</a></li> <li>The <a href="https://www.haskell.org/onlinereport/haskell2010/" rel="nofollow noreferrer">report</a></li> <li>An accessible and nice <a href="http://lambda.jstolarek.com/2012/05/towards-understanding-haskells-monomorphism-restriction/" rel="nofollow noreferrer">blog post</a></li> <li>Sections 6.2 and 6.3 of <a href="http://research.microsoft.com/en-us/um/people/simonpj/papers/history-of-haskell/history.pdf" rel="nofollow noreferrer">A History Of Haskell: Being Lazy With Class</a> deals with the monomorphism restriction and type defaulting</li> </ul>
36,463,966
MySQL: When is Flush Privileges in MySQL really needed?
<p>When creating new tables and a user to go along with it, I usually just invoke the following commands:</p> <pre><code>CREATE DATABASE mydb; GRANT ALL PRIVILEGES ON mydb.* TO myuser@localhost IDENTIFIED BY "mypassword"; </code></pre> <p>I have never ever needed to utilize the <code>FLUSH PRIVILEGES</code> command after issuing the previous two commands. Users can log in and use their database and run PHP scripts which connect to the database just fine. Yet I see this command used in almost every tutorial I look at.</p> <p>When is the <code>FLUSH PRIVILEGES</code> command really needed and when is it unnecessary?</p>
36,464,093
4
3
null
2016-04-06 23:14:55.723 UTC
18
2021-02-01 19:51:17.347 UTC
2021-02-01 19:51:17.347 UTC
null
10,907,864
null
4,698,242
null
1
80
mysql
182,962
<p>Privileges assigned through GRANT option do not need FLUSH PRIVILEGES to take effect - MySQL server will notice these changes and reload the grant tables immediately.</p> <p><a href="http://dev.mysql.com/doc/refman/5.7/en/privilege-changes.html" rel="noreferrer">From MySQL documentation</a>:</p> <blockquote> <p>If you modify the grant tables directly using statements such as INSERT, UPDATE, or DELETE, your changes have no effect on privilege checking until you either restart the server or tell it to reload the tables. If you change the grant tables directly but forget to reload them, your changes have no effect until you restart the server. This may leave you wondering why your changes seem to make no difference!</p> <p>To tell the server to reload the grant tables, perform a flush-privileges operation. This can be done by issuing a FLUSH PRIVILEGES statement or by executing a mysqladmin flush-privileges or mysqladmin reload command.</p> <p>If you modify the grant tables indirectly using account-management statements such as GRANT, REVOKE, SET PASSWORD, or RENAME USER, the server notices these changes and loads the grant tables into memory again immediately.</p> </blockquote>
48,508,799
How to reset all files from working directory but not from staging area?
<p>Is there a way to reset all files from the working directory but not those from staging area?</p> <p>I know that using the following command one can reset any single file:</p> <p><code>git checkout thefiletoreset.txt</code></p> <p>And also that by using the following command it is possible to reset the entire repository to the last committed state:</p> <p><code>git reset --hard</code></p> <p>But is there any command that can reset the whole working directory, leaving the staging area untouched?</p>
57,066,072
2
3
null
2018-01-29 19:41:01.76 UTC
10
2020-11-28 21:44:54.357 UTC
null
null
null
null
6,510,552
null
1
10
git
20,953
<blockquote> <p>But is there any command that can reset the whole working directory, leaving the staging area untouched?</p> </blockquote> <p>With Git 2.23 (Q3 2019), yes there is: <a href="https://git-scm.com/docs/git-restore" rel="noreferrer"><strong><code>git restore</code></strong></a>.</p> <h2>How to use it (<a href="https://git-scm.com/docs/git-restore" rel="noreferrer">man page</a>)</h2> <p>To answer the OP's question:</p> <pre><code># restore working tree from HEAD content, without touching the index/staging area git restore # restore working tree from master content, without touching the index/staging area git restore -s master </code></pre> <h2>Details from Git sources</h2> <p>See <a href="https://github.com/git/git/commit/97ed685701a6df0273f7d29fd5bc0a0658a63cad" rel="noreferrer">commit 97ed685</a>, <a href="https://github.com/git/git/commit/d16dc428b47837cebd231de1fad76d9c307f34b0" rel="noreferrer">commit d16dc42</a>, <a href="https://github.com/git/git/commit/bcba406532725fcdf17d5a3d9c6585e8fc879021" rel="noreferrer">commit bcba406</a> (20 Jun 2019), <a href="https://github.com/git/git/commit/4e43b7ff1ea4b6f16b93a432b6718e9ab38749bd" rel="noreferrer">commit 4e43b7f</a>, <a href="https://github.com/git/git/commit/12358755949084392b1112cfb5cb4feb9935331f" rel="noreferrer">commit 1235875</a>, <a href="https://github.com/git/git/commit/80f537f79c16efeb7b92b3409ede434a230b5679" rel="noreferrer">commit 80f537f</a>, <a href="https://github.com/git/git/commit/fc991b43df83ee32a92b9d906e77276e5dbd639c" rel="noreferrer">commit fc991b4</a>, <a href="https://github.com/git/git/commit/75f4c7c1eb06cdf6eae1339bbac02dfb620acc11" rel="noreferrer">commit 75f4c7c</a>, <a href="https://github.com/git/git/commit/4df3ec6324ba78b9b28ce1ecb872594dd1bffa1c" rel="noreferrer">commit 4df3ec6</a>, <a href="https://github.com/git/git/commit/2f0896ec3ad4731d970d22f61daf62046bc766a9" rel="noreferrer">commit 2f0896e</a>, <a href="https://github.com/git/git/commit/a5e5f399ca89cea574d11704d625a7b28b53de76" rel="noreferrer">commit a5e5f39</a>, <a href="https://github.com/git/git/commit/3a733ce5237570460bbb63e20002b92e903ad65f" rel="noreferrer">commit 3a733ce</a>, <a href="https://github.com/git/git/commit/e3ddd3b5e583e62d874f56f8c88603ad0ebafd5e" rel="noreferrer">commit e3ddd3b</a>, <a href="https://github.com/git/git/commit/183fb44fd234499ed76d72d745ccb480b25f6d15" rel="noreferrer">commit 183fb44</a>, <a href="https://github.com/git/git/commit/4058199c0ec5b68ffa2225dcdf5235a328f2443e" rel="noreferrer">commit 4058199</a>, <a href="https://github.com/git/git/commit/a6cfb9ba360d975dd38b2e6e77a88d2c8fe8d323" rel="noreferrer">commit a6cfb9b</a>, <a href="https://github.com/git/git/commit/be8ed5022b84fa75c24f24bbf64bb5ad6652c64f" rel="noreferrer">commit be8ed50</a>, <a href="https://github.com/git/git/commit/c9c935f6d4519c53f27f50113bea2c17deb8b71e" rel="noreferrer">commit c9c935f</a>, <a href="https://github.com/git/git/commit/46e91b663badd99b3807ab34decfd32f3cbf15e7" rel="noreferrer">commit 46e91b6</a> (25 Apr 2019), and <a href="https://github.com/git/git/commit/328c6cb853d7237098569de9f94bc3d259846a08" rel="noreferrer">commit 328c6cb</a> (29 Mar 2019) by <a href="https://github.com/pclouds" rel="noreferrer">Nguyễn Thái Ngọc Duy (<code>pclouds</code>)</a>.<br /> <sup>(Merged by <a href="https://github.com/gitster" rel="noreferrer">Junio C Hamano -- <code>gitster</code> --</a> in <a href="https://github.com/git/git/commit/f496b064fc1135e0dded7f93d85d72eb0b302c22" rel="noreferrer">commit f496b06</a>, 09 Jul 2019)</sup></p> <blockquote> <h2><code>checkout</code>: split part of it to new command '<code>restore</code>'</h2> </blockquote> <blockquote> <p>Previously the switching branch business of '<code>git checkout</code>' becomes <a href="https://stackoverflow.com/a/57066202/6309"><strong>a new command '<code>switch</code>'</strong></a>. This adds the <code>restore</code> command for the checking out paths path.</p> <p>Similar to <code>git-switch</code>, a new man page is added to describe what the command will become. The implementation will be updated shortly to match the man page.</p> <p>A couple main differences from '<code>git checkout &lt;paths&gt;</code>':</p> <ul> <li><p><strong>'<code>restore</code>' by default will only update worktree</strong>.<br /> This matters more when <code>--source</code> is specified ('<code>checkout &lt;tree&gt; &lt;paths&gt;</code>' updates both worktree and index).</p> </li> <li><p>'<code>restore --staged</code>' can be used to restore the index.<br /> This command overlaps with '<code>git reset &lt;paths&gt;</code>'.</p> </li> <li><p>both worktree and index could also be restored at the same time (from a tree) when both <code>--staged</code> and <code>--worktree</code> are specified. This overlaps with '<code>git checkout &lt;tree&gt; &lt;paths&gt;</code>'</p> </li> <li><p>default source for restoring worktree and index is the index and HEAD respectively. A different (tree) source could be specified as with <code>--source</code> (*).</p> </li> <li><p>when both index and worktree are restored, <code>--source</code> must be specified since the default source for these two individual targets are different (**)</p> </li> <li><p><code>--no-overlay</code> is enabled by default, if an entry is missing in the source, restoring means deleting the entry</p> </li> </ul> <p>(*) I originally went with <code>--from</code> instead of <code>--source</code>.<br /> I still think <code>--from</code> is a better name. The short option <code>-f</code> however is already taken by <code>force</code>. And I do think short option is good to have, e.g. to write <code>-s@</code> or <code>-s@^</code> instead of <code>--source=HEAD</code>.</p> <p>(**) If you sit down and think about it, moving worktree's source from the index to HEAD makes sense, but nobody is really thinking it through when they type the commands.</p> </blockquote> <hr /> <p>Before Git 2.24 (Q3 2019), &quot;<code>git checkout</code>&quot; and &quot;<code>git restore</code>&quot; can re-populate the index from a tree-ish (typically HEAD), but did not work correctly for a path that was removed and then added again with the <strong>intent-to-add (<code>ita</code> or <code>i-t-a</code>)</strong> bit, when the corresponding working tree file was empty.<br /> This has been corrected.</p> <p>See <a href="https://github.com/git/git/commit/620c09e1b686e06c4ddbd5fb153f7ad898bab412" rel="noreferrer">commit 620c09e</a> (01 Aug 2019), and <a href="https://github.com/git/git/commit/ecd72042de7d79c05d8f153e288766c7f88f0b10" rel="noreferrer">commit ecd7204</a> (02 Aug 2019) by <a href="https://github.com/varunnaik" rel="noreferrer">Varun Naik (<code>varunnaik</code>)</a>.<br /> Helped-by: <a href="https://github.com/peff" rel="noreferrer">Jeff King (<code>peff</code>)</a>.<br /> <sup>(Merged by <a href="https://github.com/gitster" rel="noreferrer">Junio C Hamano -- <code>gitster</code> --</a> in <a href="https://github.com/git/git/commit/072735ea58407db41c0874fd2f8a91d0c191d49b" rel="noreferrer">commit 072735e</a>, 22 Aug 2019)</sup></p> <blockquote> <h2><code>checkout.c</code>: unstage empty deleted ita files</h2> </blockquote> <blockquote> <p>It is possible to delete a committed file from the index and then add it as <strong>intent-to-add</strong>.<br /> After <code>git checkout HEAD &lt;pathspec&gt;</code>, the file should be identical in the index and HEAD. The command already works correctly if the file has contents in HEAD. This patch provides the desired behavior even when the file is empty in HEAD.</p> <p><code>git checkout HEAD &lt;pathspec&gt;</code> calls <code>tree.c:read_tree_1()</code>, with fn pointing to <code>checkout.c:update_some()</code>.<br /> <code>update_some()</code> creates a new cache entry but discards it when its mode and oid match those of the old entry. A cache entry for an ita file and a cache entry for an empty file have the same oid. Therefore, an empty deleted ita file previously passed both of these checks, and the new entry was discarded, so the file remained unchanged in the index.<br /> After this fix, if the file is marked as ita in the cache, then we avoid discarding the new entry and add the new entry to the cache instead.</p> </blockquote> <hr /> <p>With Git 2.25 (Q1 2020), <code>git restore</code> is more robust parsing its options.</p> <p>See <a href="https://github.com/git/git/commit/169bed7421b9c71870231e41ccb93a7abad3240e" rel="noreferrer">commit 169bed7</a> (12 Nov 2019) by <a href="https://github.com/" rel="noreferrer">René Scharfe (``)</a>.<br /> <sup>(Merged by <a href="https://github.com/gitster" rel="noreferrer">Junio C Hamano -- <code>gitster</code> --</a> in <a href="https://github.com/git/git/commit/406ca29e0d660f8ba99a783cb207c53359f870cc" rel="noreferrer">commit 406ca29</a>, 01 Dec 2019)</sup></p> <blockquote> <h2><a href="https://github.com/git/git/commit/169bed7421b9c71870231e41ccb93a7abad3240e" rel="noreferrer"><code>parse-options</code></a>: avoid arithmetic on pointer that's potentially NULL</h2> <p><sup>Signed-off-by: René Scharfe</sup></p> </blockquote> <blockquote> <p><code>parse_options_dup()</code> counts the number of elements in the given array without the end marker, allocates enough memory to hold all of them plus an end marker, then copies them and terminates the new array.</p> <p>The counting part is done by advancing a pointer through the array, and the original pointer is reconstructed using pointer subtraction before the copy operation.</p> <p>The function is also prepared to handle a <code>NULL</code> pointer passed to it. None of its callers do that currently, but this feature was used by <a href="https://github.com/git/git/commit/46e91b663badd99b3807ab34decfd32f3cbf15e7" rel="noreferrer">46e91b663b</a> (&quot;<code>checkout</code>: split part of it to new command 'restore'&quot;, 2019-04-25, Git v2.23.0-rc0 -- <a href="https://github.com/git/git/commit/f496b064fc1135e0dded7f93d85d72eb0b302c22" rel="noreferrer">merge</a> listed in <a href="https://github.com/git/git/commit/6d5b26420848ec3bc7eae46a7ffa54f20276249d" rel="noreferrer">batch #4</a>); it seems worth keeping.</p> <p>It ends up doing arithmetic on that <code>NULL</code> pointer, though, which is undefined in standard C, when it tries to calculate &quot;<code>NULL</code> - 0&quot;.</p> <p>Better avoid doing that by remembering the originally given pointer value.</p> <p>There is another issue, though.</p> <p><code>memcpy(3)</code> does not support <code>NULL</code> pointers, even for empty arrays.</p> <p>Use <code>COPY_ARRAY</code> instead, which does support such empty arrays.</p> <p>Its call is also shorter and safer by inferring the element type automatically.</p> <p>Coccinelle and <code>contrib/coccinelle/array.cocci</code> did not propose to use <code>COPY_ARRAY</code> because of the pointer subtraction and because the source is const -- the semantic patch cautiously only considers pointers and array references of the same type. .</p> </blockquote> <hr /> <p>With Git 2.25.1 (Feb. 2020), &quot;<code>git restore --staged</code>&quot; did not correctly update the cache-tree structure, resulting in bogus trees to be written afterwards, which has been corrected.</p> <p>See <a href="https://public-inbox.org/git/[email protected]/" rel="noreferrer">discussion</a></p> <p>See <a href="https://github.com/git/git/commit/e701bab3e95f7029e59717eab610a544821b2213" rel="noreferrer">commit e701bab</a> (08 Jan 2020) by <a href="https://github.com/peff" rel="noreferrer">Jeff King (<code>peff</code>)</a>.<br /> <sup>(Merged by <a href="https://github.com/gitster" rel="noreferrer">Junio C Hamano -- <code>gitster</code> --</a> in <a href="https://github.com/git/git/commit/09e393d913072d7765b02aba1210d843a83cfbae" rel="noreferrer">commit 09e393d</a>, 22 Jan 2020)</sup></p> <blockquote> <h2><a href="https://github.com/git/git/commit/e701bab3e95f7029e59717eab610a544821b2213" rel="noreferrer"><code>restore</code></a>: invalidate cache-tree when removing entries with --staged</h2> <p><sup>Reported-by: Torsten Krah</sup><br /> <sup>Signed-off-by: Jeff King</sup></p> </blockquote> <blockquote> <p>When &quot;<a href="https://git-scm.com/docs/git-restore#Documentation/git-restore.txt---staged" rel="noreferrer"><code>git restore --staged</code></a> &quot; removes a path that's in the index, it marks the entry with <code>CE_REMOVE,</code> but we don't do anything to invalidate the cache-tree.<br /> In the non-staged case, we end up in <code>checkout_worktree()</code>, which calls <code>remove_marked_cache_entries()</code>. That actually drops the entries from the index, as well as invalidating the cache-tree and untracked-cache.</p> <p>But with <code>--staged</code>, we never call <code>checkout_worktree()</code>, and the <code>CE_REMOVE</code> entries remain. Interestingly, they are dropped when we write out the index, but that means the resulting index is inconsistent: its cache-tree will not match the actual entries, and running &quot;<code>git commit</code>&quot; immediately after will create the wrong tree.</p> <p>We can solve this by calling <code>remove_marked_cache_entries()</code> ourselves before writing out the index. Note that we can't just hoist it out of <code>checkout_worktree()</code>; that function needs to iterate over the <code>CE_REMOVE</code> entries (to drop their matching worktree files) before removing them.</p> <p>One curiosity about the test: without this patch, it actually triggers a BUG() when running git-restore:</p> <pre><code>BUG: cache-tree.c:810: new1 with flags 0x4420000 should not be in cache-tree </code></pre> <p>But in the original problem report, which used a similar recipe, <a href="https://git-scm.com/docs/git-restore" rel="noreferrer"><code>git restore</code></a> actually creates the bogus index (and the commit is created with the wrong tree). I'm not sure why the test here behaves differently than my out-of-suite reproduction, but what's here should catch either symptom (and the fix corrects both cases).</p> </blockquote> <hr /> <p>With Git 2.26 (Q1 2020), <code>parse_option_dup</code> (used by <code>git restore</code>) is cleaned-up.</p> <p>See <a href="https://github.com/git/git/commit/7a9f8ca805045f5d6d59227c8cce5a3e6790b0ef" rel="noreferrer">commit 7a9f8ca</a>, <a href="https://github.com/git/git/commit/c84078573e9dc4b817d8270268583251eed7cff9" rel="noreferrer">commit c840785</a>, <a href="https://github.com/git/git/commit/f904f9025f070b17a440d019b53e1d70fca3a269" rel="noreferrer">commit f904f90</a>, <a href="https://github.com/git/git/commit/a277d0a67f0324deb58abbeb0c5a2b3abbcde340" rel="noreferrer">commit a277d0a</a> (09 Feb 2020) by <a href="https://github.com/rscharfe" rel="noreferrer">René Scharfe (<code>rscharfe</code>)</a>.<br /> <sup>(Merged by <a href="https://github.com/gitster" rel="noreferrer">Junio C Hamano -- <code>gitster</code> --</a> in <a href="https://github.com/git/git/commit/cbecc168d4264d93295cd1e0a48dc19f0ed1880c" rel="noreferrer">commit cbecc16</a>, 17 Feb 2020)</sup></p> <blockquote> <h2><a href="https://github.com/git/git/commit/7a9f8ca805045f5d6d59227c8cce5a3e6790b0ef" rel="noreferrer"><code>parse-options</code></a>: simplify <code>parse_options_dup()</code></h2> <p><sup>Signed-off-by: René Scharfe</sup></p> </blockquote> <blockquote> <p>Simplify <code>parse_options_dup()</code> by making it a trivial wrapper of <code>parse_options_concat()</code> by making use of the facts that the latter duplicates its input as well and that appending an empty set is a no-op.</p> </blockquote>
48,699,836
How to change .NET Framework in Rider IDE?
<p>In Rider IDE, I am trying to create a new solution:</p> <p><a href="https://i.stack.imgur.com/IPGIF.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/IPGIF.jpg" alt="enter image description here" /></a></p> <p>But I'm unable to change the .NET Framework as the dropdown is disabled. How can I change the version? I have installed .NET Framework 3.5, 4.5, 4.6.</p>
48,702,057
4
4
null
2018-02-09 06:18:29.743 UTC
0
2021-04-14 07:24:28.52 UTC
2021-04-14 07:24:28.52 UTC
null
1,402,846
null
4,222,487
null
1
21
c#|.net|.net-framework-version|rider
42,255
<p>Actually for now Rider contains the only one Web App Template - for net45. We are going to add another one - for net4.6.1 (or 4.6.2) in 2018.1. You can track status here: <a href="https://youtrack.jetbrains.com/issue/RIDER-10888" rel="nofollow noreferrer">https://youtrack.jetbrains.com/issue/RIDER-10888</a></p> <p>The main issue here - we can not just change target framework version, but change all referenced package versions and some template files... </p>
48,864,985
VSCode single to double quote automatic replace
<p>When I execute a <code>Format Document</code> command on a Vue Component.vue file VSCode replace all single quoted string with double quoted string.</p> <p>In my specific case this rule conflicts with electron-vue lint configuration that require singlequote.</p> <p>I don't have prettier extensions installed (no <code>prettier.singleQuote</code> in my setting)</p> <p>How to customize VSCode to avoid this? </p>
48,866,406
30
4
null
2018-02-19 11:16:25.793 UTC
25
2022-08-08 03:53:47.503 UTC
2020-05-27 06:39:56.5 UTC
null
6,904,888
null
3,356,777
null
1
206
visual-studio-code|vscode-settings
263,010
<p>I dont have <code>prettier</code> extension installed, but after reading the <a href="https://stackoverflow.com/questions/47091719/vs-code-auto-indent-code-formatting-changes-single-quotation-marks-to-double">possible duplicate</a> answer I've added from scratch in my User Setting (<code>UserSetting.json</code>, Ctrl+, shortcut):</p> <pre><code>"prettier.singleQuote": true </code></pre> <p>A part a green warning (<code>Unknown configuration setting</code>) the single quotes are no more replaced.</p> <p>I suspect that the prettier extension is not visible but is embedded inside the <a href="https://marketplace.visualstudio.com/items?itemName=octref.vetur" rel="noreferrer">Vetur</a> extension.</p>
7,696,347
To break a message in two or more lines in JOptionPane
<pre><code>try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); String connectionUrl = "jdbc:sqlserver://"+hostName.getText()+";" + "databaseName="+dbName.getText()+";user="+userName.getText()+";password="+password.getText()+";"; Connection con = DriverManager.getConnection(connectionUrl); if(con!=null){JOptionPane.showMessageDialog(this, "Connection Established");} } catch (SQLException e) { JOptionPane.showMessageDialog(this, e); //System.out.println("SQL Exception: "+ e.toString()); } catch (ClassNotFoundException cE) { //System.out.println("Class Not Found Exception: "+ cE.toString()); JOptionPane.showMessageDialog(this, cE.toString()); } </code></pre> <p>When there is an error it shows a long JOptionPane message box that is longer than the width of the computer screen. How can I break e.toString() into two or more parts.</p>
7,707,397
4
0
null
2011-10-08 10:59:19.663 UTC
3
2018-11-13 08:46:03.587 UTC
2011-10-08 12:51:45.317 UTC
null
714,968
null
922,402
null
1
9
java|swing|newline|joptionpane
43,094
<p><img src="https://i.stack.imgur.com/rJrch.png" alt="enter image description here"></p> <pre><code>import javax.swing.*; class FixedWidthLabel { public static void main(String[] args) { Runnable r = () -&gt; { String html = "&lt;html&gt;&lt;body width='%1s'&gt;&lt;h1&gt;Label Width&lt;/h1&gt;" + "&lt;p&gt;Many Swing components support HTML 3.2 &amp;amp; " + "(simple) CSS. By setting a body width we can cause " + "the component to find the natural height needed to " + "display the component.&lt;br&gt;&lt;br&gt;" + "&lt;p&gt;The body width in this text is set to %1s pixels."; // change to alter the width int w = 175; JOptionPane.showMessageDialog(null, String.format(html, w, w)); }; SwingUtilities.invokeLater(r); } } </code></pre>
7,439,955
Servlet API implementation using Netty
<p>Has anyone made a Servlet API implementation built on top of Netty? I'm tempted to build my own as I can't google an implementation.</p> <ul> <li><a href="http://www.jboss.org/netty/community#nabble-td4752485">http://www.jboss.org/netty/community#nabble-td4752485</a></li> <li><a href="http://markmail.org/message/4qmvuaacxqzevqhc">http://markmail.org/message/4qmvuaacxqzevqhc</a></li> </ul> <p>Basically I'm looking to support just enough to get jersey working (hopefully jersey is not doing any threadlocal stuff).</p>
7,456,586
4
2
null
2011-09-16 03:52:29.19 UTC
9
2013-08-10 22:00:25.713 UTC
2011-11-06 11:39:32.45 UTC
null
21,234
null
318,174
null
1
17
java|servlets|nio|netty
16,588
<p>Jersey does not require servlet - runs fine even with the lightweight http server included in JDK or even runs with Grizzly NIO framework (which is similar to Netty - see grizzly.java.net). To see what it takes to make it run with Netty, you may want to look at jersey-grizzly2 module in Jersey workspace - would be nice if you would be willing to develop that and contribute to the Jersey project. Now, to disappoint you, Jersey does use ThreadLocals. We have been planning to introduce support for non-blocking async calls, but that requires a fair amount of refactoring, so will only come with 2.0 version (implementing JAX-RS 2.0 once that's final). Anyway, apart from the non-blocking stuff, it is still useful to run it on Grizzly-like framework such as Netty for its "light-weightness".</p>
7,872,113
How to remove a folder and all its content from the current directory?
<p>This code that does not work:</p> <pre><code>@echo off if exist output @set /p checkdir= Output directory found. Do you wish to overwrite it?: if /I %checkdir% == Y deltree /s /output pause </code></pre>
7,874,557
1
1
null
2011-10-24 06:47:47.147 UTC
7
2018-03-23 16:26:50.243 UTC
2017-05-11 16:04:32.89 UTC
null
576,767
null
866,800
null
1
44
windows|batch-file
74,574
<p>You were looking for this command:</p> <pre><code>RMDIR [/S] [/Q] [drive:]path RD [/S] [/Q] [drive:]path /S Removes all directories and files in the specified directory in addition to the directory itself. Used to remove a directory tree. /Q Quiet mode, do not ask if ok to remove a directory tree with /S </code></pre> <p>In your case just use <strong>/S</strong> ,it will delete the whole directory tree by first asking the user if it should proceed, i.e.- displaying the following output to the screen:</p> <p><code>"folderName, Are you sure (Y/N)?"</code></p> <p>where <code>folderName</code> is the name of the folder (and its sub-folders) you wish to remove.</p> <p>Tested on Windows 7, 64 bit.</p>
1,578,361
Update Sharepoint List Item
<p>I got following error...</p> <blockquote> <p>System.NullReferenceException: Object reference not set to an instance of an object. at Microsoft.SharePoint.SPListItem.get_UniqueId() at ConsoleApplication1.Program.Main(String[] args) in Program.cs:line 21</p> </blockquote> <p>running following code</p> <pre><code>using (SPSite site = new SPSite("http://site/")) { using (SPWeb web = site.OpenWeb()) { try { SPList list = web.Lists["ListName"]; // 2 SPListItem item = list.Items.Add(); Guid itemId = item.UniqueId; SPListItem itemUpdate = web.Lists["ListName"].Items[itemId]; itemUpdate["PercentComplete"] = .45; // 45% itemUpdate.Update(); } catch (Exception e) { Console.WriteLine(e); Console.ReadLine(); } } } </code></pre> <p>What's the problem?</p>
1,578,509
4
1
null
2009-10-16 14:21:42.423 UTC
6
2017-11-07 15:10:37.037 UTC
2009-10-22 04:46:13.127 UTC
null
25,163
null
189,737
null
1
8
c#|asp.net|sharepoint|wss
76,222
<p>If you're trying to alter values for a just inserted list item, you should go with:</p> <pre><code>SPList list = web.Lists["ListName"]; //SPListItem item = list.Items.Add(); //item["PercentComplete"] = .45; // 45% //item.Update(); SPListItemCollection items = list.GetItems(new SPQuery() { Query = @"&lt;Where&gt; &lt;Eq&gt; &lt;FieldRef Name='Title' /&gt; &lt;Value Type='Text'&gt;Desigining&lt;/Value&gt; &lt;/Eq&gt; &lt;/Where&gt;" }); foreach (SPListItem item in items) { item["PercentComplete"] = .45; // 45% item.Update(); } </code></pre> <p>You just need to use <code>list.Items[uniqueId]</code> or faster <code>list.GetItemByUniqueId(uniqueId)</code> if you needs to find a particular item to update; what can be accomplished by using <code>SPQuery</code> class.</p>
2,238,522
Significance of PermGen Space
<p>What is the significance of PermGen space in java?</p>
2,238,534
4
1
null
2010-02-10 16:34:52.51 UTC
9
2012-03-27 04:17:18.837 UTC
2012-03-27 04:17:18.837 UTC
null
697,449
null
268,850
null
1
29
java|memory-management|jvm|permgen
11,710
<p>PermGen space is reserved for long-term objects - mostly <code>Class</code> objects loaded by the <code>ClassLoader</code>. PermGen will not be garbage collected except under very special circumstances (specifically, when the <code>ClassLoader</code> that loaded those classes goes out of scope). </p> <p>This is a garbage collection optimization - if objects that we don't expect to be garbage collected are stored separately, it compacts the space where the rest of the objects are stored, which leads to less work for the garbage collector.</p>
1,507,501
Linq Aggregate complex types into a string
<p>I've seen the simple example of the .net Aggregate function working like so:</p> <pre><code>string[] words = { "one", "two", "three" }; var res = words.Aggregate((current, next) =&gt; current + ", " + next); Console.WriteLine(res); </code></pre> <p>How could the 'Aggregate' function be used if you wish to aggregate more complex types? For example: a class with 2 properties such as 'key' and 'value' and you want the output like this: </p> <pre><code>"MyAge: 33, MyHeight: 1.75, MyWeight:90" </code></pre>
1,509,042
4
0
null
2009-10-02 02:29:55.353 UTC
4
2018-03-18 12:54:00.837 UTC
null
null
null
null
74,449
null
1
30
.net|asp.net|linq|string-concatenation
21,661
<p>You have two options:</p> <ol> <li><p>Project to a <code>string</code> and then aggregate:</p> <pre><code>var values = new[] { new { Key = "MyAge", Value = 33.0 }, new { Key = "MyHeight", Value = 1.75 }, new { Key = "MyWeight", Value = 90.0 } }; var res1 = values.Select(x =&gt; string.Format("{0}:{1}", x.Key, x.Value)) .Aggregate((current, next) =&gt; current + ", " + next); Console.WriteLine(res1); </code></pre> <p>This has the advantage of using the first <code>string</code> element as the seed (no prepended ", "), but will consume more memory for the strings created in the process.</p></li> <li><p>Use an aggregate overload that accepts a seed, perhaps a <code>StringBuilder</code>:</p> <pre><code>var res2 = values.Aggregate(new StringBuilder(), (current, next) =&gt; current.AppendFormat(", {0}:{1}", next.Key, next.Value), sb =&gt; sb.Length &gt; 2 ? sb.Remove(0, 2).ToString() : ""); Console.WriteLine(res2); </code></pre> <p>The second delegate converts our <code>StringBuilder</code> into a <code>string,</code> using the conditional to trim the starting ", ".</p></li> </ol>
1,676,195
file upload without activerecord
<p>How do you handle file upload in rail without attaching them to active record ?<br> I just want to write the files to the disk.</p> <p>Thanks,</p>
1,678,388
4
1
null
2009-11-04 19:55:22.6 UTC
20
2017-09-29 05:30:04.867 UTC
null
null
null
null
143,148
null
1
35
ruby-on-rails
25,598
<p>If I understand correctly what you need then the most simple example would be this:</p> <p>The controller:</p> <pre><code> class UploadController &lt; ApplicationController def new end def create name = params[:upload][:file].original_filename path = File.join("public", "images", "upload", name) File.open(path, "wb") { |f| f.write(params[:upload][:file].read) } flash[:notice] = "File uploaded" redirect_to "/upload/new" end end </code></pre> <p>The view:</p> <pre><code>&lt;% flash.each do |key, msg| %&gt; &lt;%= content_tag :div, msg, :class =&gt; [key, " message"], :id =&gt; "notice_#{key}" %&gt; &lt;% end %&gt; &lt;% form_tag '/upload/create', { :multipart =&gt; true } do %&gt; &lt;p&gt; &lt;%= file_field_tag 'upload[file]' %&gt; &lt;/p&gt; &lt;p&gt; &lt;%= submit_tag "Upload" %&gt; &lt;/p&gt; &lt;% end %&gt; </code></pre> <p>This would let you upload any file without any checks or validations which in my opinion isn't that usefull.</p> <p>If I would do it myself then I would use something like <a href="http://validatable.rubyforge.org/" rel="noreferrer">validatable gem</a> or <a href="http://github.com/kennethkalmer/activerecord-tableless-models" rel="noreferrer">tableless gem</a> just tableless is not supported anymore. These gems would allow you to validate what you're uploading to make it more sane.</p>
2,309,943
Unioning two tables with different number of columns
<p>I have two tables (Table A and Table B).</p> <p>These have different number of columns - Say Table A has more columns.</p> <p>How can I union these two table and get null for the columns that Table B does not have?</p>
2,309,966
4
1
null
2010-02-22 09:33:02.323 UTC
33
2020-09-04 14:02:12.427 UTC
2018-01-11 07:55:21.123 UTC
null
680,068
null
122,528
null
1
147
sql|mysql
276,550
<p>Add extra columns as null for the table having less columns like</p> <pre><code>Select Col1, Col2, Col3, Col4, Col5 from Table1 Union Select Col1, Col2, Col3, Null as Col4, Null as Col5 from Table2 </code></pre>
52,653,337
vuejs - Redirect from login/register to home if already loggedin, Redirect from other pages to login if not loggedin in vue-router
<p>I want to redirect user to home page if logged-in and wants to access login/register page and redirect user to login page if not logged-in and wants to access other pages. Some pages are excluded that means there is no need to be logged in so my code is right below:</p> <pre><code>router.beforeEach((to, from, next) =&gt; { if( to.name == 'About' || to.name == 'ContactUs' || to.name == 'Terms' ) { next(); } else { axios.get('/already-loggedin') .then(response =&gt; { // response.data is true or false if(response.data) { if(to.name == 'Login' || to.name == 'Register') { next({name: 'Home'}); } else { next(); } } else { next({name: 'Login'}); } }) .catch(error =&gt; { // console.log(error); }); } }); </code></pre> <p>But the problem is that it gets into an infinite loop and for example each time login page loads and user not logged-in, it redirects user to login page and again to login page and...</p> <p>How can I fix this?</p>
52,663,166
5
4
null
2018-10-04 18:49:25.433 UTC
5
2021-08-28 05:08:25.49 UTC
2018-10-04 19:43:05.767 UTC
null
9,182,477
null
9,182,477
null
1
26
vue.js|vue-router
41,541
<p>Here's what I'm doing. First I'm using a <code>meta</code> data for the routes, so I don't need to manually put all routes that are not requiring login:</p> <pre class="lang-js prettyprint-override"><code>routes: [ { name: 'About' // + path, component, etc }, { name: 'Dashboard', // + path, component, etc meta: { requiresAuth: true } } ] </code></pre> <p>Then, I have a global guard like this:</p> <pre class="lang-js prettyprint-override"><code>router.beforeEach((to, from, next) =&gt; { if (to.matched.some(record =&gt; record.meta.requiresAuth)) { // this route requires auth, check if logged in // if not, redirect to login page. if (!store.getters.isLoggedIn) { next({ name: 'Login' }) } else { next() // go to wherever I'm going } } else { next() // does not require auth, make sure to always call next()! } }) </code></pre> <p>Here I am storing if the user is logged in or not, and not making a new request.</p> <p>In your example, you have <strong>forgotten</strong> to include <code>Login</code> into the list of pages that "don't need authentication". So if the user is trying to go to let's say <code>Dashboard</code>, you make the request, turns out he's not logged in. Then he goes to <code>Login</code>, BUT your code checks, sees it's not part of the 3 "auth not required" list, and makes another call :)</p> <p>Therefore skipping this "list" is crucial! ;)</p> <p>Good luck!</p>
10,300,875
jQuery Check for tablet?
<p>I use a media query to load in a stylesheet (if device is a tablet).</p> <p>I was just wondering how I could check in my javascript if the user is using a tablet, is there a check or should I just check what stylesheet was loaded in?</p>
10,301,074
3
2
null
2012-04-24 15:16:56.837 UTC
2
2014-04-05 21:55:14.067 UTC
2012-04-24 15:18:18.32 UTC
null
106,224
null
1,013,512
null
1
30
javascript|jquery
56,478
<p>Try to see if perhaps this sheds a light on your question:</p> <p><a href="https://stackoverflow.com/questions/3514784/best-way-to-detect-handheld-device-in-jquery">What is the best way to detect a mobile device in jQuery?</a></p> <p>As the answer to that thread says, I'd suggest to rely on 'feature detection' rather than tablet vs non-tablet (as it may not be as straightforward as one may think) hence --> <a href="http://modernizr.com/" rel="nofollow noreferrer">http://modernizr.com/</a></p>
10,326,406
Getting index value on razor foreach
<p>I'm iterating a <code>List&lt;T&gt;</code> in a razor foreach loop in my view which renders a partial. In the partial I'm rendering a single record for which I want to have 4 in a row in my view. I have a css class for the two end columns so need to determine in the partial whether the call is the 1st or the 4th record. What is the best way of identifying this in my partial to output the correct code?</p> <p>This is my main page which contains the loop:</p> <pre><code>@foreach (var myItem in Model.Members){ //if i = 1 &lt;div class="grid_20"&gt; &lt;!-- Start Row --&gt; //is there someway to get in for i = 1 to 4 and pass to partial? @Html.Partial("nameOfPartial", Model) //if i = 4 then output below and reset i to 1 &lt;div class="clear"&gt;&lt;/div&gt; &lt;!-- End Row --&gt; &lt;/div&gt; } </code></pre> <p>I figure I can create a int that I can update on each pass and render the text no problem here but it's passing the integer value into my partial I'm more concerned about. Unless there's a better way.</p> <p>Here is my partial:</p> <pre><code>@{ switch() case 1: &lt;text&gt; &lt;div class="grid_4 alpha"&gt; &lt;/text&gt; break; case 4: &lt;text&gt; &lt;div class="grid_4 omega"&gt; &lt;/text&gt; break; default: &lt;text&gt; &lt;div class="grid_4"&gt; &lt;/text&gt; break; } &lt;img src="Content/960-grid/spacer.gif" style="width:130px; height:160px; background-color:#fff; border:10px solid #d3d3d3;" /&gt; &lt;p&gt;&lt;a href="member-card.html"&gt;@Model.Name&lt;/a&gt;&lt;br/&gt; @Model.Job&lt;br/&gt; @Model.Location&lt;/p&gt; &lt;/div&gt; </code></pre> <p>Not sure if I'm having a blonde day today and this is frightfully easy but I just can't think of the best way to pass the int value in. Hope someone can help.</p>
22,373,172
11
2
null
2012-04-26 02:24:12.51 UTC
10
2021-02-20 16:56:10.14 UTC
null
null
null
null
151,522
null
1
76
asp.net-mvc|asp.net-mvc-2|razor|partial-views
134,404
<pre><code> @{int i = 0;} @foreach(var myItem in Model.Members) { &lt;span&gt;@i&lt;/span&gt; @{i++; } } </code></pre> <p>// Use @{i++ to increment value}</p>
28,567,549
How to use if within a map return?
<p>I need to generate diffrent reactJS code based on datamodel but I get </p> <blockquote> <p>In file "~/Scripts/Grid.jsx": Parse Error: Line 13: Unexpected token if (at line 13 column 15) Line: 52 Column:3</p> </blockquote> <p>With this code</p> <pre><code>var GridRow = React.createClass({ render: function() { var row; row = this.props.cells.map(function(cell, i) { return ( if(cell.URL != null &amp;&amp; cell.URL.length &gt; 0){ &lt;td className={cell.Meta.HTMLClass} key={i}&gt;{cell.Text}&lt;/td&gt; } else { &lt;td className={cell.Meta.HTMLClass} key={i}&gt;{cell.Text}&lt;/td&gt; } ); }.bind(this)); return ( &lt;tr&gt; {row} &lt;/tr&gt; ); } }); </code></pre> <p>The render part seems to be really limited in how it can be used?</p>
28,567,644
2
3
null
2015-02-17 17:36:53.503 UTC
12
2019-09-26 12:07:13.5 UTC
null
null
null
null
365,624
null
1
39
javascript|reactjs
131,116
<p>You put <code>return</code> statement inside <code>if</code> clause like so:</p> <pre><code> row = this.props.cells.map(function(cell, i) { if(cell.URL != null &amp;&amp; cell.URL.length &gt; 0){ return &lt;td className={cell.Meta.HTMLClass} key={i}&gt;{cell.Text}&lt;/td&gt;; } else { return &lt;td className={cell.Meta.HTMLClass} key={i}&gt;{cell.Text}&lt;/td&gt;; } }.bind(this)); </code></pre>
7,293,220
Adding jquery mobile swipe event
<p>I have a listview and what I am trying to do is add a swipe event on the links. For example, if a user swipes the first link it goes to that page. Is this possible with listview elements. I have tried div,href,a,li,ul but still no alert. It works with body. Thanks</p> <pre><code>&lt;div&gt; &lt;ul data-role="listview" data-inset="true"&gt; &lt;li class="rqstpage"&gt;&lt;a href="./requests.php"&gt;Requests&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="./speakers.php" data-transition="pop"&gt;Control Panel&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="./schedule.html"&gt;Schedule&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="./information.html"&gt;Information&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;script&gt; $("div ul li.rqstpage").bind('swipe',function(event, ui){ $.mobile.changePage("requests.php", "slide"); }); &lt;/script&gt; </code></pre>
7,309,030
5
1
null
2011-09-03 12:53:06.16 UTC
16
2014-06-09 18:57:55.453 UTC
2013-01-30 12:07:50.917 UTC
null
31,532
null
804,749
null
1
27
jquery|jquery-mobile
102,688
<p>Live Example:</p> <ul> <li><a href="http://jsfiddle.net/yxzZf/4/" rel="nofollow noreferrer">http://jsfiddle.net/yxzZf/4/</a></li> </ul> <p>JS:</p> <pre><code>$("#listitem").swiperight(function() { $.mobile.changePage("#page1"); }); </code></pre> <p>HTML:</p> <pre><code>&lt;div data-role="page" id="home"&gt; &lt;div data-role="content"&gt; &lt;p&gt; &lt;ul data-role="listview" data-inset="true" data-theme="c"&gt; &lt;li id="listitem"&gt;Swipe Right to view Page 1&lt;/li&gt; &lt;/ul&gt; &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div data-role="page" id="page1"&gt; &lt;div data-role="content"&gt; &lt;ul data-role="listview" data-inset="true" data-theme="c"&gt; &lt;li data-role="list-divider"&gt;Navigation&lt;/li&gt; &lt;li&gt;&lt;a href="#home"&gt;Back to the Home Page&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;p&gt; Yeah!&lt;br /&gt;You Swiped Right to view Page 1 &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Related:</p> <ul> <li><a href="https://stackoverflow.com/questions/7298915/adding-jqm-swipe-event-to-listview-link">Adding JQM swipe event to listview link</a></li> </ul>
7,479,265
How to Apply Mask to Image in OpenCV?
<p>I want to <strong>apply a binary mask</strong> to a color image. Please provide a basic code example with proper explanation of how the code works.</p> <p>Also, is there some option to apply a mask permanently so all functions operate only within the mask?</p>
7,504,836
6
0
null
2011-09-20 01:59:41.767 UTC
8
2022-06-06 14:38:28.91 UTC
2020-06-29 15:08:40.913 UTC
null
6,674,599
null
1,526,152
null
1
24
c++|image|image-processing|opencv|mask
116,529
<p>You don't apply a binary mask to an image. You (optionally) use a binary mask in a processing function call to tell the function which pixels of the image you want to process. If I'm completely misinterpreting your question, you should add more detail to clarify.</p>
7,378,644
How to call getWindow() outside an Activity in Android?
<p>I am trying to organize my code and move repetitive functions to a single class. This line of code works fine inside a class that extends activity:</p> <pre><code>getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); </code></pre> <p>However it is not working when I try to include it into an external class.</p> <p>How do I call getWindow() from another class to apply it inside an Activity?</p>
7,378,652
7
0
null
2011-09-11 13:49:14.083 UTC
8
2022-08-28 00:50:30.2 UTC
2014-11-04 10:42:46.493 UTC
null
529,024
null
529,024
null
1
50
java|android
103,792
<p>Pass a reference of the activity when you create the class, and when calling relevant methods and use it.</p> <pre><code>void someMethodThatUsesActivity(Activity myActivityReference) { myActivityReference.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); } </code></pre>
7,508,322
How do I map lists of nested objects with Dapper
<p>I'm currently using Entity Framework for my db access but want to have a look at Dapper. I have classes like this:</p> <pre><code>public class Course{ public string Title{get;set;} public IList&lt;Location&gt; Locations {get;set;} ... } public class Location{ public string Name {get;set;} ... } </code></pre> <p>So one course can be taught at several locations. Entity Framework does the mapping for me so my Course object is populated with a list of locations. How would I go about this with Dapper, is it even possible or do I have to do it in several query steps?</p>
7,523,274
8
2
null
2011-09-22 00:48:35.333 UTC
74
2021-05-17 10:24:12.003 UTC
2018-04-23 14:54:45.65 UTC
null
206,730
null
395,377
null
1
155
orm|dapper
126,881
<p>Dapper is not a full blown ORM it does not handle magic generation of queries and such. </p> <p>For your particular example the following would probably work:</p> <h3>Grab the courses:</h3> <pre><code>var courses = cnn.Query&lt;Course&gt;("select * from Courses where Category = 1 Order by CreationDate"); </code></pre> <h3>Grab the relevant mapping:</h3> <pre><code>var mappings = cnn.Query&lt;CourseLocation&gt;( "select * from CourseLocations where CourseId in @Ids", new {Ids = courses.Select(c =&gt; c.Id).Distinct()}); </code></pre> <h3>Grab the relevant locations</h3> <pre><code>var locations = cnn.Query&lt;Location&gt;( "select * from Locations where Id in @Ids", new {Ids = mappings.Select(m =&gt; m.LocationId).Distinct()} ); </code></pre> <h3>Map it all up</h3> <p>Leaving this to the reader, you create a few maps and iterate through your courses populating with the locations. </p> <p><strong>Caveat</strong> the <code>in</code> trick will work if you have less than <a href="https://stackoverflow.com/questions/845931/maximum-number-of-parameters-in-sql-query/845972#845972">2100</a> lookups (Sql Server), if you have more you probably want to amend the query to <code>select * from CourseLocations where CourseId in (select Id from Courses ... )</code> if that is the case you may as well yank all the results in one go using <code>QueryMultiple</code></p>
13,813,675
MySQL Timestamp Difference
<p>I have a table with column timestam which stores a timestamp with this format: "2012-12-10 21:24:30"</p> <p>I am looking for a SQL Query that takes the current timestamp and subtracts it with the one in the column and gives the difference in this format:</p> <p>"3 Hours and 2 mins Remaining"</p> <p>Looking for a MySQL Query that does that. </p>
13,813,710
2
0
null
2012-12-11 04:30:39.337 UTC
3
2016-04-13 06:32:48.943 UTC
2016-04-13 06:32:48.943 UTC
null
5,735,460
null
1,089,139
null
1
22
mysql|timestamp
41,836
<p>use <a href="http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_timestampdiff"><code>TIMESTAMPDIFF</code></a> </p> <pre><code>TIMESTAMPDIFF(unit,datetime_expr1,datetime_expr2) </code></pre> <blockquote> <p>where unit argument, which should be one of the following values: MICROSECOND (microseconds), SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, or YEAR.</p> </blockquote> <p><strong>my approach :</strong> set unit as <strong>SECOND</strong> and then use <strong><a href="http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_sec-to-time">SEC_TO_TIME</a></strong></p> <pre><code>SELECT SEC_TO_TIME(TIMESTAMPDIFF(SECOND,`table`.`time_column`,CURRENT_TIMESTAMP())) // will return in hh:mm:ii format </code></pre> <h3>update</h3> <p>Return <strong>yes</strong> if <code>HourDifference</code> are less than 48 hours? otherwise <strong>no</strong></p> <pre><code>SELECT IF(TIMESTAMPDIFF(HOUR,`time_column`,CURRENT_TIMESTAMP())&lt; 48 ,'yes','no') </code></pre>
14,324,270
Matplotlib custom marker/symbol
<p>So there is this guide: <a href="http://matplotlib.org/examples/pylab_examples/scatter_symbol.html" rel="noreferrer">http://matplotlib.org/examples/pylab_examples/scatter_symbol.html</a> <img src="https://i.stack.imgur.com/YsJ5d.png" alt="enter image description here"></p> <pre><code># http://matplotlib.org/examples/pylab_examples/scatter_symbol.html from matplotlib import pyplot as plt import numpy as np import matplotlib x = np.arange(0.0, 50.0, 2.0) y = x ** 1.3 + np.random.rand(*x.shape) * 30.0 s = np.random.rand(*x.shape) * 800 + 500 plt.scatter(x, y, s, c="g", alpha=0.5, marker=r'$\clubsuit$', label="Luck") plt.xlabel("Leprechauns") plt.ylabel("Gold") plt.legend(loc=2) plt.show() </code></pre> <p>But what if you are like me and don't want to use a clubsuit marker...</p> <p>How do you make your own marker _________?</p> <p><strong><em>UPDATE</em></strong></p> <p>What I like about this special marker type is that it's easy to adjust with simple matplotlib syntax:</p> <pre><code>from matplotlib import pyplot as plt import numpy as np import matplotlib x = np.arange(0.0, 50.0, 2.0) y = x ** 1.3 + np.random.rand(*x.shape) * 30.0 s = np.random.rand(*x.shape) * 800 + 500 plt.plot(x, y, "ro", alpha=0.5, marker=r'$\clubsuit$', markersize=22) plt.xlabel("Leprechauns") plt.ylabel("Gold") plt.show() </code></pre> <p><img src="https://i.stack.imgur.com/h7GeG.png" alt="enter image description here"></p>
58,552,620
2
2
null
2013-01-14 18:24:19.503 UTC
20
2019-11-01 22:59:19.827 UTC
2013-01-19 10:04:48.343 UTC
null
618,099
null
618,099
null
1
39
python|matplotlib
41,008
<p>The most flexible option for <code>matplotlib</code> is <a href="https://matplotlib.org/3.1.1/gallery/shapes_and_collections/marker_path.html" rel="noreferrer">marker paths</a>. </p> <p>I used Inkscape to convert <a href="https://commons.wikimedia.org/wiki/File:718smiley.svg" rel="noreferrer">Smiley face svg</a> into a single SVG path. Inkscape also has options to trace path in raster images. The I used svg path to convert it to <code>matplotlib.path.Path</code> using <a href="https://github.com/nvictus/svgpath2mpl" rel="noreferrer">svgpath2mpl</a>. </p> <pre class="lang-py prettyprint-override"><code>!pip install svgpath2mpl matplotlib from svgpath2mpl import parse_path import matplotlib.pyplot as plt import numpy as np # Use Inkscape to edit SVG, # Path -&gt; Combine to convert multiple paths into a single path # Use Path -&gt; Object to path to convert objects to SVG path smiley = parse_path("""m 739.01202,391.98936 c 13,26 13,57 9,85 -6,27 -18,52 -35,68 -21,20 -50,23 -77,18 -15,-4 -28,-12 -39,-23 -18,-17 -30,-40 -36,-67 -4,-20 -4,-41 0,-60 l 6,-21 z m -302,-1 c 2,3 6,20 7,29 5,28 1,57 -11,83 -15,30 -41,52 -72,60 -29,7 -57,0 -82,-15 -26,-17 -45,-49 -50,-82 -2,-12 -2,-33 0,-45 1,-10 5,-26 8,-30 z M 487.15488,66.132209 c 121,21 194,115.000001 212,233.000001 l 0,8 25,1 1,18 -481,0 c -6,-13 -10,-27 -13,-41 -13,-94 38,-146 114,-193.000001 45,-23 93,-29 142,-26 z m -47,18 c -52,6 -98,28.000001 -138,62.000001 -28,25 -46,56 -51,87 -4,20 -1,57 5,70 l 423,1 c 2,-56 -39,-118 -74,-157 -31,-34 -72,-54.000001 -116,-63.000001 -11,-2 -38,-2 -49,0 z m 138,324.000001 c -5,6 -6,40 -2,58 3,16 4,16 10,10 14,-14 38,-14 52,0 15,18 12,41 -6,55 -3,3 -5,5 -5,6 1,4 22,8 34,7 42,-4 57.6,-40 66.2,-77 3,-17 1,-53 -4,-59 l -145.2,0 z m -331,-1 c -4,5 -5,34 -4,50 2,14 6,24 8,24 1,0 3,-2 6,-5 17,-17 47,-13 58,9 7,16 4,31 -8,43 -4,4 -7,8 -7,9 0,0 4,2 8,3 51,17 105,-20 115,-80 3,-15 0,-43 -3,-53 z m 61,-266 c 0,0 46,-40 105,-53.000001 66,-15 114,7 114,7 0,0 -14,76.000001 -93,95.000001 -76,18 -126,-49 -126,-49 z""") smiley.vertices -= smiley.vertices.mean(axis=0) x = np.linspace(-3, 3, 20) plt.plot(x, np.sin(x), marker=smiley, markersize=20, color='c') plt.show() </code></pre> <p><a href="https://colab.research.google.com/drive/1RonnV9F2iWa8uR_Q8rgSJTbtymOIJMKX" rel="noreferrer">Google Colab Link</a></p> <p><a href="https://i.stack.imgur.com/6oupq.png" rel="noreferrer"><img src="https://i.stack.imgur.com/6oupq.png" alt="Plot created from above code snippet"></a></p>
13,973,158
How do I convert a javascript object array to a string array of the object attribute I want?
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/8281824/accessing-properties-of-an-array-of-objects">Accessing properties of an array of objects</a> </p> </blockquote> <p> Given:</p> <pre><code>[{ 'id':1, 'name':'john' },{ 'id':2, 'name':'jane' }........,{ 'id':2000, 'name':'zack' }] </code></pre> <p>What's the best way to get:</p> <pre><code>['john', 'jane', ...... 'zack'] </code></pre> <p>Must I loop through and push <code>item.name</code> to another array, or is there a simple function to do it?</p>
13,973,194
4
2
null
2012-12-20 13:22:47.957 UTC
18
2017-10-31 23:55:55.763 UTC
2017-10-31 23:55:55.763 UTC
null
2,729,534
null
268,151
null
1
118
javascript
177,546
<p>If your array of objects is <code>items</code>, you can do:</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-js lang-js prettyprint-override"><code>var items = [{ id: 1, name: 'john' }, { id: 2, name: 'jane' }, { id: 2000, name: 'zack' }]; var names = items.map(function(item) { return item['name']; }); console.log(names); console.log(items);</code></pre> </div> </div> </p> <p>Documentation: <strong><a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map" rel="noreferrer"><code>map()</code></a></strong></p>
9,235,934
Get preferred date format string of Android system
<p>Does anybody know how to get the format string used by the system when formatting a date using </p> <pre><code>DateFormat.getLongDateFormat(Context context).format(Date date) </code></pre>
17,718,379
8
1
null
2012-02-10 22:52:00.423 UTC
3
2018-01-23 00:05:36.153 UTC
2013-09-03 12:22:47.477 UTC
null
458,741
null
1,130,746
null
1
29
android
26,543
<p>I wrote a method to detect this format string. ( work for my case).</p> <pre><code>public static String getDateFormat(Context context){ // 25/12/2013 Calendar testDate = Calendar.getInstance(); testDate.set(Calendar.YEAR, 2013); testDate.set(Calendar.MONTH, Calendar.DECEMBER); testDate.set(Calendar.DAY_OF_MONTH, 25); Format format = android.text.format.DateFormat.getDateFormat(context); String testDateFormat = format.format(testDate.getTime()); String[] parts = testDateFormat.split("/"); StringBuilder sb = new StringBuilder(); for(String s : parts){ if(s.equals("25")){ sb.append("dd/"); } if(s.equals("12")){ sb.append("MM/"); } if(s.equals("2013")){ sb.append("yyyy/"); } } return sb.toString().substring(0, sb.toString().length()-1); } </code></pre> <p><strong>EDIT</strong> Please check the Mark Melling's answer below <strong><a href="https://stackoverflow.com/a/18982842/945808">https://stackoverflow.com/a/18982842/945808</a></strong> to have better solution. Mine was just a hack long time ago.</p>
44,511,436
How to do an explicit fall-through in C
<p>The newer versions of gcc offer the <code>Wimplicit-fallthrough</code>, which is great to have for most switch statements. However, I have one switch statement where I want to allow fall throughs from all case-statements.</p> <p>Is there a way to do an explicit fall through? I'd prefer to avoid having to compile with <code>Wno-implicit-fallthrough</code> for this file.</p> <p>EDIT: I'm looking for a way to make the fall through explicit (if it's possible), not to turn off the warning via a compiler switch or pragma.</p>
44,511,477
3
3
null
2017-06-13 02:27:09.22 UTC
4
2021-04-22 20:13:22.17 UTC
2017-06-14 03:13:27.02 UTC
null
2,638,548
null
2,638,548
null
1
29
c|gcc|c99|gcc-warning
13,930
<p>Use <a href="https://gcc.gnu.org/onlinedocs/gcc/Statement-Attributes.html" rel="nofollow noreferrer"><code>__attribute__ ((fallthrough))</code></a></p> <pre><code>switch (condition) { case 1: printf(&quot;1 &quot;); __attribute__ ((fallthrough)); case 2: printf(&quot;2 &quot;); __attribute__ ((fallthrough)); case 3: printf(&quot;3\n&quot;); break; } </code></pre>
19,533,567
Trouble sorting three numbers in ascending order in Java
<p>I'm currently working on a program and I just cannot get it to work the way it is supposed to work. I need to enter three integers using a scanner, and then output the numbers in ascending order. I technically got this to work but it didn't follow the structure that it HAS to follow. In my main method I have the declarations and input. Then I have to use a second method that does the sorting. I for the life of me cannot get the numbers to sort at all actually when I put the sorting inside this new method. It compiles, I run it, enter the numbers and it ends the program. Without the second method it runs correct, mostly. When it ran outside the second method there was also some errors I believe in the way that I thought was logical to sort the numbers.</p> <p>Anyway this is the code that I came up with.</p> <pre><code>import java.util.Scanner; public class Ch5PA1 { public static void main(String[] args) { // Declarations Scanner input = new Scanner(System.in); System.out.print("Enter three values: "); int num1 = input.nextInt(); int num2 = input.nextInt(); int num3 = input.nextInt(); } /** Sort Numbers */ public static void displaySortedNumbers(double num1, double num2, double num3){ if ((num1 &lt; num2) &amp;&amp; (num2 &lt; num3)){ System.out.println("The sorted numbers are " + num1 + " " + num2 + " " + num3); } if ((num1 &lt; num2) &amp;&amp; (num2 &gt; num3)){ System.out.println("The sorted numbers are " + num1 + " " + num3 + " " + num2); } if ((num1 &gt; num2) &amp;&amp; (num2 &gt; num3)){ System.out.println("The sorted numbers are " + num3 + " " + num2 + " " + num1); } if ((num1 &gt; num2) &amp;&amp; (num2 &lt; num3)){ System.out.println("The sorted numbers are " + num2 + " " + num1 + " " + num3); } } } </code></pre> <p>Another thing, looking around I saw a few questions people asked about the same (or similar) issues I am having with this but the replies insist on using arrays. I cannot use an array at all for this.</p> <p>Thanks ahead of time.</p>
19,533,671
10
2
null
2013-10-23 05:35:18.95 UTC
0
2022-03-12 01:44:51.263 UTC
null
null
null
null
2,872,123
null
1
-2
java|sorting
56,175
<p>In your main method call your method:</p> <pre><code>public static void main(String[] args) { // Declarations Scanner input = new Scanner(System.in); System.out.print("Enter three values: "); int num1 = input.nextInt(); int num2 = input.nextInt(); int num3 = input.nextInt(); displaySortedNumbers(num1, num2, num3); } </code></pre> <p>And for more info. about sorting 3 numbers here is an old post:</p> <p><a href="https://stackoverflow.com/questions/13040240/the-fastest-way-to-sort-3-values-java">Fastest way to sort 3 values in Java</a></p> <p>And giving a look to your code, I don't think it's posible to sort 3 numbers just by comparing them 2 times.</p>
19,687,419
Android: onClick on LinearLayout with TextView and Button
<p>I have a Fragment that uses the following XML layout:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/card" android:clickable="true" android:onClick="editActions" android:orientation="vertical" &gt; &lt;TextView android:id="@+id/title" style="@style/CardTitle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:duplicateParentState="true" android:text="@string/title_workstation" /&gt; &lt;Button android:id="@+id/factory_button_edit" style="?android:attr/buttonStyleSmall" android:layout_width="wrap_content" android:layout_height="wrap_content" android:duplicateParentState="true" android:text="@string/label_edit" /&gt; &lt;/LinearLayout&gt; </code></pre> <p>As you can see, I have an <strong>onClick</strong> parameter set on <code>LinearLayout</code>. Now on the <code>TextView</code> this one is triggered correctly, and on all empty area. Just on the <code>Button</code> it doesn't invoke the onClick method that I set.</p> <p>Is this normal? What do I have to do so that the onClick method is invoked everywhere on the <code>LinearLayout</code>?</p>
19,687,762
10
2
null
2013-10-30 15:43:20.023 UTC
5
2020-07-09 11:24:45.053 UTC
null
null
null
null
902,358
null
1
7
android|android-layout|onclick|android-xml
49,147
<p>add onClick Action for your button dirrectly in code like this: </p> <pre><code>Button btn = findViewById(R.id.factory_button_edit); btn.setOnClickListener(button_click); OnClickListener button_click = new OnClickListener() { @Override public void onClick(View v) { editActions; } }; </code></pre> <p>or xml add </p> <pre><code>android:onClick="editActions" </code></pre> <p>to your button</p>
19,519,328
Testing javascript alerts with Jasmine
<p>I'm writing some Jasmine tests for some legacy javascript that produces an alert or a confirm at some points in the code. </p> <p>At the moment where the alert pops up it pauses execution in the browser requiring me to press ok before going on.</p> <p>I'm sure I'm missing something but is there a way of faking an alert? </p> <p>Even better is it possible to find out what the message was for the alert?</p> <p>Thanks for your help.</p>
26,976,989
4
2
null
2013-10-22 13:30:41.977 UTC
4
2020-07-02 21:48:28.063 UTC
2013-10-22 14:08:03.753 UTC
null
1,023,425
null
1,023,425
null
1
31
javascript|jasmine
19,198
<pre><code>spyOn(window, 'alert'); . . . expect(window.alert).toHaveBeenCalledWith('a message'); </code></pre>
52,244,808
Backpressure mechanism in Spring Web-Flux
<p>I'm a starter in <strong>Spring Web-Flux</strong>. I wrote a controller as follows: </p> <pre><code>@RestController public class FirstController { @GetMapping("/first") public Mono&lt;String&gt; getAllTweets() { return Mono.just("I am First Mono") } } </code></pre> <p>I know one of the reactive benefits is <strong>Backpressure</strong>, and it can balance the request or the response rate. I want to realize how to have backpressure mechanism in <strong>Spring Web-Flux</strong>.</p>
52,245,213
1
4
null
2018-09-09 13:04:05.317 UTC
35
2021-06-18 07:39:19.577 UTC
2018-09-09 13:40:13.88 UTC
null
4,922,375
null
793,934
null
1
54
java|reactive-programming|spring-webflux|backpressure
21,524
<h1>Backpressure in WebFlux</h1> <p>In order to understand how Backpressure works in the current implementation of the WebFlux framework, we have to recap the transport layer used by default here. As we may remember, the normal communication between browser and server (server to server communication usually the same as well) is done through the TCP connection. WebFlux also uses that transport for communication between a client and the server. Then, in order to get the meaning of the <em>backpressure control</em> term, we have to recap what backpressure means from the Reactive Streams specification perspective.</p> <blockquote> <p>The basic semantics define how the transmission of stream elements is regulated through back-pressure.</p> </blockquote> <p>So, from that statement, we may conclude that in Reactive Streams the backpressure is a mechanism that regulates the demand through the transmission (notification) of how many elements recipient can consume; And here we have a tricky point. The TCP has a bytes abstraction rather than logical elements abstraction. What we usually want by saying backpressure control is the control of the number of logical elements sent/received to/from the network. Even though the TCP has its own flow control (see the meaning <a href="https://www.brianstorti.com/tcp-flow-control/" rel="noreferrer">here</a> and animation <a href="http://www-sop.inria.fr/mistral/personnel/Thomas.Bonald/tcp_eng.html" rel="noreferrer">there</a>) this flow control is still for bytes rather than for logical elements.</p> <p>In the current implementation of the WebFlux module, the backpressure is regulated by the transport flow control, but it does not expose the real demand of the recipient. In order to finally see the interaction flow, please see the following diagram:</p> <p><a href="https://i.stack.imgur.com/cJIEk.png" rel="noreferrer"><img src="https://i.stack.imgur.com/cJIEk.png" alt="enter image description here" /></a></p> <p>For simplicity, the above diagram shows the communication between two microservices where the left one sends streams of data, and the right one consumes that stream. The following numbered list provides a brief explanation of that diagram:</p> <ol> <li>This is the WebFlux framework that takes proper care for conversion of logical elements to bytes and back and transferring/receiving them to/from the TCP (network).</li> <li>This is the starting of long-running processing of the element which requests for next elements once the job is completed.</li> <li>Here, while there is no demand from the business logic, the WebFlux enqueue bytes that come from the network without their acknowledgment (there is no demand from the business logic).</li> <li>Because of the nature of TCP flow control, Service A may still send data to the network.</li> </ol> <p>As we may notice from the diagram above, the demand exposed by the recipient is different from the demand of the sender (demand here in logical elements). It means that the demand of both is isolated and works only for WebFlux &lt;-&gt; Business logic (Service) interaction and exposes less the backpressure for Service A &lt;-&gt; Service B interaction. All that means that the backpressure control is not that fair in WebFlux as we expect.</p> <p><em><strong>All that means that the backpressure control is not that fair in WebFlux as we expect.</strong></em></p> <h2>But I still want to know how to control backpressure</h2> <p>If we still want to have an unfair control of backpressure in WebFlux, we may do that with the support of Project Reactor operators such as <a href="https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Flux.html#limitRate-int-" rel="noreferrer"><code>limitRate()</code></a>. The following example shows how we may use that operator:</p> <pre><code>@PostMapping(&quot;/tweets&quot;) public Mono&lt;Void&gt; postAllTweets(Flux&lt;Tweet&gt; tweetsFlux) { return tweetService.process(tweetsFlux.limitRate(10)) .then(); } </code></pre> <p>As we may see from the example, <code>limitRate()</code> operator allows defining the number of elements to be prefetched at once. That means that even if the final subscriber requests <code>Long.MAX_VALUE</code> elements, the <code>limitRate</code> operator split that demand into chunks and does not allow to consume more than that at once. The same we may do with elements sending process:</p> <pre><code>@GetMapping(&quot;/tweets&quot;) public Flux&lt;Tweet&gt; getAllTweets() { return tweetService.retreiveAll() .limitRate(10); } </code></pre> <p>The above example shows that even if WebFlux requests more then 10 elements at a time, the <code>limitRate()</code> throttles the demand to the prefetch size and prevents to consume more than the specified number of elements at once.</p> <p>Another option is to implement own <code>Subscriber</code> or extend the <code>BaseSubscriber</code> from Project Reactor. For instance, The following is a naive example of how we may do that:</p> <pre><code>class MyCustomBackpressureSubscriber&lt;T&gt; extends BaseSubscriber&lt;T&gt; { int consumed; final int limit = 5; @Override protected void hookOnSubscribe(Subscription subscription) { request(limit); } @Override protected void hookOnNext(T value) { // do business logic there consumed++; if (consumed == limit) { consumed = 0; request(limit); } } } </code></pre> <h1>Fair backpressure with RSocket Protocol</h1> <p>In order to achieve logical-elements backpressure through the network boundaries, we need an appropriate protocol for that. Fortunately, there is one called <a href="http://rsocket.io/" rel="noreferrer">RScoket protocol</a>. RSocket is an application-level protocol that allows transferring real demand through the network boundaries. There is an RSocket-Java implementation of that protocol that allows to set up an RSocket server. In the case of a server to server communication, the same RSocket-Java library provides a client implementation as well. To learn more how to use RSocket-Java, please see the following examples <a href="https://github.com/rsocket/rsocket-java/tree/1.0.x/rsocket-examples/src/main/java/io/rsocket/examples/transport/tcp" rel="noreferrer">here</a>. For browser-server communication, there is an <a href="https://github.com/rsocket/rsocket-js" rel="noreferrer">RSocket-JS</a> implementation which allows wiring the streaming communication between browser and server through WebSocket.</p> <h1>Known frameworks on top of RSocket</h1> <p>Nowadays there are a few frameworks, built on top of the RSocket protocol.</p> <h2>Proteus</h2> <p>One of the frameworks is a Proteus project which offers full-fledged microservices built on top of RSocket. Also, Proteus is well integrated with Spring framework so now we may achieve a fair backpressure control (see examples <a href="https://github.com/netifi-proteus/proteus-spring/tree/master/demos/springboot-demo" rel="noreferrer">there</a>)</p> <h1>Further readings</h1> <ul> <li><a href="https://www.netifi.com/proteus" rel="noreferrer">https://www.netifi.com/proteus</a></li> <li><a href="https://medium.com/netifi" rel="noreferrer">https://medium.com/netifi</a></li> <li><a href="http://scalecube.io/" rel="noreferrer">http://scalecube.io/</a></li> </ul>
35,160,256
How do I output lists as a table in Jupyter notebook?
<p>I know that I've seen some example somewhere before but for the life of me I cannot find it when googling around.</p> <p>I have some rows of data:</p> <pre><code>data = [[1,2,3], [4,5,6], [7,8,9], ] </code></pre> <p>And I want to output this data in a table, e.g.</p> <pre><code>+---+---+---+ | 1 | 2 | 3 | +---+---+---+ | 4 | 5 | 6 | +---+---+---+ | 7 | 8 | 9 | +---+---+---+ </code></pre> <p>Obviously I could use a library like prettytable or download pandas or something but I'm very disinterested in doing that.</p> <p>I just want to output my rows as tables in my Jupyter notebook cell. How do I do this?</p>
35,161,699
12
5
null
2016-02-02 17:40:45.297 UTC
19
2022-01-16 06:20:47.317 UTC
null
null
null
null
344,286
null
1
104
python|jupyter-notebook
171,611
<p>I finally re-found the <a href="http://nbviewer.jupyter.org/github/ipython/ipython/blob/4.0.x/examples/IPython%20Kernel/Rich%20Output.ipynb#HTML" rel="noreferrer">jupyter/IPython documentation</a> that I was looking for.</p> <p>I needed this:</p> <pre><code>from IPython.display import HTML, display data = [[1,2,3], [4,5,6], [7,8,9], ] display(HTML( '&lt;table&gt;&lt;tr&gt;{}&lt;/tr&gt;&lt;/table&gt;'.format( '&lt;/tr&gt;&lt;tr&gt;'.join( '&lt;td&gt;{}&lt;/td&gt;'.format('&lt;/td&gt;&lt;td&gt;'.join(str(_) for _ in row)) for row in data) ) )) </code></pre> <p>(I may have slightly mucked up the comprehensions, but <code>display(HTML('some html here'))</code> is what we needed)</p>
914,143
Display XML on an ASP.NET page
<p>I have a string containing XML document using LinqtoXML</p> <p>What is the best way of displaying it on an asp.net page as is.</p>
914,318
5
0
null
2009-05-27 05:44:57.037 UTC
3
2016-07-07 08:06:09.32 UTC
null
null
null
null
105,133
null
1
15
asp.net
49,205
<p>I would have liked to do it the way Dennis has mentioned (using an <code>&lt;asp:Xml&gt;</code> control). But that necessitates the use of an XSL stylesheet to format the XML. The Xml control does not allow an HTML encoded string to be passed as the DocumentContent property and does not expose any method to encode the content.</p> <p>As I have mentioned in the comments to Dennis' post, the defaultss.xsl contained within msxml.dll is not available publicly (and is not XSL 1.0 compliant). However, a public converted version was posted here: <a href="http://www.dpawson.co.uk/xsl/sect2/microsoft.html#d7615e227" rel="noreferrer">http://www.dpawson.co.uk/xsl/sect2/microsoft.html#d7615e227</a>. I have tested it and it works, though a bit buggy.</p> <p>Therefore, I think the simplest way would be to use an <code>&lt;asp:Literal&gt;</code> control to output pre-encoded XML to the page. The following sample demonstrates this method:</p> <hr> <pre><code>&lt;%@ Page Language="C#" %&gt; &lt;%@ Import Namespace="System.IO" %&gt; &lt;%@ Import Namespace="System.Xml" %&gt; &lt;script runat="server"&gt; protected void Page_Load(object sender, EventArgs e) { string theXML = Server.HtmlEncode(File.ReadAllText(Server.MapPath("~/XML/myxmlfile.xml"))); lit1.Text = theXML; } &lt;/script&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head runat="server"&gt; &lt;title&gt;Untitled Page&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;form id="form1" runat="server"&gt; &lt;div&gt; &lt;pre&gt; &lt;asp:Literal ID="lit1" runat="server" /&gt; &lt;/pre&gt; &lt;/div&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
1,310,422
How to do something to every file in a directory using bash?
<p>I started with this:</p> <pre><code>command * </code></pre> <p>But it doesn't work when the directory is empty; the * wildcard becomes a literal "*" character. So I switched to this:</p> <pre><code>for i in *; do ... done </code></pre> <p>which works, but again, not if the directory is empty. I resorted to using ls:</p> <pre><code>for i in `ls -A` </code></pre> <p>but of course, then file names with spaces in them get split. I tried tacking on the -Q switch:</p> <pre><code>for i in `ls -AQ` </code></pre> <p>which causes the names to still be split, only with a quote character at the beginning and ending of the name. Am I missing something obvious here, or is this harder than it ought it be?</p>
1,310,438
5
1
null
2009-08-21 07:12:14.493 UTC
8
2011-11-23 09:27:47.22 UTC
null
null
null
new sys admin
null
null
1
21
bash|shell
41,629
<p>Assuming you only want to do something to files, the simple solution is to test if $i is a file:</p> <pre><code>for i in * do if test -f "$i" then echo "Doing somthing to $i" fi done </code></pre> <p>You should really always make such tests, because you almost certainly don't want to treat files and directories in the same way. Note the quotes around the "$i" which prevent problems with filenames containing spaces.</p>
760,301
Implementing a no-op std::ostream
<p>I'm looking at making a logging class which has members like Info, Error etc that can configurably output to console, file, or to nowhere.</p> <p>For efficiency, I would like to avoid the overhead of formatting messages that are going to be thrown away (ie info messages when not running in a verbose mode). If I implement a custom std::streambuf that outputs to nowhere, I imagine that the std::ostream layer will still do all the formatting. Can anyone suggest a way to have a truly "null" std::ostream that avoids doing any work at all on the parameters passed to it with <code>&lt;&lt;</code>?</p>
760,350
5
2
null
2009-04-17 12:55:46.367 UTC
11
2019-07-24 19:30:18.81 UTC
2019-07-24 19:21:18.347 UTC
null
212,378
null
32,817
null
1
32
c++|logging|debugging
8,924
<p>To prevent the <code>operator&lt;&lt;()</code> invocations from doing formatting, you should know the streamtype at compile-time. This can be done either with macros or with templates.</p> <p>My template solution follows.</p> <pre><code>class NullStream { public: void setFile() { /* no-op */ } template&lt;typename TPrintable&gt; NullStream&amp; operator&lt;&lt;(TPrintable const&amp;) { return *this; } /* no-op */ } template&lt;class TErrorStream&gt; // add TInfoStream etc class Logger { public: TErrorStream&amp; errorStream() { return m_errorStream; } private: TErrorStream m_errorStream; }; //usage int main() { Logger&lt;std::ofstream&gt; normal_logger; // does real output normal_logger.errorStream().open("out.txt"); normal_logger.errorStream() &lt;&lt; "My age is " &lt;&lt; 19; Logger&lt;NullStream&gt; null_logger; // does zero output with zero overhead null_logger.errorStream().open("out.txt"); // no-op null_logger.errorStream() &lt;&lt; "My age is " &lt;&lt; 19; // no-op } </code></pre> <p>Since you have to do this at compile-time, it is of course quite inflexible.</p> <p>For example, you cannot decide the logging level at runtime from a configuration file.</p>
741,950
Programmatically determining amount of parameters a function requires - Python
<p>I was creating a simple command line utility and using a dictionary as a sort of case statement with key words linking to their appropriate function. The functions all have different amount of arguments required so currently to check if the user entered the correct amount of arguments needed for each function I placed the required amount inside the dictionary case statement in the form <code>{Keyword:(FunctionName, AmountofArguments)}</code>.</p> <p>This current setup works perfectly fine however I was just wondering in the interest of self improval if there was a way to determine the required number of arguments in a function and my google attempts have returned so far nothing of value but I see how args and kwargs could screw such a command up because of the limitless amount of arguments they allow.</p>
741,957
6
0
null
2009-04-12 15:43:34.777 UTC
4
2017-04-10 16:35:58.38 UTC
2017-04-10 16:35:58.38 UTC
null
1,033,581
null
56,924
null
1
38
python|parameters|function
28,347
<p><a href="http://docs.python.org/library/inspect.html#inspect.getargspec" rel="noreferrer">inspect.getargspec()</a>:</p> <blockquote> <p>Get the names and default values of a function’s arguments. A tuple of four things is returned: (args, varargs, varkw, defaults). args is a list of the argument names (it may contain nested lists). varargs and varkw are the names of the * and ** arguments or None. defaults is a tuple of default argument values or None if there are no default arguments; if this tuple has n elements, they correspond to the last n elements listed in args.</p> </blockquote>
810,493
Recommendations for java captcha libraries
<p>I'm looking for a replacement for JCaptcha, which doesn't seem to be maintained any more, and isn't very good to begin with. The replacement has to integrate nicely with JavaEE webapps.</p> <p>As I can see it, there are three options:</p> <ul> <li>JCaptcha - No longer maintained, crude API</li> <li>SimpleCaptcha - much nicer API, nicer captchas, but seems to be Java6 only</li> <li>ReCaptcha - easy to use, uses remote web-service to generate captchas, but not much control over look and feel</li> </ul> <p>Has anyone used any others, that they'd recommend?</p>
810,499
6
2
2009-06-27 21:33:45.433 UTC
2009-05-01 07:20:10.023 UTC
34
2021-04-15 07:54:11.317 UTC
2014-11-16 13:51:48.547 UTC
null
573,032
null
21,234
null
1
67
java|jakarta-ee|captcha|recaptcha|simplecaptcha
77,776
<p><a href="http://recaptcha.net/" rel="noreferrer">ReCaptcha</a> is the only captcha you should use, because it's the only captcha that makes the world better (improve OCR results to old text), with almost unlimited database.</p> <p>All other captchas are usually limited by its database, or do nothing good to this world.</p> <p><strong>EDIT :: I found steps how to implement captcha using recaptcha.</strong></p> <h2>You can check both Online and Offline captcha using java <a href="http://technoscripts.com/creating-captcha-application-using-java/" rel="noreferrer">here</a></h2>
274,360
Checking if an instance's class implements an interface?
<p>Given a class instance, is it possible to determine if it implements a particular interface? As far as I know, there isn't a built-in function to do this directly. What options do I have (if any)?</p>
274,363
6
0
null
2008-11-08 04:24:28.397 UTC
18
2021-12-14 12:50:31.647 UTC
null
null
null
Wilco
5,291
null
1
180
php|interface|oop
117,999
<pre><code>interface IInterface { } class TheClass implements IInterface { } $cls = new TheClass(); if ($cls instanceof IInterface) { echo "yes"; } </code></pre> <p>You can use the "instanceof" operator. To use it, the left operand is a class instance and the right operand is an interface. It returns true if the object implements a particular interface.</p>
31,169,514
Microsoft.ReportViewer.Common Version=12.0.0.0
<p>I'm getting the following exception in my Windows Service Application:</p> <blockquote> <p>System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.ReportViewer.Common, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' or one of its dependencies. The system cannot find the file specified.</p> </blockquote> <p>I cannot find a download url for version 12 and setting the files to "Include" and "Prequisite (Auto)" does not solve the problem in this Windows Service Application, although it works fine in my WinForms Application and results in the appropriate files being included and referenced along with all other requisite .DLLs.</p> <p>Can someone either help me get this Windows Service Application to include the files, or lead me to a download link that will install Version 12 in the GAC?</p>
31,170,281
7
3
null
2015-07-01 18:59:37.363 UTC
4
2020-10-20 22:01:21.8 UTC
2016-12-10 00:38:18.937 UTC
null
1,760,479
null
148,051
null
1
14
.net|reportviewer
132,467
<p>Version 12 of the ReportViewer bits is referred to as <em>Microsoft Report Viewer 2015 Runtime</em> and can downloaded for installation from the following link:</p> <p><a href="https://www.microsoft.com/en-us/download/details.aspx?id=45496" rel="noreferrer">https://www.microsoft.com/en-us/download/details.aspx?id=45496</a></p> <p><strong>UPDATE:</strong></p> <p>The ReportViewer bits are also available as a NUGET package: <a href="https://www.nuget.org/packages/Microsoft.ReportViewer.Runtime.Common/12.0.2402.15" rel="noreferrer">https://www.nuget.org/packages/Microsoft.ReportViewer.Runtime.Common/12.0.2402.15</a></p> <p><code>Install-Package Microsoft.ReportViewer.Runtime.Common</code></p>
32,581,644
Branch-aware programming
<p>I'm reading around that branch misprediction can be a hot bottleneck for the performance of an application. As I can see, people often show <em>assembly</em> code that unveil the problem and state that programmers usually can predict where a branch could go the most of the times and avoid branch mispredictons.</p> <p>My questions are:</p> <ol> <li><p>Is it possible to <em>avoid</em> branch mispredictions using some <em>high level</em> programming technique (i.e. <strong>no assembly</strong>)?</p> </li> <li><p>What should I keep in mind to produce <em>branch-friendly</em> code in a high level programming language (I'm mostly interested in C and C++)?</p> </li> </ol> <p>Code examples and benchmarks are welcome.</p>
32,581,909
8
17
null
2015-09-15 08:48:47.16 UTC
9
2020-09-20 20:26:33.203 UTC
2020-09-20 20:26:33.203 UTC
null
6,461,462
null
2,508,150
null
1
41
c++|c|performance|optimization|branch-prediction
7,733
<blockquote> <p>people often ... and state that programmers usually can predict where a branch could go</p> </blockquote> <p>(*) Experienced programmers often remind that human programmers are very bad at predicting that.</p> <blockquote> <p>1- Is it possible to avoid branch mispredictions using some high level programming technique (i.e. no assembly)?</p> </blockquote> <p>Not in standard c++ or c. At least not for a single branch. What you can do is minimize the depth of your dependency chains so that branch mis-prediction would not have any effect. Modern cpus will execute both code paths of a branch and drop the one that wasn't chosen. There's a limit to this however, which is why branch prediction only matters in deep dependency chains.</p> <p>Some compilers provide extension for suggesting the prediction manually such as <a href="https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html" rel="nofollow noreferrer">__builtin_expect</a> in gcc. Here is a <a href="https://stackoverflow.com/a/30131034/2079303">stackoverflow question</a> about it. Even better, some compilers (such as gcc) support profiling the code and automatically detect the optimal predictions. It's smart to use profiling rather than manual work because of (*).</p> <blockquote> <p>2- What should I keep in mind to produce branch-friendly code in a high level programming language (I'm mostly interested in C and C++)?</p> </blockquote> <p>Primarily, you should keep in mind that branch mis-prediction is only going to affect you in the most performance critical part of your program and not to worry about it until you've measured and found a problem.</p> <blockquote> <p>But what can I do when some profiler (valgrind, VTune, ...) tells that on line n of foo.cpp I got a branch prediction penalty?</p> </blockquote> <p>Lundin gave very sensible advice</p> <ol> <li>Measure fo find out whether it matters.</li> <li>If it matters, then <ul> <li>Minimize the depth of dependency chains of your calculations. How to do that can be quite complicated and beyond my expertise and there's not much you can do without diving into assembly. What you can do in a high level language is to minimize the number of conditional checks (**). Otherwise you're at the mercy of compiler optimization. Avoiding deep dependency chains also allows more efficient use of out-of-order superscalar processors.</li> <li>Make your branches consistently predictable. The effect of that can be seen in this <a href="https://stackoverflow.com/questions/11227809/why-is-processing-a-sorted-array-faster-than-an-unsorted-array">stackoverflow question</a>. In the question, there is a loop over an array. The loop contains a branch. The branch depends on size of the current element. When the data was sorted, the loop could be demonstrated to be much faster when compiled with a particular compiler and run on a particular cpu. Of course, keeping all your data sorted will also cost cpu time, possibly more than the branch mis-predictions do, so, <em>measure</em>.</li> </ul></li> <li>If it's still a problem, use <a href="https://en.wikipedia.org/wiki/Profile-guided_optimization" rel="nofollow noreferrer">profile guided optimization</a> (if available).</li> </ol> <p>Order of 2. and 3. may be switched. Optimizing your code by hand is a lot of work. On the other hand, gathering the profiling data can be difficult for some programs as well.</p> <p>(**) One way to do that is transform your loops by for example unrolling them. You can also let the optimizer do it automatically. You must measure though, because unrolling will affect the way you interact with the cache and may well end up being a pessimization.</p>
46,777,626
Mathematically producing sphere-shaped hexagonal grid
<p>I am trying to create a shape similar to this, hexagons with 12 pentagons, at an arbitrary size.</p> <p><a href="https://i.stack.imgur.com/F35J0.png" rel="noreferrer"><img src="https://i.stack.imgur.com/F35J0.png" alt="https://i.stack.imgur.com/F35J0.png"></a></p> <p>(<a href="https://stackoverflow.com/questions/28014924/three-js-texturing-terrain-on-a-spherical-hexagon-grid-map">Image Source</a>)</p> <p>The only thing is, I have absolutely no idea what kind of code would be needed to generate it!</p> <p>The goal is to be able to take a point in 3D space and convert it to a position coordinate on the grid, or vice versa and take a grid position and get the relevant vertices for drawing the mesh.</p> <p>I don't even know how one would store the grid positions for this. Does each "triagle section" between 3 pentagons get their own set of 2D coordinates?</p> <p>I will most likely be using C# for this, but I am more interested in which algorithms to use for this and an explanation of how they would work, rather than someone just giving me a piece of code.</p>
47,043,459
3
5
null
2017-10-16 19:20:51.903 UTC
13
2021-08-21 00:52:03.25 UTC
2017-10-24 22:14:44.313 UTC
null
4,441,547
null
4,441,547
null
1
27
algorithm|geometry|computational-geometry|tiling|hexagonal-tiles
21,131
<p>First some analysis of the image in the question: the spherical triangle spanned by neighbouring pentagon centers seems to be equilateral. When five equilateral triangles meet in one corner and cover the whole sphere, this can only be the configuration induced by a <a href="https://en.wikipedia.org/wiki/Icosahedron" rel="noreferrer">icosahedron</a>. So there are 12 pentagons and 20 patches of a triangular cutout of a hexongal mesh mapped to the sphere.</p> <p>So this is a way to construct such a hexagonal grid on the sphere:</p> <ol> <li><p>Create triangular cutout of hexagonal grid: a fixed triangle (I chose (-0.5,0),(0.5,0),(0,sqrt(3)/2) ) gets superimposed a hexagonal grid with desired resolution <code>n</code> s.t. the triangle corners coincide with hexagon centers, see the examples for <code>n = 0,1,2,20</code>: <a href="https://i.stack.imgur.com/dJLjE.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/dJLjE.jpg" alt="enter image description here"></a></p></li> <li><p>Compute corners of <a href="https://en.wikipedia.org/wiki/Icosahedron" rel="noreferrer">icosahedron</a> and define the 20 triangular faces of it (see code below). The corners of the icosahedron define the centers of the pentagons, the faces of the icosahedron define the patches of the mapped hexagonal grids. (The icosahedron gives the finest <em>regular</em> division of the sphere surface into triangles, i.e. a division into congruent equilateral triangles. Other such divisions can be derived from a tetrahedron or an octahedron; then at the corners of the triangles one will have triangles or squares, resp. Furthermore the fewer and bigger triangles would make the inevitable distortion in any mapping of a planar mesh onto a curved surface more visible. So choosing the icosahedron as a basis for the triangular patches helps minimizing the distortion of the hexagons.)</p></li> <li><p>Map triangular cutout of hexagonal grid to spherical triangles corresponding to icosaeder faces: a double-<a href="https://en.wikipedia.org/wiki/Slerp" rel="noreferrer">slerp</a> based on <a href="https://en.wikipedia.org/wiki/Barycentric_coordinate_system" rel="noreferrer">barycentric coordinates</a> does the trick. Below is an illustration of the mapping of a triangular cutout of a hexagonal grid with resolution <code>n = 10</code> onto one spherical triangle (defined by one face of an icosaeder), and an illustration of mapping the grid onto all these spherical triangles covering the whole sphere (different colors for different mappings):</p></li> </ol> <p><a href="https://i.stack.imgur.com/bnn46.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/bnn46.jpg" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/yXEJ9.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/yXEJ9.jpg" alt="enter image description here"></a></p> <p>Here is Python code to generate the corners (coordinates) and triangles (point indices) of an icosahedron:</p> <pre><code>from math import sin,cos,acos,sqrt,pi s,c = 2/sqrt(5),1/sqrt(5) topPoints = [(0,0,1)] + [(s*cos(i*2*pi/5.), s*sin(i*2*pi/5.), c) for i in range(5)] bottomPoints = [(-x,y,-z) for (x,y,z) in topPoints] icoPoints = topPoints + bottomPoints icoTriangs = [(0,i+1,(i+1)%5+1) for i in range(5)] +\ [(6,i+7,(i+1)%5+7) for i in range(5)] +\ [(i+1,(i+1)%5+1,(7-i)%5+7) for i in range(5)] +\ [(i+1,(7-i)%5+7,(8-i)%5+7) for i in range(5)] </code></pre> <p>And here is the Python code to map (points of) the fixed triangle to a spherical triangle using a double slerp:</p> <pre><code># barycentric coords for triangle (-0.5,0),(0.5,0),(0,sqrt(3)/2) def barycentricCoords(p): x,y = p # l3*sqrt(3)/2 = y l3 = y*2./sqrt(3.) # l1 + l2 + l3 = 1 # 0.5*(l2 - l1) = x l2 = x + 0.5*(1 - l3) l1 = 1 - l2 - l3 return l1,l2,l3 from math import atan2 def scalProd(p1,p2): return sum([p1[i]*p2[i] for i in range(len(p1))]) # uniform interpolation of arc defined by p0, p1 (around origin) # t=0 -&gt; p0, t=1 -&gt; p1 def slerp(p0,p1,t): assert abs(scalProd(p0,p0) - scalProd(p1,p1)) &lt; 1e-7 ang0Cos = scalProd(p0,p1)/scalProd(p0,p0) ang0Sin = sqrt(1 - ang0Cos*ang0Cos) ang0 = atan2(ang0Sin,ang0Cos) l0 = sin((1-t)*ang0) l1 = sin(t *ang0) return tuple([(l0*p0[i] + l1*p1[i])/ang0Sin for i in range(len(p0))]) # map 2D point p to spherical triangle s1,s2,s3 (3D vectors of equal length) def mapGridpoint2Sphere(p,s1,s2,s3): l1,l2,l3 = barycentricCoords(p) if abs(l3-1) &lt; 1e-10: return s3 l2s = l2/(l1+l2) p12 = slerp(s1,s2,l2s) return slerp(p12,s3,l3) </code></pre>
63,312,642
How to install node.tar.xz file in linux
<p>I recently downloaded the Nodejs file from the official site and I don't know how to install the Nodejs from a archived file.</p> <p>Please help me how can I install this file so that I can run the &quot;npm&quot; command from the CLI for installation of several packages for my own project.</p>
66,166,866
6
2
null
2020-08-08 06:58:03.22 UTC
22
2022-05-01 00:19:19.77 UTC
null
null
null
null
11,588,855
null
1
50
node.js|node-modules|npm-install
58,666
<p><strong>Steps to download and install node in ubuntu</strong></p> <p>Step 1: Download latest or recommended <strong>node</strong> .tar.xz file from <a href="https://nodejs.org/en/" rel="noreferrer">https://nodejs.org/en/</a></p> <p>or you can download node version 14.15.5 (.tar.xz file) directly from here -&gt;</p> <p><a href="https://nodejs.org/dist/v14.15.5/node-v14.15.5-linux-x64.tar.xz" rel="noreferrer">https://nodejs.org/dist/v14.15.5/node-v14.15.5-linux-x64.tar.xz</a></p> <p>Step 2: Go to the directory in which (.tar.xz file) is downloaded.</p> <p>In my case --&gt; /Download directory</p> <p>Step 3: Update System Repositories</p> <p><code>sudo apt update</code></p> <p>Step 4: Install the package xz-utils</p> <p><code>sudo apt install xz-utils</code></p> <p>Step 5: To Extract the .tar.xz file</p> <p><code>sudo tar -xvf name_of_file</code></p> <p>In my case --&gt; <code>sudo tar -xvf node-v14.15.5-linux-x64.tar.xz</code></p> <p>Step 6: <code>sudo cp -r directory_name/{bin,include,lib,share} /usr/</code></p> <p>In my case --&gt; <code>sudo cp -r node-v14.15.5-linux-x64/{bin,include,lib,share} /usr/</code></p> <p>Step 7: Update the Path <code>export PATH=/usr/node_directory_name/bin:$PATH</code><br /> In my case --&gt; <code>export PATH=/usr/node-v14.15.5-linux-x64/bin:$PATH</code></p> <p>Step 8: Check the node version</p> <p><code>node --version</code></p> <p>Result In my case -&gt; <code>v14.15.5</code></p>
54,298,051
Argument of type '...' is not assignable to parameter of type '...' TS 2345
<p>Given the following:</p> <pre class="lang-js prettyprint-override"><code>interface MyInterface { type: string; } let arr: object[] = [ {type: 'asdf'}, {type: 'qwerty'}] // Alphabetical sort arr.sort((a: MyInterface, b: MyInterface) =&gt; { if (a.type &lt; b.type) return -1; if (a.type &gt; b.type) return 1; return 0; }); </code></pre> <p>Can someone help decipher the TS error:</p> <pre class="lang-js prettyprint-override"><code>// TypeScript Error [ts] Argument of type '(a: MyInterface, b: MyInterface) =&gt; 0 | 1 | -1' is not assignable to parameter of type '(a: object, b: object) =&gt; number'. Types of parameters 'a' and 'a' are incompatible. Type '{}' is missing the following properties from type 'MyInterface': type [2345] </code></pre>
54,299,005
1
6
null
2019-01-21 21:33:07.843 UTC
1
2020-11-26 14:17:55.94 UTC
2020-11-26 14:17:55.94 UTC
null
572,747
null
572,747
null
1
10
typescript
52,447
<p>Here is a simplified example to reproduce the error: </p> <pre><code>interface MyInterface { type: string; } let arr:object[] = [] // Error: "object" is not compatible with MyInterface arr.sort((a: MyInterface, b: MyInterface) =&gt; {}); </code></pre> <p>The reason its an error is because <code>object</code> cannot be assigned to something that is of type <code>MyInterface</code>: </p> <pre><code>interface MyInterface { type: string; } declare let foo: object; declare let bar: MyInterface; // ERROR: object not assignable to MyInterface bar = foo; </code></pre> <p>And the reason this is an error is because <code>object</code> is synonymous with <code>{}</code>. <code>{}</code> does not have the <code>type</code> property and therefore incompatible with MyInterface. </p> <h1>Fix</h1> <p>Perhaps you meant to use <code>any</code> (instead of <code>object</code>). <code>any</code> is compatible with <em>everything</em>. </p> <h1>Better fix</h1> <p>Use the exact type i.e. <code>MyInterface</code></p> <pre><code>interface MyInterface { type: string; } let arr:MyInterface[] = []; // Add correct annotation arr.sort((a: MyInterface, b: MyInterface) =&gt; {}); </code></pre>
1,897,129
How to convert unordered list into nicely styled <select> dropdown using jquery?
<p>How do I convert an unordered list in this format</p> <pre><code>&lt;ul class="selectdropdown"&gt; &lt;li&gt;&lt;a href="one.html" target="_blank"&gt;one&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="two.html" target="_blank"&gt;two&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="three.html" target="_blank"&gt;three&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="four.html" target="_blank"&gt;four&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="five.html" target="_blank"&gt;five&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="six.html" target="_blank"&gt;six&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="seven.html" target="_blank"&gt;seven&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>into a dropdown in this format</p> <pre><code>&lt;select&gt; &lt;option value="one.html" target="_blank"&gt;one&lt;/option&gt; &lt;option value="two.html" target="_blank"&gt;two&lt;/option&gt; &lt;option value="three.html" target="_blank"&gt;three&lt;/option&gt; &lt;option value="four.html" target="_blank"&gt;four&lt;/option&gt; &lt;option value="five.html" target="_blank"&gt;five&lt;/option&gt; &lt;option value="six.html" target="_blank"&gt;six&lt;/option&gt; &lt;option value="seven.html" target="_blank"&gt;seven&lt;/option&gt; &lt;/select&gt; </code></pre> <p>using jQuery?</p> <p><em>Edit:</em> When selecting an entry from the select/dropdown the link should open in a new window or tab automatically. I also want to able to style it like: <a href="http://www.dfc-e.com/metiers/multimedia/opensource/jqtransform/" rel="noreferrer">http://www.dfc-e.com/metiers/multimedia/opensource/jqtransform/</a></p>
1,897,468
5
1
null
2009-12-13 17:36:54.173 UTC
17
2017-04-01 15:20:01.687 UTC
2014-03-24 14:13:33.147 UTC
null
221,381
null
84,201
null
1
20
javascript|jquery|css|xhtml
49,843
<pre><code>$('ul.selectdropdown').each(function() { var select = $(document.createElement('select')).insertBefore($(this).hide()); $('&gt;li a', this).each(function() { var a = $(this).click(function() { if ($(this).attr('target')==='_blank') { window.open(this.href); } else { window.location.href = this.href; } }), option = $(document.createElement('option')).appendTo(select).val(this.href).html($(this).html()).click(function() { a.click(); }); }); }); </code></pre> <p><strong>In reply to your last comment</strong>, I modified it a little bit but haven't tested it. Let me know.</p> <pre><code>$('ul.selectdropdown').each(function() { var list = $(this), select = $(document.createElement('select')).insertBefore($(this).hide()); $('&gt;li a', this).each(function() { var target = $(this).attr('target'), option = $(document.createElement('option')) .appendTo(select) .val(this.href) .html($(this).html()) .click(function(){ if(target==='_blank') { window.open($(this).val()); } else { window.location.href = $(this).val(); } }); }); list.remove(); }); </code></pre>
1,850,162
Is there an open source WebSockets (JavaScript) XMPP library?
<p>Has anyone written an open source XMPP library that uses WebSockets and is meant to be run by a browser?</p>
1,875,848
6
1
null
2009-12-04 22:47:29.157 UTC
19
2013-08-27 20:38:30.387 UTC
null
null
null
null
195,656
null
1
34
javascript|xmpp
18,947
<p>We don't yet have a standard for XMPP over <a href="https://datatracker.ietf.org/doc/html/draft-hixie-thewebsocketprotocol" rel="nofollow noreferrer">WebSockets</a> that the servers can implement, which will be required before the client side can be tackled adequately.</p> <p>The first step is to finish WebSocket standardization. It looks like this may happen in an IETF HyBi working group, which at the time of writing has not yet been approved by the IESG. There was a HyBi Birds-of-a-Feather (BoF) at the Hiroshima IETF meeting a couple of weeks ago (see the <a href="http://trac.tools.ietf.org/bof/trac/wiki/HyBi" rel="nofollow noreferrer">meeting materials</a>), which went pretty well.</p> <p>After WebSockets has a stable reference, and seems to be settling down, the <a href="http://xmpp.org/" rel="nofollow noreferrer">XSF</a> will create a <a href="http://xmpp.org/extensions/" rel="nofollow noreferrer">XEP</a> that binds XMPP to WebSockets, presumably with a stanza per WebSocket frame.</p> <p>Edit: Jack Moffitt has written an IETF <a href="https://datatracker.ietf.org/doc/html/draft-moffitt-xmpp-over-websocket" rel="nofollow noreferrer">Internet-Draft</a> with a first pass at a protocol that can be used. <strong>WARNING</strong>. This is still likely to change drastically. Only implement it if you're willing to rip it out completely later. <strong>WARNING</strong>.</p>
1,518,594
When should one use the following: Amazon EC2, Google App Engine, Microsoft Azure and Salesforce.com?
<p>I am asking this in very general sense. Both from cloud provider and cloud consumer's perspective. Also the question is not for any specific kind of application (in fact the intention is to know which type of applications/domains can fit into which of the cloud slab -SaaS PaaS IaaS).</p> <p>My understanding so far is:</p> <p>IaaS: Raw Hardware (Processors, Networks, Storage).</p> <p>PaaS: OS, System Softwares, Development Framework, Virtual Machines.</p> <p>SaaS: Software Applications.</p> <p>It would be great if Stackoverflower's can share their understanding and experiences of cloud computing concept.</p> <p>EDIT: Ok, I will put it in more specific way -</p> <p>Amazon EC2: You don't have control over hardware layer. But you can take your choice of OS image, Dev Framework (.NET, J2EE, LAMP) and Application and put it on EC2 hardware. Can you deploy an applications built with Google App Engine or Azure on EC2?</p> <p>Google App Engine: You don't have control over hardware and OS and you get a specific Dev Framework to build your application. Can you take any existing Java or Python application and port it to GAE? Or vice versa, can applications that were built on GAE be taken out of GAE and ported to any Application Server like Websphere or Weblogic? </p> <p>Azure: You don't have control over hardware and OS and you get a specific Dev Framework to build your application. Can you take any existing .NET application and port it to Azure? Or vice versa, can applications that were built on Azure be taken out of Azure and ported to any Application Server like Biztalk? </p>
1,519,048
7
3
null
2009-10-05 07:06:03.503 UTC
46
2013-05-14 04:39:13.96 UTC
2009-10-06 05:12:34.503 UTC
null
32,262
null
32,262
null
1
93
google-app-engine|amazon-ec2|azure|cloud|salesforce
11,811
<p>Good question! As you point out, the different offerings fit into different categories:</p> <p>EC2 is Infrastructure as a Service; you get VM instances, and do with them as you wish. Rackspace Cloud Servers are more or less the same.</p> <p>Azure, App Engine, and Salesforce are all Platform as a Service; they offer different levels of integration, though: Azure pretty much lets you run arbitrary background services, while App Engine is oriented around short lived request handler tasks (though it also supports a task queue and scheduled tasks). I'm not terribly familiar with Salesforce's offering, but my understanding is that it's similar to App Engine in some respects, though more specialized for its particular niche.</p> <p>Cloud offerings that fall under Software as a Service are everything from infrastructure pieces like Amazon's Simple Storage Service and SimpleDB through to complete applications like Fog Creek's hosted FogBugz and, of course, StackExchange.</p> <p>A good general rule is that the higher level the offering, the less work you'll have to do, but the more specific it is. If you want a bug tracker, using FogBugz is obviously going to be the least work; building one on top of App Engine or Azure is more work, but provides for more versatility, while building one on top of raw VMs like EC2 is even more work (quite a lot more, in fact), but provides for even more versatility. My general advice is to pick the highest level platform that still meets your requirements, and build from there.</p>
1,609,742
Efficient way of calculating likeness scores of strings when sample size is large?
<p>Let's say that you have a list of 10,000 email addresses, and you'd like to find what some of the closest "neighbors" in this list are - defined as email addresses that are suspiciously close to other email addresses in your list.</p> <p>I'm aware of how to calculate the <a href="http://en.wikipedia.org/wiki/Levenshtein_distance" rel="noreferrer">Levenshtein distance</a> between two strings (thanks to <a href="https://stackoverflow.com/questions/797688/how-to-determine-a-strings-dna-for-likeness-to-another">this question</a>), which will give me a score of how many operations are needed to transform one string into another.</p> <p>Let's say that I define "suspiciously close to another email address" as two strings having a Levenshtein score less than N.</p> <p>Is there a more efficient way to find pairs of strings whose score is lower than this threshold besides comparing every possible string to every other possible string in the list? In other words, can this type of problem be solved quicker than <code>O(n^2)</code>? </p> <p>Is Levenshtein score a poor choice of algorithms for this problem?</p>
1,613,372
8
2
null
2009-10-22 20:24:19.883 UTC
9
2016-01-01 13:36:24.453 UTC
2017-05-23 11:53:22.447 UTC
null
-1
null
4,249
null
1
15
algorithm|string|cluster-analysis|complexity-theory|edit-distance
5,281
<p>Yup - you can find all strings within a given distance of a string in O(log n) time by using a <a href="http://blog.notdot.net/2007/4/Damn-Cool-Algorithms-Part-1-BK-Trees" rel="nofollow noreferrer">BK-Tree</a>. Alternate solutions involving generating every string with distance n may be faster for a levenshtein distance of 1, but the amount of work rapidly balloons out of control for longer distances.</p>
1,448,819
How to install pysqlite?
<p>I am trying to install pysqlite (Python interface to the SQLite). I downloaded the file with the package (pysqlite-2.5.5.tar.gz). And I did the following:</p> <pre><code>gunzip pysqlite-2.5.5.tar.gz tar xvf pysqlite-2.5.5.tar \cd pysqlite-2.5.5 python setup.py install </code></pre> <p>At the last step I have a problem. I get the following error message:</p> <pre><code>error: command 'gcc' failed with exit status 1 </code></pre> <p><a href="http://forums.opensuse.org/applications/400363-gcc-fails-during-pysqlite-install.html" rel="nofollow noreferrer">I found that other peoples also had this problem</a>.</p> <p>As far as I understood in the person had a problem because sqlite2 was not installed. But in my case, I have sqlite3 (I can run it from command line).</p> <p>May be I should change some paths in <code>"setup.cfg"</code>? At the moment I have there:</p> <pre><code>#define= #include_dirs=/usr/local/include #library_dirs=/usr/local/lib libraries=sqlite3 define=SQLITE_OMIT_LOAD_EXTENSION </code></pre> <p>And if I type "which sqlite3" I get:</p> <pre><code>/usr/bin/sqlite3 </code></pre> <p>I saw a similar question here. The answer was "you need sqlite3-dev". But, even if it is the case, how to check if I have <code>sqlite3-dev</code>. And if I do not have it how to get it?</p> <p>Can anybody pleas help me with that problem.</p> <p>Thank you in advance. </p>
1,448,865
11
4
null
2009-09-19 15:55:09.66 UTC
null
2018-07-30 15:23:46.76 UTC
2009-09-19 16:20:18.89 UTC
null
12,855
null
175,960
null
1
4
python|linux|sqlite|gcc|pysqlite
38,873
<blockquote> <p>how to check if I have "sqlite3-dev"</p> </blockquote> <p>That's entirely dependent on what Linux distro you're using -- is it Fedora, Suse, Ubuntu, Gentoo, Mandrake, or which other one out of the dozens out there; there are several packaging strategies and tools used to check which packages are there, get more, and so forth.</p> <p>So, never ask questions about checking, getting or tweaking packages on Linux without specifying the distribution[s] of interest -- it makes it essentially impossible to offer precise, specific help.</p> <p><strong>Edit</strong>: the simplest way I know of getting details about your Linux distribution (works on all the ones I have at hand to try, but I don't have a particularly wide array...;-):</p> <pre><code>$ cat /etc/*-release DISTRIB_CODENAME=hardy DISTRIB_DESCRIPTION="Ubuntu 8.04.2" DISTRIB_ID=Ubuntu DISTRIB_RELEASE=8.04 ...etc, etc... </code></pre> <p>This is probably going to be the contents of file <code>/etc/lsb-release</code>, but I'm suggesting the <code>*-release</code> because I think there may be some other such files involved.</p> <p>Of course, if the need to check your distro applies inside a file or program, reading this file (or files) and locating specific contents will also be quite feasible; but for the purpose of informing would-be helpers about what distro you're using, the <code>cat</code> at the shell prompt is going to be quite sufficient;-).</p>
1,414,951
How do I get elapsed time in milliseconds in Ruby?
<p>If I have a <code>Time</code> object got from :</p> <pre><code>Time.now </code></pre> <p>and later I instantiate another object with that same line, how can I see how many milliseconds have passed? The second object may be created that same minute, over the next minutes or even hours.</p>
1,415,073
11
0
null
2009-09-12 12:00:10.897 UTC
12
2021-12-10 19:12:02.047 UTC
2012-05-05 02:00:01.363 UTC
null
15,168
null
31,610
null
1
104
ruby
129,602
<p>As stated already, you can operate on <code>Time</code> objects as if they were numeric (or floating point) values. These operations result in second resolution which can easily be converted. </p> <p>For example:</p> <pre><code>def time_diff_milli(start, finish) (finish - start) * 1000.0 end t1 = Time.now # arbitrary elapsed time t2 = Time.now msecs = time_diff_milli t1, t2 </code></pre> <p>You will need to decide whether to truncate that or not.</p>
2,003,534
How to find out how many lines of code there are in an Xcode project?
<p>Is there a way to determine how many lines of code an Xcode project contains? I promise not to use such information for managerial measurement or employee benchmarking purposes. ;)</p>
2,003,645
14
2
null
2010-01-05 01:18:55.917 UTC
102
2021-06-13 10:57:25.7 UTC
2016-02-07 19:19:27.833 UTC
user4639281
null
null
153,040
null
1
181
xcode|code-metrics
101,264
<p>Check out <a href="https://github.com/AlDanial/cloc" rel="noreferrer">CLOC</a>.</p> <blockquote> <p>cloc counts blank lines, comment lines, and physical lines of source code in many programming languages.</p> </blockquote> <p>(<a href="http://cloc.sourceforge.net/" rel="noreferrer">Legacy builds are archived on SourceForge</a>.)</p>
1,912,676
I am not able launch JNLP applications using "Java Web Start"?
<p>Up until recently, I was able to launch/open <em>JNLP</em> files in <em>Firefox</em> using <em>Java web start</em>.</p> <p>Don't know what happened all of a sudden <em>JNLP</em> files stopped launching, a splash screen appears saying <em>Java Starting...</em> and then nothing happens. Even the <em>Java Console</em> in the browser and <em>javacpl.cpl</em> applet doesn't open.</p> <p>Tried all possibilities: removed all older version and installed the latest JRE (java version "1.6.0_17"), still it doesn't work.</p> <p>Done some googling for this problem, people suggested to start <em>javaws.exe</em> with <em>-viewer</em> option but same behavior (a splash screen appears saying "Java Starting..." and then disappears)</p> <p>The problem is that I don't know any place (logs etc.) to look for to see what is causing the problem.</p> <p>I am using WinXP SP3, and some of the screenshots below shows further info about my system. I can provide any other detail if required but please help me solve this problem.</p>
18,461,490
17
1
null
2009-12-16 06:18:13.937 UTC
4
2022-04-19 15:14:03.923 UTC
2016-06-01 12:17:33.467 UTC
null
3,956,223
null
108,769
null
1
28
java|jnlp|java-web-start
254,502
<p>Although this question is bit old, the issue was caused by <strong>corrupted ClearType registry setting</strong> and resolved by fixing it, as described in this <a href="http://www.rarst.net/software/cleartype-install4j-java-bug/" rel="nofollow noreferrer">ClearType, install4j and case of Java bug</a> post.</p> <blockquote> <p>ClearType, install4j and case of Java bug Java</p> <p>Do you know what ClearType (font-smoothing technology in Windows) has in common with Java (programming language and one of the recommended frameworks)?</p> <p>Nothing except that they were working together hard at making me miserable for few months. I had some Java software that I couldn’t install. I mean really couldn’t – not even figure out reason or reproduce it on another PC.</p> <p>Recently I was approved for Woopra beta (site analytics service) and it uses desktop client written in Java… I couldn’t install. That got me really mad. :)</p> <p>Story All of the software in question was similar :</p> <p>setup based on install4j; setup crashing with bunch of errors. I was blaming install4j during early (hundred or so) attempts to solve issue. Later I slowly understood that if it was that bugged for that long time – solution would have been created and googled.</p> <p>Tracing After shifting focus from install4j I decided to push Java framework. I was trying stable versions earlier so decided to go for non-stable 1.6 Update 10 Release Candidate.</p> <p>This actually fixed error messages but not crashes. I had also noticed that there was new error log created in directory with setup files. Previously I had only seen logs in Windows temporary directory.</p> <p>New error log was saying following :</p> <p>Could not display the GUI. This application needs access to an X Server. If you have access there is probably an X library missing. ******************************************************************* You can also run this application in console mode without access to an X server by passing the argument -c Very weird to look for X-Server on non-Linux PC, isn’t it? So I decided to try that “-c” argument. And was actually able to install in console mode.</p> <p>Happy ending? Nope. Now installed app was crashing. But it really got me thinking. If console works but graphical interface doesn’t – there must be problem with latter.</p> <p>One more error log (in application folder) was now saying (among other things) :</p> <p>Caused by: java.lang.IllegalArgumentException: -60397977 incompatible with Text-specific LCD contrast key Which successfully googled me description of bug with Java unable to read non-standard ClearType registry setting.</p> <p>Solution I immediately launched ClearType Tuner from Control Panel and found setting showing gibberish number. After correcting it to proper one all problems with Java were instantly gone.</p> <p>cleartypetuner_screenshot Lessons learned Don’t be fast to blame software problems on single application. Even minor and totally unrelated settings can launch deadly chain reactions. Links Jave Runtime Environment <a href="http://www.java.com/en/download/index.jsp" rel="nofollow noreferrer">http://www.java.com/en/download/index.jsp</a></p> <p>ClearType Tuner <a href="http://www.microsoft.com/windowsxp/downloads/powertoys/xppowertoys.mspx" rel="nofollow noreferrer">http://www.microsoft.com/windowsxp/downloads/powertoys/xppowertoys.mspx</a></p> <p>Woopra <a href="http://www.woopra.com/" rel="nofollow noreferrer">http://www.woopra.com/</a></p> <p>install4j <a href="http://www.ej-technologies.com/products/install4j/overview.html" rel="nofollow noreferrer">http://www.ej-technologies.com/products/install4j/overview.html</a></p> </blockquote>
1,590,608
How do I forward-declare a function to avoid `NameError`s for functions defined later?
<p>Is it possible to forward-declare a function in Python? I want to sort a list using my own <code>cmp</code> function before it is declared.</p> <pre><code>print &quot;\n&quot;.join([str(bla) for bla in sorted(mylist, cmp = cmp_configs)]) </code></pre> <p>I've put the definition of <code>cmp_configs</code> method after the invocation. It fails with this error:</p> <pre><code>NameError: name 'cmp_configs' is not defined </code></pre> <p>Is there any way to &quot;declare&quot; <code>cmp_configs</code> method before it's used?</p> <p>Sometimes, it is difficult to reorganize code to avoid this problem. For instance, when implementing some forms of recursion:</p> <pre><code>def spam(): if end_condition(): return end_result() else: return eggs() def eggs(): if end_condition(): return end_result() else: return spam() </code></pre> <p>Where <code>end_condition</code> and <code>end_result</code> have been previously defined.</p> <p>Is the only solution to reorganize the code and always put definitions before invocations?</p>
1,590,657
17
0
null
2009-10-19 19:29:21.987 UTC
36
2022-07-03 17:21:26.16 UTC
2022-07-03 17:16:05.643 UTC
null
365,102
null
1,084
null
1
252
python|forward-declaration
223,507
<p>If you don't want to define a function <em>before</em> it's used, and defining it <em>afterwards</em> is impossible, what about defining it in some other module?</p> <p>Technically you still define it first, but it's clean.</p> <p>You could create a recursion like the following:</p> <pre><code>def foo(): bar() def bar(): foo() </code></pre> <p>Python's functions are anonymous just like values are anonymous, yet they can be bound to a name.</p> <p>In the above code, <code>foo()</code> does not call a function with the name foo, it calls a function that happens to be bound to the name <code>foo</code> at the point the call is made. It is possible to redefine <code>foo</code> somewhere else, and <code>bar</code> would then call the new function.</p> <p>Your problem cannot be solved because it's like asking to get a variable which has not been declared.</p>
1,720,421
How do I concatenate two lists in Python?
<p>How do I concatenate two lists in Python?</p> <p>Example:</p> <pre><code>listone = [1, 2, 3] listtwo = [4, 5, 6] </code></pre> <p>Expected outcome:</p> <pre><code>&gt;&gt;&gt; joinedlist [1, 2, 3, 4, 5, 6] </code></pre>
1,720,432
31
3
null
2009-11-12 07:04:09.05 UTC
404
2022-09-22 20:50:48.6 UTC
2019-03-17 09:15:29.797 UTC
null
63,550
null
206,504
null
1
3,246
python|list|concatenation
3,831,656
<p>Use the <code>+</code> operator to combine the lists:</p> <pre><code>listone = [1, 2, 3] listtwo = [4, 5, 6] joinedlist = listone + listtwo </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; joinedlist [1, 2, 3, 4, 5, 6] </code></pre>
8,760,322
Troubles implementing IEnumerable<T>
<p>I'm trying to write my own (simple) implementation of List. This is what I did so far:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace provaIEnum { class MyList&lt;T&gt; : IEnumerable&lt;T&gt; { private T[] _array; public int Count { get; private set; } public MyList() { /* ... */ } public void Add(T element) { /* ... */ } // ... public IEnumerator&lt;T&gt; GetEnumerator() { for (int i = 0; i &lt; Count; i++) yield return _array[i]; } } </code></pre> <p>I'm getting an error about GetEnumerator though:</p> <blockquote> <p>'provaIEnum.Lista' does not implement interface member 'System.Collections.IEnumerable.GetEnumerator()'. 'provaIEnum.Lista.GetEnumerator()' cannot implement 'System.Collections.IEnumerable.GetEnumerator()' because it does not have the matching return type of 'System.Collections.IEnumerator'.</p> </blockquote> <p>I'm not sure if I understand what VS's trying to tell me and I have no idea how to fix it.</p> <p>Thanks for your time</p>
8,760,350
7
2
null
2012-01-06 15:38:14.217 UTC
2
2015-11-09 12:22:44.773 UTC
null
null
null
null
521,776
null
1
32
c#
23,703
<p>Since <a href="http://msdn.microsoft.com/en-us/library/9eekhta0.aspx"><code>IEnumerable&lt;T&gt;</code></a> implements <a href="http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.aspx"><code>IEnumerable</code></a> you need to implement this interface as well in your class which has the non-generic version of the <a href="http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.getenumerator.aspx">GetEnumerator</a> method. To avoid conflicts you could implement it explicitly:</p> <pre><code>IEnumerator IEnumerable.GetEnumerator() { // call the generic version of the method return this.GetEnumerator(); } public IEnumerator&lt;T&gt; GetEnumerator() { for (int i = 0; i &lt; Count; i++) yield return _array[i]; } </code></pre>
17,784,587
gradient descent using python and numpy
<pre><code>def gradient(X_norm,y,theta,alpha,m,n,num_it): temp=np.array(np.zeros_like(theta,float)) for i in range(0,num_it): h=np.dot(X_norm,theta) #temp[j]=theta[j]-(alpha/m)*( np.sum( (h-y)*X_norm[:,j][np.newaxis,:] ) ) temp[0]=theta[0]-(alpha/m)*(np.sum(h-y)) temp[1]=theta[1]-(alpha/m)*(np.sum((h-y)*X_norm[:,1])) theta=temp return theta X_norm,mean,std=featureScale(X) #length of X (number of rows) m=len(X) X_norm=np.array([np.ones(m),X_norm]) n,m=np.shape(X_norm) num_it=1500 alpha=0.01 theta=np.zeros(n,float)[:,np.newaxis] X_norm=X_norm.transpose() theta=gradient(X_norm,y,theta,alpha,m,n,num_it) print theta </code></pre> <p>My theta from the above code is <code>100.2 100.2</code>, but it should be <code>100.2 61.09</code> in matlab which is correct.</p>
17,796,231
5
1
null
2013-07-22 09:55:30.337 UTC
77
2022-03-12 10:15:25.303 UTC
2014-02-10 11:44:37.617 UTC
null
540,873
null
1,658,129
null
1
64
python|numpy|machine-learning|linear-regression|gradient-descent
190,541
<p>I think your code is a bit too complicated and it needs more structure, because otherwise you'll be lost in all equations and operations. In the end this regression boils down to four operations:</p> <ol> <li>Calculate the hypothesis h = X * theta</li> <li>Calculate the loss = h - y and maybe the squared cost (loss^2)/2m</li> <li>Calculate the gradient = X' * loss / m</li> <li>Update the parameters theta = theta - alpha * gradient</li> </ol> <p>In your case, I guess you have confused <code>m</code> with <code>n</code>. Here <code>m</code> denotes the number of examples in your training set, not the number of features.</p> <p>Let's have a look at my variation of your code:</p> <pre><code>import numpy as np import random # m denotes the number of examples here, not the number of features def gradientDescent(x, y, theta, alpha, m, numIterations): xTrans = x.transpose() for i in range(0, numIterations): hypothesis = np.dot(x, theta) loss = hypothesis - y # avg cost per example (the 2 in 2*m doesn't really matter here. # But to be consistent with the gradient, I include it) cost = np.sum(loss ** 2) / (2 * m) print("Iteration %d | Cost: %f" % (i, cost)) # avg gradient per example gradient = np.dot(xTrans, loss) / m # update theta = theta - alpha * gradient return theta def genData(numPoints, bias, variance): x = np.zeros(shape=(numPoints, 2)) y = np.zeros(shape=numPoints) # basically a straight line for i in range(0, numPoints): # bias feature x[i][0] = 1 x[i][1] = i # our target variable y[i] = (i + bias) + random.uniform(0, 1) * variance return x, y # gen 100 points with a bias of 25 and 10 variance as a bit of noise x, y = genData(100, 25, 10) m, n = np.shape(x) numIterations= 100000 alpha = 0.0005 theta = np.ones(n) theta = gradientDescent(x, y, theta, alpha, m, numIterations) print(theta) </code></pre> <p>At first I create a small random dataset which should look like this:</p> <p><img src="https://i.stack.imgur.com/xCyZn.png" alt="Linear Regression"></p> <p>As you can see I also added the generated regression line and formula that was calculated by excel.</p> <p>You need to take care about the intuition of the regression using gradient descent. As you do a complete batch pass over your data X, you need to reduce the m-losses of every example to a single weight update. In this case, this is the average of the sum over the gradients, thus the division by <code>m</code>. </p> <p>The next thing you need to take care about is to track the convergence and adjust the learning rate. For that matter you should always track your cost every iteration, maybe even plot it.</p> <p>If you run my example, the theta returned will look like this:</p> <pre><code>Iteration 99997 | Cost: 47883.706462 Iteration 99998 | Cost: 47883.706462 Iteration 99999 | Cost: 47883.706462 [ 29.25567368 1.01108458] </code></pre> <p>Which is actually quite close to the equation that was calculated by excel (y = x + 30). Note that as we passed the bias into the first column, the first theta value denotes the bias weight.</p>
18,202,818
Classes vs. Functions
<p>Functions are easy to understand even for someone without any programming experience, but with a fair math background. On the other hand, classes seem to be more difficult to grasp.</p> <p>Let's say I want to make a class/function that calculates the age of a person given his/her birthday year and the current year. Should I create a class for this, or a function? Or is the choice dependant to the scenario?</p> <p>P.S. I am working on Python, but I guess the question is generic.</p>
18,202,865
8
3
null
2013-08-13 07:12:57.92 UTC
57
2021-05-07 17:58:58.117 UTC
2013-08-13 08:13:47.853 UTC
null
126,214
null
1,585,017
null
1
107
class|function|oop
168,107
<p>Create a function. Functions <em>do</em> specific things, classes <em>are</em> specific things.</p> <p>Classes often have methods, which are functions that are associated with a particular class, and do things associated with the thing that the class is - but if all you want is to do something, a function is all you need.</p> <p>Essentially, a class is a way of grouping functions (as methods) and data (as properties) into a logical unit revolving around a certain kind of thing. If you don't need that grouping, there's no need to make a class.</p>
7,006,888
How to get combobox not to accept user input in Excel-Vba?
<p>Does anyone know what the properties are in the combobox that I can manipulate in order not to allow the user to key/type in any data?</p>
7,007,075
3
2
null
2011-08-10 06:49:03.527 UTC
5
2014-10-10 21:15:03.63 UTC
2011-08-10 06:55:08.963 UTC
null
13,295
null
694,831
null
1
24
excel|vba|controls|excel-2007
90,493
<p>Set the the Style of the combobox to <code>2 - fmStyleDropDownList</code>. This will disallow user input, and will also prevent (combobox).value changes via macro. </p>
6,463,459
When to use Observable.FromEventPattern rather than Observable.FromEvent?
<p>We've got a client calling off to a TIBCO EMS queue and are wiring up the events like this:</p> <pre><code>var msgConsumer = _session.CreateConsumer(responseQueue); var response = Observable.FromEvent&lt;EMSMessageHandler,EMSMessageEventArgs&gt; (h =&gt; msgConsumer.MessageHandler += h, h =&gt; msgConsumer.MessageHandler -= h) .Where(arg =&gt; arg.Message.CorrelationID == message.MessageID); </code></pre> <p>When I call <code>response.Subscribe(...)</code> I get System.ArgumentException "Error binding to target method."</p> <p>I can make it work with <code>Observable.FromEventPattern&lt;EMSMessageEventArgs&gt;(msgConsumer, "MessageHandler")</code> but then it's got the event as a string and just not as clean. </p> <p>Also I have <code>IObservable&lt;EventPattern&lt;EMSMessageEventArgs&gt;&gt;</code> rather than <code>IObservable&lt;EMSMessageEventArgs&gt;</code> </p> <p>What I'd like to understand is: when should I use <code>FromEvent</code> over <code>FromEventPattern</code>? It seems a bit trial and error.</p>
6,468,952
3
3
null
2011-06-24 04:41:30.123 UTC
12
2015-11-27 11:34:10.573 UTC
2015-11-27 11:34:10.573 UTC
user1400995
null
null
5,130
null
1
60
c#|system.reactive
26,616
<p>"Use FromEvent for events structurally don't look like a .NET event pattern (i.e. not based on sender, event args), and use FromEventPattern for the pattern-based ones." - <a href="http://social.msdn.microsoft.com/Forums/en-CA/rx/thread/5f4df41c-6df1-42be-b7bb-bbf072143c24" rel="noreferrer">Bart De Smet (Rx team)</a></p>
23,469,051
JavaScript Alert Selected Option of html drop down
<p>I have searched around and tried various things but I cannot find a way to get javascript to alert my chosen option. All that happens with what I have is in the console debugging section at the bottom of the page it says " 'null' is not an object (evaluating 'x.options') " which suggests to me that my variable x is not getting any value in the first place, here is my code:</p> <p>html</p> <pre><code> &lt;select id=“test-dropdown” onchange=“choice1()”&gt; &lt;option value=“1”&gt;One&lt;/option&gt; &lt;option value=“2”&gt;Two&lt;/option&gt; &lt;option value=“3”&gt;Three&lt;/option&gt; &lt;/select&gt; </code></pre> <p>javascript</p> <pre><code> function choice1() { var x = document.getElementById(“test-dropdown”); alert(x.options[x.selectedIndex].value); } </code></pre> <p>I would be very thankful if someone could solve the problem or point me in the direction of where this question has been answered before.</p>
23,470,017
2
3
null
2014-05-05 09:27:16.647 UTC
1
2014-05-05 10:15:59.757 UTC
null
null
null
null
3,603,650
null
1
5
javascript|html
49,358
<p>I believe you want to alert the text of the chosen element, you can do it by doing this in a shorter way too</p> <p>HTML: </p> <pre><code>&lt;select id="test-dropdown" onchange="choice1(this)"&gt; &lt;option value="1"&gt;One&lt;/option&gt; &lt;option value="2"&gt;Two&lt;/option&gt; &lt;option value="3"&gt;Three&lt;/option&gt; &lt;/select&gt; </code></pre> <p>JavaScript: </p> <pre><code>function choice1(select) { alert(select.options[select.selectedIndex].text); } </code></pre> <p>Fiddle: <a href="http://jsfiddle.net/AwFE3/" rel="noreferrer">http://jsfiddle.net/AwFE3/</a></p>
34,937,724
Running bash scripts with npm
<p>I want to try using npm to run my various build tasks for a web application. I know I can do this by adding a <code>scripts</code> field to my <code>package.json</code> like so:</p> <pre><code>"scripts": { "build": "some build command" }, </code></pre> <p>This gets unwieldy when you have more complex commands with a bunch of options. Is it possible to move these commands to a bash script or something along those lines? Something like:</p> <pre><code>"scripts": { "build": "build.sh" }, </code></pre> <p>where <code>npm run build</code> would execute the commands in the <code>build.sh</code> file?</p> <p>Reading through <a href="http://substack.net/task_automation_with_npm_run" rel="noreferrer">this</a> post it seems like it is, but I'm not clear on exactly where I'm supposed to drop my <code>build.sh</code> file or if I'm missing something.</p>
34,938,559
4
8
null
2016-01-22 01:54:33.847 UTC
25
2022-08-27 03:04:43.713 UTC
null
null
null
null
2,962,432
null
1
115
node.js|bash|shell|npm
137,251
<p>Its totally possible... </p> <pre><code>"scripts": { "build": "./build.sh" }, </code></pre> <p>also, make sure you put a hash bang at the top of your bash file <code>#!/usr/bin/env bash</code></p> <p>also make sure you have permissions to execute the file </p> <pre><code>chmod +x ./build.sh </code></pre> <p>Finally, the command to run build in npm would be </p> <pre><code>npm run build </code></pre>
35,127,060
How to implement atoi using SIMD?
<p>I'd like to try writing an atoi implementation using SIMD instructions, to be included in <a href="http://rapidjson.org/" rel="noreferrer">RapidJSON</a> (a C++ JSON reader/writer library). It currently has some SSE2 and SSE4.2 optimizations in other places.</p> <p>If it's a speed gain, multiple <code>atoi</code> results can be done in parallel. The strings are originally coming from a buffer of JSON data, so a multi-atoi function will have to do any required swizzling.</p> <p>The algorithm I came up with is the following:</p> <ol> <li>I can initialize a vector of length N in the following fashion: [10^N..10^1]</li> <li>I convert each character in the buffer to an integer and place them in another vector.</li> <li>I take each number in the significant digits vector and multiply it by the matching number in the numbers vector and sum the results. </li> </ol> <p>I'm targeting x86 and x86-64 architectures.</p> <p>I know that AVX2 supports three operand Fused Multiply-Add so I'll be able to perform Sum = Number * Significant Digit + Sum.<br> That's where I got so far.<br> Is my algorithm correct? Is there a better way?<br> Is there a reference implementation for atoi using any SIMD instructions set?</p>
35,132,718
2
11
null
2016-02-01 09:33:51.45 UTC
12
2017-11-12 12:36:20.863 UTC
2016-02-01 14:18:17.533 UTC
null
224,132
null
85,140
null
1
29
c++|x86|sse|simd|atoi
6,536
<p>The algorithm and its implementation is finished now. It's complete and (moderately) tested (<em>Updated for less constant memory usage and tolerating plus-char</em>).</p> <p><strong>The properties of this code are as follows:</strong></p> <ul> <li>Works for <code>int</code> and <code>uint</code>, from <code>MIN_INT=-2147483648</code> to <code>MAX_INT=2147483647</code> and from <code>MIN_UINT=0</code> to <code>MAX_UINT=4294967295</code></li> <li>A leading <code>'-'</code> char indicates a negative number (as sensible), a leading <code>'+'</code> char is ignored</li> <li>Leading zeros (with or without sign char) are ignored</li> <li>Overflow is ignored - bigger numbers just wraparound</li> <li>Zero length strings result in value <code>0 = -0</code></li> <li>Invalid characters are recognized and the conversion ends at the first invalid char</li> <li>At least 16 bytes after the last leading zero must be accessible and possible security implications of reading after EOS are left to the caller</li> <li>Only SSE4.2 is needed</li> </ul> <p><strong>About this implementation:</strong></p> <ul> <li>This code sample can be run with GNU Assembler(<code>as</code>) using <code>.intel_syntax noprefix</code> at the beginning</li> <li>Data footprint for constants is 64 bytes (4*128 bit XMM) equalling one cache line.</li> <li>Code footprint is 46 instructions with 51 micro-Ops and 64 cycles latency</li> <li>One loop for removal of leading zeros, otherwise no jumps except for error handling, so...</li> <li>Time complexity is O(1)</li> </ul> <p><strong>The approach of the algorithm:</strong> </p> <pre><code>- Pointer to number string is expected in ESI - Check if first char is '-', then indicate if negative number in EDX (**A**) - Check for leading zeros and EOS (**B**) - Check string for valid digits and get strlen() of valid chars (**C**) - Reverse string so that power of 10^0 is always at BYTE 15 10^1 is always at BYTE 14 10^2 is always at BYTE 13 10^3 is always at BYTE 12 10^4 is always at BYTE 11 ... and mask out all following chars (**D**) - Subtract saturated '0' from each of the 16 possible chars (**1**) - Take 16 consecutive byte-values and and split them to WORDs in two XMM-registers (**2**) P O N M L K J I | H G F E D C B A -&gt; H G F E | D C B A (XMM0) P O N M | L K J I (XMM1) - Multiply each WORD by its place-value modulo 10000 (1,10,100,1000) (factors smaller then MAX_WORD, 4 factors per QWORD/halfXMM) (**2**) so we can horizontally combine twice before another multiply. The PMADDWD instruction can do this and the next step: - Horizontally add adjacent WORDs to DWORDs (**3**) H*1000+G*100 F*10+E*1 | D*1000+C*100 B*10+A*1 (XMM0) P*1000+O*100 N*10+M*1 | L*1000+K*100 J*10+I*1 (XMM1) - Horizontally add adjacent DWORDs from XMM0 and XMM1 to XMM0 (**4**) xmmDst[31-0] = xmm0[63-32] + xmm0[31-0] xmmDst[63-32] = xmm0[127-96] + xmm0[95-64] xmmDst[95-64] = xmm1[63-32] + xmm1[31-0] xmmDst[127-96] = xmm1[127-96] + xmm1[95-64] - Values in XMM0 are multiplied with the factors (**5**) P*1000+O*100+N*10+M*1 (DWORD factor 1000000000000 = too big for DWORD, but possibly useful for QWORD number strings) L*1000+K*100+J*10+I*1 (DWORD factor 100000000) H*1000+G*100+F*10+E*1 (DWORD factor 10000) D*1000+C*100+B*10+A*1 (DWORD factor 1) - The last step is adding these four DWORDs together with 2*PHADDD emulated by 2*(PSHUFD+PADDD) - xmm0[31-0] = xmm0[63-32] + xmm0[31-0] (**6**) xmm0[63-32] = xmm0[127-96] + xmm0[95-64] (the upper QWORD contains the same and is ignored) - xmm0[31-0] = xmm0[63-32] + xmm0[31-0] (**7**) - If the number is negative (indicated in EDX by 000...0=pos or 111...1=neg), negate it(**8**) </code></pre> <p><strong>And the sample implementation in GNU Assembler with intel syntax:</strong></p> <pre><code>.intel_syntax noprefix .data .align 64 ddqDigitRange: .byte '0','9',0,0,0,0,0,0,0,0,0,0,0,0,0,0 ddqShuffleMask:.byte 15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0 ddqFactor1: .word 1,10,100,1000, 1,10,100,1000 ddqFactor2: .long 1,10000,100000000,0 .text _start: mov esi, lpInputNumberString /* (**A**) indicate negative number in EDX */ mov eax, -1 xor ecx, ecx xor edx, edx mov bl, byte ptr [esi] cmp bl, '-' cmove edx, eax cmp bl, '+' cmove ecx, eax sub esi, edx sub esi, ecx /* (**B**)remove leading zeros */ xor eax,eax /* return value ZERO */ remove_leading_zeros: inc esi cmp byte ptr [esi-1], '0' /* skip leading zeros */ je remove_leading_zeros cmp byte ptr [esi-1], 0 /* catch empty string/number */ je FINISH dec esi /* check for valid digit-chars and invert from front to back */ pxor xmm2, xmm2 movdqa xmm0, xmmword ptr [ddqDigitRange] movdqu xmm1, xmmword ptr [esi] pcmpistri xmm0, xmm1, 0b00010100 /* (**C**) iim8=Unsigned bytes, Ranges, Negative Polarity(-), returns strlen() in ECX */ jo FINISH /* if first char is invalid return 0 - prevent processing empty string - 0 is still in EAX */ mov al , '0' /* value to subtract from chars */ sub ecx, 16 /* len-16=negative to zero for shuffle mask */ movd xmm0, ecx pshufb xmm0, xmm2 /* broadcast CL to all 16 BYTEs */ paddb xmm0, xmmword ptr [ddqShuffleMask] /* Generate permute mask for PSHUFB - all bytes &lt; 0 have highest bit set means place gets zeroed */ pshufb xmm1, xmm0 /* (**D**) permute - now from highest to lowest BYTE are factors 10^0, 10^1, 10^2, ... */ movd xmm0, eax /* AL='0' from above */ pshufb xmm0, xmm2 /* broadcast AL to XMM0 */ psubusb xmm1, xmm0 /* (**1**) */ movdqa xmm0, xmm1 punpcklbw xmm0, xmm2 /* (**2**) */ punpckhbw xmm1, xmm2 pmaddwd xmm0, xmmword ptr [ddqFactor1] /* (**3**) */ pmaddwd xmm1, xmmword ptr [ddqFactor1] phaddd xmm0, xmm1 /* (**4**) */ pmulld xmm0, xmmword ptr [ddqFactor2] /* (**5**) */ pshufd xmm1, xmm0, 0b11101110 /* (**6**) */ paddd xmm0, xmm1 pshufd xmm1, xmm0, 0b01010101 /* (**7**) */ paddd xmm0, xmm1 movd eax, xmm0 /* negate if negative number */ add eax, edx /* (**8**) */ xor eax, edx FINISH: /* EAX is return (u)int value */ </code></pre> <p><strong>The result of Intel-IACA Throughput Analysis for Haswell 32-bit:</strong></p> <pre><code>Throughput Analysis Report -------------------------- Block Throughput: 16.10 Cycles Throughput Bottleneck: InterIteration Port Binding In Cycles Per Iteration: --------------------------------------------------------------------------------------- | Port | 0 - DV | 1 | 2 - D | 3 - D | 4 | 5 | 6 | 7 | --------------------------------------------------------------------------------------- | Cycles | 9.5 0.0 | 10.0 | 4.5 4.5 | 4.5 4.5 | 0.0 | 11.1 | 11.4 | 0.0 | --------------------------------------------------------------------------------------- N - port number or number of cycles resource conflict caused delay, DV - Divider pipe (on port 0) D - Data fetch pipe (on ports 2 and 3), CP - on a critical path F - Macro Fusion with the previous instruction occurred * - instruction micro-ops not bound to a port ^ - Micro Fusion happened # - ESP Tracking sync uop was issued @ - SSE instruction followed an AVX256 instruction, dozens of cycles penalty is expected ! - instruction not supported, was not accounted in Analysis | Num Of | Ports pressure in cycles | | | Uops | 0 - DV | 1 | 2 - D | 3 - D | 4 | 5 | 6 | 7 | | --------------------------------------------------------------------------------- | 0* | | | | | | | | | | xor eax, eax | 0* | | | | | | | | | | xor ecx, ecx | 0* | | | | | | | | | | xor edx, edx | 1 | | 0.1 | | | | | 0.9 | | | dec eax | 1 | | | 0.5 0.5 | 0.5 0.5 | | | | | CP | mov bl, byte ptr [esi] | 1 | | | | | | | 1.0 | | CP | cmp bl, 0x2d | 2 | 0.1 | 0.2 | | | | | 1.8 | | CP | cmovz edx, eax | 1 | 0.1 | 0.5 | | | | | 0.4 | | CP | cmp bl, 0x2b | 2 | 0.5 | 0.2 | | | | | 1.2 | | CP | cmovz ecx, eax | 1 | 0.2 | 0.5 | | | | | 0.2 | | CP | sub esi, edx | 1 | 0.2 | 0.5 | | | | | 0.3 | | CP | sub esi, ecx | 0* | | | | | | | | | | xor eax, eax | 1 | 0.3 | 0.1 | | | | | 0.6 | | CP | inc esi | 2^ | 0.3 | | 0.5 0.5 | 0.5 0.5 | | | 0.6 | | | cmp byte ptr [esi-0x1], 0x30 | 0F | | | | | | | | | | jz 0xfffffffb | 2^ | 0.6 | | 0.5 0.5 | 0.5 0.5 | | | 0.4 | | | cmp byte ptr [esi-0x1], 0x0 | 0F | | | | | | | | | | jz 0x8b | 1 | 0.1 | 0.9 | | | | | | | CP | dec esi | 1 | | | 0.5 0.5 | 0.5 0.5 | | | | | | movdqa xmm0, xmmword ptr [0x80492f0] | 1 | | | 0.5 0.5 | 0.5 0.5 | | | | | CP | movdqu xmm1, xmmword ptr [esi] | 0* | | | | | | | | | | pxor xmm2, xmm2 | 3 | 2.0 | 1.0 | | | | | | | CP | pcmpistri xmm0, xmm1, 0x14 | 1 | | | | | | | 1.0 | | | jo 0x6e | 1 | | 0.4 | | | | 0.1 | 0.5 | | | mov al, 0x30 | 1 | 0.1 | 0.5 | | | | 0.1 | 0.3 | | CP | sub ecx, 0x10 | 1 | | | | | | 1.0 | | | CP | movd xmm0, ecx | 1 | | | | | | 1.0 | | | CP | pshufb xmm0, xmm2 | 2^ | | 1.0 | 0.5 0.5 | 0.5 0.5 | | | | | CP | paddb xmm0, xmmword ptr [0x80492c0] | 1 | | | | | | 1.0 | | | CP | pshufb xmm1, xmm0 | 1 | | | | | | 1.0 | | | | movd xmm0, eax | 1 | | | | | | 1.0 | | | | pshufb xmm0, xmm2 | 1 | | 1.0 | | | | | | | CP | psubusb xmm1, xmm0 | 0* | | | | | | | | | CP | movdqa xmm0, xmm1 | 1 | | | | | | 1.0 | | | CP | punpcklbw xmm0, xmm2 | 1 | | | | | | 1.0 | | | | punpckhbw xmm1, xmm2 | 2^ | 1.0 | | 0.5 0.5 | 0.5 0.5 | | | | | CP | pmaddwd xmm0, xmmword ptr [0x80492d0] | 2^ | 1.0 | | 0.5 0.5 | 0.5 0.5 | | | | | | pmaddwd xmm1, xmmword ptr [0x80492d0] | 3 | | 1.0 | | | | 2.0 | | | CP | phaddd xmm0, xmm1 | 3^ | 2.0 | | 0.5 0.5 | 0.5 0.5 | | | | | CP | pmulld xmm0, xmmword ptr [0x80492e0] | 1 | | | | | | 1.0 | | | CP | pshufd xmm1, xmm0, 0xee | 1 | | 1.0 | | | | | | | CP | paddd xmm0, xmm1 | 1 | | | | | | 1.0 | | | CP | pshufd xmm1, xmm0, 0x55 | 1 | | 1.0 | | | | | | | CP | paddd xmm0, xmm1 | 1 | 1.0 | | | | | | | | CP | movd eax, xmm0 | 1 | | | | | | | 1.0 | | CP | add eax, edx | 1 | | | | | | | 1.0 | | CP | xor eax, edx Total Num Of Uops: 51 </code></pre> <p><strong>The result of Intel-IACA Latency Analysis for Haswell 32-bit:</strong></p> <pre><code>Latency Analysis Report --------------------------- Latency: 64 Cycles N - port number or number of cycles resource conflict caused delay, DV - Divider pipe (on port 0) D - Data fetch pipe (on ports 2 and 3), CP - on a critical path F - Macro Fusion with the previous instruction occurred * - instruction micro-ops not bound to a port ^ - Micro Fusion happened # - ESP Tracking sync uop was issued @ - Intel(R) AVX to Intel(R) SSE code switch, dozens of cycles penalty is expected ! - instruction not supported, was not accounted in Analysis The Resource delay is counted since all the sources of the instructions are ready and until the needed resource becomes available | Inst | Resource Delay In Cycles | | | Num | 0 - DV | 1 | 2 - D | 3 - D | 4 | 5 | 6 | 7 | FE | | ------------------------------------------------------------------------- | 0 | | | | | | | | | | | xor eax, eax | 1 | | | | | | | | | | | xor ecx, ecx | 2 | | | | | | | | | | | xor edx, edx | 3 | | | | | | | | | | | dec eax | 4 | | | | | | | | | 1 | CP | mov bl, byte ptr [esi] | 5 | | | | | | | | | | CP | cmp bl, 0x2d | 6 | | | | | | | | | | CP | cmovz edx, eax | 7 | | | | | | | | | | CP | cmp bl, 0x2b | 8 | | | | | | | 1 | | | CP | cmovz ecx, eax | 9 | | | | | | | | | | CP | sub esi, edx | 10 | | | | | | | | | | CP | sub esi, ecx | 11 | | | | | | | | | 3 | | xor eax, eax | 12 | | | | | | | | | | CP | inc esi | 13 | | | | | | | | | | | cmp byte ptr [esi-0x1], 0x30 | 14 | | | | | | | | | | | jz 0xfffffffb | 15 | | | | | | | | | | | cmp byte ptr [esi-0x1], 0x0 | 16 | | | | | | | | | | | jz 0x8b | 17 | | | | | | | | | | CP | dec esi | 18 | | | | | | | | | 4 | | movdqa xmm0, xmmword ptr [0x80492f0] | 19 | | | | | | | | | | CP | movdqu xmm1, xmmword ptr [esi] | 20 | | | | | | | | | 5 | | pxor xmm2, xmm2 | 21 | | | | | | | | | | CP | pcmpistri xmm0, xmm1, 0x14 | 22 | | | | | | | | | | | jo 0x6e | 23 | | | | | | | | | 6 | | mov al, 0x30 | 24 | | | | | | | | | | CP | sub ecx, 0x10 | 25 | | | | | | | | | | CP | movd xmm0, ecx | 26 | | | | | | | | | | CP | pshufb xmm0, xmm2 | 27 | | | | | | | | | 7 | CP | paddb xmm0, xmmword ptr [0x80492c0] | 28 | | | | | | | | | | CP | pshufb xmm1, xmm0 | 29 | | | | | | 1 | | | | | movd xmm0, eax | 30 | | | | | | 1 | | | | | pshufb xmm0, xmm2 | 31 | | | | | | | | | | CP | psubusb xmm1, xmm0 | 32 | | | | | | | | | | CP | movdqa xmm0, xmm1 | 33 | | | | | | | | | | CP | punpcklbw xmm0, xmm2 | 34 | | | | | | | | | | | punpckhbw xmm1, xmm2 | 35 | | | | | | | | | 9 | CP | pmaddwd xmm0, xmmword ptr [0x80492d0] | 36 | | | | | | | | | 9 | | pmaddwd xmm1, xmmword ptr [0x80492d0] | 37 | | | | | | | | | | CP | phaddd xmm0, xmm1 | 38 | | | | | | | | | 10 | CP | pmulld xmm0, xmmword ptr [0x80492e0] | 39 | | | | | | | | | | CP | pshufd xmm1, xmm0, 0xee | 40 | | | | | | | | | | CP | paddd xmm0, xmm1 | 41 | | | | | | | | | | CP | pshufd xmm1, xmm0, 0x55 | 42 | | | | | | | | | | CP | paddd xmm0, xmm1 | 43 | | | | | | | | | | CP | movd eax, xmm0 | 44 | | | | | | | | | | CP | add eax, edx | 45 | | | | | | | | | | CP | xor eax, edx Resource Conflict on Critical Paths: ----------------------------------------------------------------- | Port | 0 - DV | 1 | 2 - D | 3 - D | 4 | 5 | 6 | 7 | ----------------------------------------------------------------- | Cycles | 0 0 | 0 | 0 0 | 0 0 | 0 | 0 | 1 | 0 | ----------------------------------------------------------------- List Of Delays On Critical Paths ------------------------------- 6 --&gt; 8 1 Cycles Delay On Port6 </code></pre> <p><strong>An alternative handling</strong> suggested in comments by Peter Cordes is replacing the last two <code>add+xor</code> instructions by an <code>imul</code>. <em>This concentration of OpCodes is likely to be superior.</em> Unfortunately IACA doesn't support that instruction and throws a <code>! - instruction not supported, was not accounted in Analysis</code> comment. Nevertheless, although I like the reduction of OpCodes and reduction from (2uops, 2c latency) to (1 uop, 3c latency - "worse latency, but still one m-op on AMD"), I prefer to leave it to the implementer which way to choose. I haven't checked if the following code is sufficient for parsing any number. It is just mentioned for completeness and code modifications in other parts may be necessary (especially handling positive numbers).</p> <p>The alternative may be replacing the last two lines with:</p> <pre><code> ... /* negate if negative number */ imul eax, edx FINISH: /* EAX is return (u)int value */ </code></pre>
34,354,401
"The remote certificate is invalid according to the validation procedure" using HttpClient
<p>Can't solve the problem with certificate validation. </p> <p>There's Web API server, that uses HTTPS to handle requests. Server's certificate has this certification path: RCA (root) -> ICA (intermediate) -> Web API server. RCA, ICA and Web API server are members of the same Active Directory domain.</p> <p>Client application (desktop, computer is joined to the same domain) uses <code>HttpClient</code> to communicate with server and supports two scenarios:</p> <ul> <li>connected to corporate network;</li> <li>disconnected from corporate network (Internet access).</li> </ul> <p>Both scenarios use basic authentication.<br> RCA and ICA certificates are placed in "Trusted Root Certification Authorities" and "Intermediate Certification Authorities" respectively for local computer account. RCA certificate is self-signed.</p> <p>Now, when client is connected to corporate network, certificate validation works as expected, and user can "talk" to Web API.</p> <p>When client is disconnected (only Internet connection is available), certificate validation fails with <code>AuthenticationException</code> ("The remote certificate is invalid according to the validation procedure").</p> <p>I don't want to turn off certificate validation completely, but just need a way to tell validation system, that this particular certificate is valid. Also, client application uses SignalR, which by default uses it's own transport. Hence, <a href="https://stackoverflow.com/a/1386568/580053">this</a> and <a href="https://stackoverflow.com/a/12553854/580053">this</a> are not options.</p> <p>Why placing RCA an ICA certificates to "Trusted..." and "Intermediate..." folders doesn't help?</p> <p>Is there any workaround?</p>
34,355,415
3
7
null
2015-12-18 11:16:42.617 UTC
4
2021-05-10 03:33:20.777 UTC
2017-05-23 11:59:52.66 UTC
null
-1
null
580,053
null
1
21
c#|ssl-certificate|dotnet-httpclient
38,951
<p>The issue you are experiencing is because the subject CN presented by the certificate does not match the host name in the Uri.</p> <p>Make sure that the certificate bound to the public IP address of the host does have a matching CN with the host name you are using to access the resource.</p> <p>To easily verify, open the Url in a browser and view the certificate. The <em>Issued to</em> field should contain a FQDN and match the host name part in the Uri. In your case, it does not.</p>
27,808,734
JDK8 - Error "class file for javax.interceptor.InterceptorBinding not found" when trying to generate javadoc using Maven javadoc plugin
<p>I am using JDK8 (tried it on my Eclipse workspace with Win x64 u25 JDK + on Linux launched by Jenkins - jdk-8u20-linux-x64, same problem for both).</p> <p>I have multi-module Maven project (I am launching Maven goal "javadoc:aggregate" from a main module with packaging type "pom").</p> <p>Pom build section looks like this:</p> <pre class="lang-xml prettyprint-override"><code>&lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt; &lt;configuration&gt; &lt;source&gt;1.8&lt;/source&gt; &lt;target&gt;1.8&lt;/target&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-javadoc-plugin&lt;/artifactId&gt; &lt;configuration&gt; &lt;additionalparam&gt;-Xdoclint:none&lt;/additionalparam&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; </code></pre> <p>I always receive error:</p> <pre class="lang-none prettyprint-override"><code>[ERROR] Failed to execute goal org.apache.maven.plugins:maven-javadoc-plugin:2.10.1:aggregate (default-cli) on project uloan-global-build: An error has occurred in JavaDocs report generation: [ERROR] Exit code: 1 - javadoc: error - com.sun.tools.doclets.internal.toolkit.util.DocletAbortException: com.sun.tools.doclets.internal.toolkit.util.DocletAbortException: com.sun.tools.doclets.internal.toolkit.util.DocletAbortException: com.sun.tools.javac.code.Symbol$CompletionFailure: class file for javax.interceptor.InterceptorBinding not found [ERROR] [ERROR] Command line was: /usr/java/jdk1.8.0_20/jre/../bin/javadoc @options @packages </code></pre> <p>I have tried everything possible and tried to search on Google for a long time, but no success. I have found links, where people had similar problems, but without any information about possible solution:</p> <p><a href="http://marc.info/?l=maven-user&amp;m=139615350913286&amp;w=2">http://marc.info/?l=maven-user&amp;m=139615350913286&amp;w=2</a></p> <p><a href="http://mail-archives.apache.org/mod_mbox/maven-users/201409.mbox/%[email protected]%3E">http://mail-archives.apache.org/mod_mbox/maven-users/201409.mbox/%[email protected]%3E</a> (suggesting to update JDK8 to > update 20, which I did, but problem is still the same).</p> <p>Any hints or anyone experienced this kind of behavior as well (unfortunately it looks as quite "rare" problem for some reason)? Quite desperate about this...</p>
28,755,606
10
3
null
2015-01-06 23:00:09.28 UTC
16
2021-10-27 20:02:40.86 UTC
2015-06-16 19:19:39.42 UTC
null
540,552
null
3,626,641
null
1
91
java|maven|java-8|maven-javadoc-plugin
46,643
<p>This appears to be due to <code>javax.transaction.Transactional</code> (or any other class in your classpath for that matter) being itself annotated with <code>javax.interceptor.InterceptorBinding</code>, which is missing in classpath unless explicitly declared in dependencies:</p> <pre><code>@Inherited @InterceptorBinding // &lt;-- this ONE is causing troubles @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(value = RetentionPolicy.RUNTIME) public @interface Transactional { </code></pre> <p>Said that:</p> <ul> <li><code>javax.transaction.Transactional</code> - comes with <a href="https://repository.sonatype.org/#nexus-search;gav~javax.transaction~javax.transaction-api~1.2~~" rel="noreferrer" title="javax.transaction:javax.transaction-api:1.+">javax.transaction:javax.transaction-api:1.+</a> (or <code>org.jboss.spec.javax.transaction:jboss-transaction-api_1.2_spec:1.0.0.Final</code>) and is typically used in JPA/ORM/JMS apps to annotate transactional methods.</li> <li><code>javax.interceptor.InterceptorBinding</code> - should come with <a href="https://repository.sonatype.org/#nexus-search;gav~javax.interceptor~javax.interceptor-api~1.2~~%20javax.interceptor:javax.interceptor-api:1.2%22" rel="noreferrer">javax.interceptor:javax.interceptor-api:1.+</a>. But, although declared on top of <code>Transactional</code>, is not required for normal operation and (looks like because of this) is not getting fetched as a transitive dependency of your JPA framework.</li> </ul> <p>As a result JDK8 javadoc tool fails to process the sources (if any of them are annotated with <code>@Transactional</code>).</p> <p>Although it could be more specific about the place where this "error" has been found.</p> <p><strong>Issue fix</strong>: adding <code>javax.interceptor:javax.interceptor-api:1.+</code> dependency fixes the issue.</p> <pre><code>&lt;dependency&gt; &lt;groupId&gt;javax.interceptor&lt;/groupId&gt; &lt;artifactId&gt;javax.interceptor-api&lt;/artifactId&gt; &lt;version&gt;1.2.2&lt;/version&gt; &lt;/dependency&gt; </code></pre> <p>Note (January 2020): the latest (plausible) version is currently 1.2.2 (see <a href="https://mvnrepository.com/artifact/javax.interceptor/javax.interceptor-api" rel="noreferrer">https://mvnrepository.com/artifact/javax.interceptor/javax.interceptor-api</a> </p>
27,852,343
Split Python sequence (time series/array) into subsequences with overlap
<p>I need to extract all subsequences of a time series/array of a given window. For example:</p> <pre><code>&gt;&gt;&gt; ts = pd.Series([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) &gt;&gt;&gt; window = 3 &gt;&gt;&gt; subsequences(ts, window) array([[0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [5, 7, 8], [6, 8, 9]]) </code></pre> <p>Naive methods that iterate over the sequence are of course expensive, for example:</p> <pre><code>def subsequences(ts, window): res = [] for i in range(ts.size - window + 1): subts = ts[i:i+window] subts.reset_index(drop=True, inplace=True) subts.name = None res.append(subts) return pd.DataFrame(res) </code></pre> <p>I found a better way by copying the sequence, shifting it by a different value until the window is covered, and splitting the different sequences with <code>reshape</code>. Performance is around 100x better, because the for loop iterates over the window size, and not the sequence size:</p> <pre><code>def subsequences(ts, window): res = [] for i in range(window): subts = ts.shift(-i)[:-(ts.size%window)].reshape((ts.size // window, window)) res.append(subts) return pd.DataFrame(np.concatenate(res, axis=0)) </code></pre> <p>I've seen that pandas includes several rolling functions in the pandas.stats.moment module, and I guess what they do is somehow similar to the subsequencing problem. Is there anywhere in that module, or anywhere else in pandas to make this more efficient?</p> <p>Thank you!</p> <p><strong>UPDATE (SOLUTION):</strong></p> <p>Based on @elyase answer, for this specific case there is a slightly simpler implementation, let me write it down here, and explain what it's doing:</p> <pre><code>def subsequences(ts, window): shape = (ts.size - window + 1, window) strides = ts.strides * 2 return np.lib.stride_tricks.as_strided(ts, shape=shape, strides=strides) </code></pre> <p>Given the 1-D numpy array, we first compute the shape of the resulting array. We will have a row starting at each position of the array, with just the exception of the last few elements, at which starting them there wouldn't be enough elements next to complete the window.</p> <p>See on the first example in this description, how the last number we start at is 6, because starting at 7, we can't create a window of three elements. So, the number of rows is the size minus the window plus one. The number of columns is simply the window.</p> <p>Next, the tricky part is telling how to fill the resulting array, with the shape we just defined.</p> <p>To do we consider that the first element will be the first. Then we need to specify two values (in a tuple of two integers as the argument to the parameter <code>strides</code>). The values specify the steps we need to do in the original array (the 1-D one) to fill the second (the 2-D one).</p> <p>Consider a different example, where we want to implement the <code>np.reshape</code> function, from a 9 elements 1-D array, to a 3x3 array. The first element fills the first position, and then, the one at its right, would be the next on the 1-D array, so we move <em>1 step</em>. Then, the tricky part, to fill the first element of the second row, we should do 3 steps, from the 0 to the 4, see:</p> <pre><code>&gt;&gt;&gt; original = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8]) &gt;&gt;&gt; new = array([[0, 1, 2], [3, 4, 5], [6, 7, 8])] </code></pre> <p>So, to <code>reshape</code>, our steps for the two dimensions would be <code>(1, 3)</code>. For our case, where it exists overlap, it is actually simpler. When we move right to fill the resulting array, we start at the next position in the 1-D array, and when we move right, again we get the next element, so 1 step, in the 1-D array. So, the steps would be <code>(1, 1)</code>.</p> <p>There is only one last thing to note. The <code>strides</code> argument does not accept the "steps" we used, but instead the bytes in memory. To know them, we can use the <code>strides</code> method of numpy arrays. It returns a tuple with the strides (steps in bytes), with one element for each dimension. In our case we get a 1 element tuple, and we want it twice, so we have the <code>* 2</code>.</p> <p>The <code>np.lib.stride_tricks.as_strided</code> function performs the filling using the described method <em>without</em> copying the data, which makes it quite efficient.</p> <p>Finally, note that the function posted here assumes a 1-D input array (which is different from a 2-D array with 1 element as row or column). See the shape method of the input array, and you should get something like <code>(N, )</code> and not <code>(N, 1)</code>. This method would fail on the latter. Note that the method posted by @elyase handles two dimension input array (that's why this version is slightly simpler).</p>
27,852,474
3
3
null
2015-01-09 01:07:26.447 UTC
10
2019-07-16 11:55:40.067 UTC
2015-01-09 21:49:17.62 UTC
null
711,705
null
711,705
null
1
13
python|performance|numpy|pandas|time-series
9,104
<p>This is 34x faster than your fast version in my machine:</p> <pre><code>def rolling_window(a, window): shape = a.shape[:-1] + (a.shape[-1] - window + 1, window) strides = a.strides + (a.strides[-1],) return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides) &gt;&gt;&gt; rolling_window(ts.values, 3) array([[0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9]]) </code></pre> <p>Credit goes to <a href="http://www.rigtorp.se/2011/01/01/rolling-statistics-numpy.html">Erik Rigtorp</a>.</p>
5,580,935
Converting iPhone app to a Universal app in Xcode 4
<p>I am trying to upgrade my existing iPhone app project to an Universal app but I can not find any option in Xcode 4 to do so. Where is it?</p>
5,582,407
2
1
null
2011-04-07 12:21:52.983 UTC
9
2014-03-31 19:03:25.163 UTC
2011-06-21 02:48:03.473 UTC
null
19,617
null
319,097
null
1
25
objective-c|ios|xcode4|universal-binary
15,690
<p>{ Outdated / incorrect information removed. Moderators, I've asked to at least unmark my answer as accepted. Please clean this up. }</p> <p><strong>See Nick Lockwood's answer!</strong></p>
16,504,084
What is Object Reference Variable?
<p>What is Object Reference variable in java?</p> <p>Does the reference variable holds the memory address of the object?</p> <p>I am confused. Please do explain.</p>
16,504,133
5
0
null
2013-05-12 04:05:34.553 UTC
8
2015-11-25 06:52:19.64 UTC
2013-05-12 06:10:11.347 UTC
null
418,556
null
2,301,829
null
1
9
java
69,877
<p>I'm not sure I have the elegance to properly answer this, but...</p> <ul> <li>An Object is an instance of a Class, it is stored some where in memory</li> <li>A reference is what is used to describe the pointer to the memory location where the Object resides.</li> <li>A variable is a means by which you can access that memory location within your application (its value is "variable"). While a variable can only point to a single memory address (if its not null), it may change and point to different locations through out the life cycle of the application</li> </ul>
1,065,247
How do I calculate tree edit distance?
<p>I need to calculate the edit distance between trees. <a href="http://erikdemaine.org/papers/TreeEdit_ICALP2007/paper.ps" rel="nofollow noreferrer">This</a> paper describes an algorithm, but I can't make heads or tails out of it. Could you describe an applicable algorithm in a more approachable way? Pseudocode or code would both be helpful.</p>
1,065,485
7
2
null
2009-06-30 18:34:55.723 UTC
20
2021-08-17 09:34:49.573 UTC
2020-01-27 15:00:32.673 UTC
null
1,536,976
null
32,944
null
1
27
algorithm|tree
16,760
<p>Here's some <a href="http://web.science.mq.edu.au/%7Eswan/howtos/treedistance/" rel="nofollow noreferrer">Java source code</a> (gzipped tarball at the bottom) for a <em>tree edit distance</em> algorithm that might be useful to you.</p> <p>The page includes references and some slides that go through the &quot;Zhang and Shasha&quot; algorithm step-by-step and other useful links to get you up to speed.</p> <p>The code in the link has bugs. Steve Johnson and tim.tadh have provided <a href="https://github.com/timtadh/zhang-shasha" rel="nofollow noreferrer">working Python code</a>. See <a href="https://stackoverflow.com/questions/1065247/how-do-i-calculate-tree-edit-distance/4264181#4264181">Steve Johnson's comment</a> for more details.</p>
917,551
Func delegate with no return type
<p>All of the Func delegates return a value. What are the .NET delegates that can be used with methods that return void?</p>
917,572
7
0
null
2009-05-27 19:21:42.033 UTC
71
2018-03-06 00:18:13.67 UTC
2013-01-10 16:51:29.803 UTC
null
265,570
null
113,165
null
1
657
c#|.net
261,866
<p>All Func delegates return something; all the Action delegates return void.</p> <p><code>Func&lt;TResult&gt;</code> takes no arguments and returns TResult:</p> <pre><code>public delegate TResult Func&lt;TResult&gt;() </code></pre> <p><code>Action&lt;T&gt;</code> takes one argument and does not return a value:</p> <pre><code>public delegate void Action&lt;T&gt;(T obj) </code></pre> <p><code>Action</code> is the simplest, 'bare' delegate:</p> <pre><code>public delegate void Action() </code></pre> <p>There's also <code>Func&lt;TArg1, TResult&gt;</code> and <code>Action&lt;TArg1, TArg2&gt;</code> (and others up to 16 arguments). All of these (except for <code>Action&lt;T&gt;</code>) are new to .NET 3.5 (defined in System.Core).</p>
659,025
How to remove non-alphanumeric characters?
<p>I need to remove all characters from a string which aren't in <code>a-z A-Z 0-9</code> set or are not spaces.</p> <p>Does anyone have a function to do this?</p>
659,030
7
0
null
2009-03-18 16:29:19.14 UTC
59
2019-08-06 22:39:34.977 UTC
2015-03-19 19:33:25.23 UTC
null
55,075
zuk1
26,823
null
1
408
php|regex|string
274,033
<p>Sounds like you almost knew what you wanted to do already, you basically defined it as a regex.</p> <pre><code>preg_replace("/[^A-Za-z0-9 ]/", '', $string); </code></pre>
1,264,833
Class factory to produce simple struct-like classes?
<p>While investigating Ruby I came across this to create a simple Struct-like class:</p> <pre><code>Person = Struct.new(:forname, :surname) person1 = Person.new('John', 'Doe') puts person1 #&lt;struct Person forname="John", surname="Doe"&gt; </code></pre> <p>Which raised a few Python questions for me. I have written a [VERY] basic clone of this mechanism in Python:</p> <pre><code>def Struct(*args): class NewStruct: def __init__(self): for arg in args: self.__dict__[arg] = None return NewStruct &gt;&gt;&gt; Person = Struct('forename', 'surname') &gt;&gt;&gt; person1 = Person() &gt;&gt;&gt; person2 = Person() &gt;&gt;&gt; person1.forename, person1.surname = 'John','Doe' &gt;&gt;&gt; person2.forename, person2.surname = 'Foo','Bar' &gt;&gt;&gt; person1.forename 'John' &gt;&gt;&gt; person2.forename 'Foo' </code></pre> <ol> <li><p>Is there already a similar mechanism in Python to handle this? (I usually just use dictionaries).</p></li> <li><p>How would I get the <code>Struct()</code> function to create the correct <code>__init__()</code> arguments. (in this case I would like to perform <code>person1 = Person('John', 'Doe')</code> Named Arguments if possible: <code>person1 = Person(surname='Doe', forename='John')</code></p></li> </ol> <p>I Would like, as a matter of interest, to have Question 2 answered even if there is a better Python mechanism to do this.</p>
1,275,088
8
1
null
2009-08-12 07:57:57.577 UTC
12
2022-06-20 16:29:38.427 UTC
2017-08-31 19:58:21.35 UTC
null
355,230
null
134,107
null
1
13
python|struct|class-factory
8,406
<p>An update of ThomasH's variant:</p> <pre><code>def Struct(*args, **kwargs): def init(self, *iargs, **ikwargs): for k,v in kwargs.items(): setattr(self, k, v) for i in range(len(iargs)): setattr(self, args[i], iargs[i]) for k,v in ikwargs.items(): setattr(self, k, v) name = kwargs.pop("name", "MyStruct") kwargs.update(dict((k, None) for k in args)) return type(name, (object,), {'__init__': init, '__slots__': kwargs.keys()}) </code></pre> <p>This allows parameters (and named parameters) passed into <code>__init__()</code> (without any validation - seems crude):</p> <pre><code>&gt;&gt;&gt; Person = Struct('fname', 'age') &gt;&gt;&gt; person1 = Person('Kevin', 25) &gt;&gt;&gt; person2 = Person(age=42, fname='Terry') &gt;&gt;&gt; person1.age += 10 &gt;&gt;&gt; person2.age -= 10 &gt;&gt;&gt; person1.fname, person1.age, person2.fname, person2.age ('Kevin', 35, 'Terry', 32) &gt;&gt;&gt; </code></pre> <h2>Update</h2> <p>Having a look into how <a href="http://docs.python.org/library/collections.html#collections.namedtuple" rel="nofollow noreferrer"><code>namedtuple()</code></a> does this in <a href="http://svn.python.org/view/python/trunk/Lib/collections.py?view=markup" rel="nofollow noreferrer">collections.py</a>. The class is created and expanded as a string and evaluated. Also has support for pickling and so on, etc.</p>
1,004,327
Getting rid of derby.log
<p>I'm using the Apache Derby embedded database for unit testing in a Maven project. Unfortunately whenever I run the test I end up with the <code>derby.log</code> file in the root of the project. The database itself is created in the <code>target</code> directory (<code>jdbc:derby:target/unittest-db;create=true</code>) so that is not a problem. After consulting the <a href="http://db.apache.org/derby/docs/10.2/ref/rrefattrib24612.html#rrefattrib24612" rel="noreferrer">reference guide</a> I tried setting the <code>logDevice</code> parameter on the JDBC url (<code>jdbc:derby:target/unittest-db;create=true;logDevice=/mylogs</code>) but that seems to be for a different log, hence <code>derby.log</code> still appears.</p> <p>Any help is much appreciated.</p>
1,004,686
8
0
null
2009-06-16 22:54:36.47 UTC
15
2016-07-27 12:13:20.11 UTC
null
null
null
null
417,328
null
1
28
java|maven-2|derby
28,381
<p>You can get rid of <a href="http://db.apache.org/derby/docs/dev/devguide/cdevdvlp25889.html" rel="noreferrer"><code>derby.log</code></a> file by creating the following class</p> <pre><code>public class DerbyUtil { public static final OutputStream DEV_NULL = new OutputStream() { public void write(int b) {} }; } </code></pre> <p>and setting the JVM system property <a href="http://db.apache.org/derby/docs/10.8/ref/rrefproper33027.html" rel="noreferrer"><code>derby.stream.error.field</code></a>, for example, using the following JVM command-line argument:</p> <pre><code>-Dderby.stream.error.field=DerbyUtil.DEV_NULL </code></pre> <p><a href="http://davidvancouvering.blogspot.com/2007/10/quiet-time-and-how-to-suppress-derbylog.html" rel="noreferrer">Credit to whom it is due.</a></p>
42,182
How to escape < and > inside <pre> tags
<p>I'm trying to write a blog post which includes a code segment inside a <code>&lt;pre&gt;</code> tag. The code segment includes a generic type and uses <code>&lt;&gt;</code> to define that type. This is what the segment looks like:</p> <pre><code>&lt;pre&gt; PrimeCalc calc = new PrimeCalc(); Func&lt;int, int&gt; del = calc.GetNextPrime; &lt;/pre&gt; </code></pre> <p>The resulting HTML removes the <code>&lt;&gt;</code> and ends up like this:</p> <pre><code>PrimeCalc calc = new PrimeCalc(); Func del = calc.GetNextPrime; </code></pre> <p>How do I escape the <code>&lt;&gt;</code> so they show up in the HTML?</p>
42,195
8
2
null
2008-09-03 17:41:06.43 UTC
15
2022-05-31 10:12:34.153 UTC
2022-05-31 10:12:34.153 UTC
null
3,689,450
urini
373
null
1
97
html|escaping|blogger|markup|pre
88,373
<pre><code>&lt;pre&gt; PrimeCalc calc = new PrimeCalc(); Func&amp;lt;int, int&amp;gt; del = calc.GetNextPrime; &lt;/pre&gt; </code></pre>
230,454
How to Fill an array from user input C#?
<p>What would be the best way to fill an array from user input?</p> <p>Would a solution be showing a prompt message and then get the values from from the user?</p>
230,463
9
0
null
2008-10-23 16:37:23.503 UTC
7
2017-08-23 01:13:31.237 UTC
2008-10-23 16:51:44.27 UTC
Longhorn213
2,469
arin
30,858
null
1
18
c#
221,328
<pre><code>string []answer = new string[10]; for(int i = 0;i&lt;answer.length;i++) { answer[i]= Console.ReadLine(); } </code></pre>
411,249
Coding style checker for C
<p>I'm working for a company that has strict coding style guidelines but no automatic tool to validate them. I've looked around and the only tools I could find were lint like tools that seem to be aimed at verifying what the code does, and preventing bugs and not at making sure the coding style is correct.</p> <p>What tool should we use, if at all?</p> <p>NOTE: I'm looking for something for C code, although something that works for C++ would be good as well.</p>
411,698
9
0
null
2009-01-04 16:46:06.79 UTC
16
2018-10-23 13:49:31.697 UTC
null
null
null
gooli
15,109
null
1
24
c|coding-style
36,510
<p>The traditional beautifier <a href="http://en.wikipedia.org/wiki/Indent_(Unix)" rel="noreferrer">indent</a>, available on every Unix machine. The version found on some is <a href="http://www.gnu.org/software/indent/" rel="noreferrer">GNU indent</a>, which can be compiled and installed on every machine. GNU indent can read a set of rules from the file <code>~/.indent.pro</code>, for instance:</p> <pre><code>--original --dont-format-first-column-comments --no-blank-lines-after-commas --parameter-indentation 8 --indent-level 8 --line-length 85 --no-space-after-parentheses --no-comment-delimiters-on-blank-lines </code></pre> <p>So, just running indent before commiting guarantees uniformity of the presentation. If you want to <strong>enforce</strong> it, define a pre-commit hook in the Version Control System you use, which will run indent and refuse the commit if the committed version differs from what indent produces.</p>
681,827
How to create and fill a ZIP file using ASP.NET?
<p>Need to dynamically package some files into a .zip to create a SCORM package, anyone know how this can be done using code? Is it possible to build the folder structure dynamically inside of the .zip as well?</p>
681,956
9
1
null
2009-03-25 14:29:48.113 UTC
8
2020-08-20 06:09:23.11 UTC
null
null
null
Ryan
18,309
null
1
27
asp.net|zip
45,392
<p>You don't have to use an external library anymore. System.IO.Packaging has classes that can be used to drop content into a zip file. Its not simple, however. <a href="http://weblogs.asp.net/jongalloway//creating-zip-archives-in-net-without-an-external-library-like-sharpziplib" rel="noreferrer">Here's a blog post with an example</a> (its at the end; dig for it).</p> <hr> <p>The link isn't stable, so here's the example Jon provided in the post.</p> <pre><code>using System; using System.IO; using System.IO.Packaging; namespace ZipSample { class Program { static void Main(string[] args) { AddFileToZip("Output.zip", @"C:\Windows\Notepad.exe"); AddFileToZip("Output.zip", @"C:\Windows\System32\Calc.exe"); } private const long BUFFER_SIZE = 4096; private static void AddFileToZip(string zipFilename, string fileToAdd) { using (Package zip = System.IO.Packaging.Package.Open(zipFilename, FileMode.OpenOrCreate)) { string destFilename = ".\\" + Path.GetFileName(fileToAdd); Uri uri = PackUriHelper.CreatePartUri(new Uri(destFilename, UriKind.Relative)); if (zip.PartExists(uri)) { zip.DeletePart(uri); } PackagePart part = zip.CreatePart(uri, "",CompressionOption.Normal); using (FileStream fileStream = new FileStream(fileToAdd, FileMode.Open, FileAccess.Read)) { using (Stream dest = part.GetStream()) { CopyStream(fileStream, dest); } } } } private static void CopyStream(System.IO.FileStream inputStream, System.IO.Stream outputStream) { long bufferSize = inputStream.Length &lt; BUFFER_SIZE ? inputStream.Length : BUFFER_SIZE; byte[] buffer = new byte[bufferSize]; int bytesRead = 0; long bytesWritten = 0; while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) != 0) { outputStream.Write(buffer, 0, bytesRead); bytesWritten += bytesRead; } } } } </code></pre>
470,256
Process.WaitForExit() asynchronously
<p>I want to wait for a process to finish, but <code>Process.WaitForExit()</code> hangs my GUI. Is there an event-based way, or do I need to spawn a thread to block until exit, then delegate the event myself?</p>
470,288
9
3
null
2009-01-22 18:13:58.397 UTC
13
2022-06-22 01:23:30.15 UTC
2022-06-22 01:23:30.15 UTC
null
11,178,549
Dustin Getz
20,003
null
1
72
c#|.net|winforms|user-interface|asynchronous
43,672
<p><a href="https://msdn.microsoft.com/en-us/library/system.diagnostics.process.enableraisingevents.aspx" rel="noreferrer">process.EnableRaisingEvents</a> = true;<br> <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.process.exited.aspx" rel="noreferrer">process.Exited</a> += [EventHandler]</p>
170,907
Is there a downside to adding an anonymous empty delegate on event declaration?
<p>I have seen a few mentions of this idiom (including <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c#9282">on SO</a>):</p> <pre><code>// Deliberately empty subscriber public event EventHandler AskQuestion = delegate {}; </code></pre> <p>The upside is clear - it avoids the need to check for null before raising the event.</p> <p><strong>However, I am keen to understand if there are any downsides.</strong> For example, is it something that is in widespread use and is transparent enough that it won't cause a maintenance headache? Is there any appreciable performance hit of the empty event subscriber call?</p>
170,915
9
0
null
2008-10-04 19:41:15.103 UTC
30
2015-08-10 18:23:23.57 UTC
2017-05-23 12:18:17.367 UTC
Joel Coehoorn
-1
serg10
1,853
null
1
84
c#|coding-style|delegates|events|idioms
12,287
<p>The only downside is a very slight performance penalty as you are calling extra empty delegate. Other than that there is no maintenance penalty or other drawback.</p>
602,706
Batch renaming files with Bash
<p>How can Bash rename a series of packages to remove their version numbers? I've been toying around with both <code>expr</code> and <code>%%</code>, to no avail.</p> <p>Examples:</p> <p><code>Xft2-2.1.13.pkg</code> becomes <code>Xft2.pkg</code></p> <p><code>jasper-1.900.1.pkg</code> becomes <code>jasper.pkg</code></p> <p><code>xorg-libXrandr-1.2.3.pkg</code> becomes <code>xorg-libXrandr.pkg</code></p>
602,770
10
2
null
2009-03-02 15:20:44.83 UTC
50
2018-08-22 09:05:25.937 UTC
2017-06-12 03:59:21.147 UTC
null
6,862,601
Nerdling
70,519
null
1
117
bash|shell|file-rename
105,863
<p>You could use bash's parameter expansion feature</p> <pre><code>for i in ./*.pkg ; do mv "$i" "${i/-[0-9.]*.pkg/.pkg}" ; done </code></pre> <p>Quotes are needed for filenames with spaces.</p>
1,309,452
How to replace innerHTML of a div using jQuery?
<p>How could I achieve the following:</p> <pre><code>document.all.regTitle.innerHTML = 'Hello World'; </code></pre> <p>Using jQuery where <code>regTitle</code> is my <code>div</code> id?</p>
1,309,454
14
0
null
2009-08-20 23:51:36.783 UTC
123
2021-06-22 09:52:00.59 UTC
2020-07-20 18:12:45.403 UTC
null
2,430,549
null
111,479
null
1
1,148
javascript|jquery|innerhtml
1,823,320
<pre><code>$("#regTitle").html("Hello World"); </code></pre>
1,163,376
HTML +CSS +Javascript Editor
<p>Hello I am looking for a good HTML + CSS +Javascript Editor Microsoft Windows platform </p> <p>Thank you very much !!!!</p> <p><strong>UPDATES</strong> : </p> <hr> <p>1) I found an amazing one, which I use already for a while on windows and on MAC as well :</p> <p><a href="http://www.sublimetext.com/2" rel="noreferrer"><strong>Sumblime Text 2</strong></a></p> <hr> <p>2) </p> <p><a href="https://www.jetbrains.com/webstorm/" rel="noreferrer"><strong>WebStorm</strong></a> is another one I like.</p> <p>WebStorm I use for the bigger projects, where the SublimeText is more for the files to open, or a small projects because it is very fast </p>
1,163,396
15
5
null
2009-07-22 06:28:58.04 UTC
4
2016-05-25 19:06:34.26 UTC
2014-10-21 18:09:37.567 UTC
null
119,084
null
119,084
null
1
26
javascript|html|css|editor
89,739
<p>I prefer Netbeans 6.7 PHP , it includES CSS / JS / HTML and PHP Features. Codefolding, Syntax Highlighting, Code completion, CSS Preview...</p> <p>But my Favourite function is code completion for JQuery + Dojo</p> <p>Download : <a href="https://netbeans.org//downloads/index.html" rel="nofollow noreferrer">Netbeans Download</a></p>
254,281
Best practices for overriding isEqual: and hash
<p>How do you properly override <code>isEqual:</code> in Objective-C? The "catch" seems to be that if two objects are equal (as determined by the <code>isEqual:</code> method), they must have the same hash value.</p> <p>The <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaObjects/CocoaObjects.html#//apple_ref/doc/uid/TP40002974-CH4-SW25" rel="noreferrer">Introspection</a> section of the <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaFundamentals/" rel="noreferrer">Cocoa Fundamentals Guide</a> does have an example on how to override <code>isEqual:</code>, copied as follows, for a class named <code>MyWidget</code>:</p> <pre><code>- (BOOL)isEqual:(id)other { if (other == self) return YES; if (!other || ![other isKindOfClass:[self class]]) return NO; return [self isEqualToWidget:other]; } - (BOOL)isEqualToWidget:(MyWidget *)aWidget { if (self == aWidget) return YES; if (![(id)[self name] isEqual:[aWidget name]]) return NO; if (![[self data] isEqualToData:[aWidget data]]) return NO; return YES; } </code></pre> <p>It checks pointer equality, then class equality, and finally compares the objects using <code>isEqualToWidget:</code>, which only checks the <code>name</code> and <code>data</code> properties. What the example <em>doesn't</em> show is how to override <code>hash</code>.</p> <p>Let's assume there are other properties that do not affect equality, say <code>age</code>. Shouldn't the <code>hash</code> method be overridden such that only <code>name</code> and <code>data</code> affect the hash? And if so, how would you do that? Just add the hashes of <code>name</code> and <code>data</code>? For example:</p> <pre><code>- (NSUInteger)hash { NSUInteger hash = 0; hash += [[self name] hash]; hash += [[self data] hash]; return hash; } </code></pre> <p>Is that sufficient? Is there a better technique? What if you have primitives, like <code>int</code>? Convert them to <code>NSNumber</code> to get their hash? Or structs like <code>NSRect</code>?</p> <p>(<strong>Brain fart</strong>: Originally wrote "bitwise OR" them together with <code>|=</code>. Meant add.)</p>
254,380
16
2
null
2008-10-31 17:22:25.783 UTC
160
2022-01-20 23:08:10.38 UTC
2009-07-11 13:49:29.39 UTC
Ned Batchelder
120,292
Dave Dribin
26,825
null
1
272
objective-c|equality
94,221
<p>Start with</p> <pre><code> NSUInteger prime = 31; NSUInteger result = 1; </code></pre> <p>Then for every primitive you do</p> <pre><code> result = prime * result + var </code></pre> <p>For objects you use 0 for nil and otherwise their hashcode.</p> <pre><code> result = prime * result + [var hash]; </code></pre> <p>For booleans you use two different values</p> <pre><code> result = prime * result + ((var)?1231:1237); </code></pre> <hr> <h2>Explanation and Attribution</h2> <p>This is not tcurdt's work, and comments were asking for more explanation, so I believe an edit for attribution is fair.</p> <p>This algorithm was popularized in the book "Effective Java", and <a href="http://www.scribd.com/doc/36454091/Effective-Java-Chapter3" rel="nofollow noreferrer">the relevant chapter can currently be found online here</a>. That book popularized the algorithm, which is now a default in a number of Java applications (including Eclipse). It derived, however, from an even older implementation which is variously attributed to Dan Bernstein or Chris Torek. That older algorithm originally floated around on Usenet, and certain attribution is difficult. For example, there is some <a href="http://svn.apache.org/repos/asf/apr/apr/trunk/tables/apr_hash.c" rel="nofollow noreferrer">interesting commentary in this Apache code</a> (search for their names) that references the original source.</p> <p>Bottom line is, this is a very old, simple hashing algorithm. It is not the most performant, and it is not even proven mathematically to be a "good" algorithm. But it is simple, and a lot of people have used it for a long time with good results, so it has a lot of historical support.</p>
1,257,482
RedirectToAction with parameter
<p>I have an action I call from an anchor thusly, <code>Site/Controller/Action/ID</code> where <code>ID</code> is an <code>int</code>.</p> <p>Later on I need to redirect to this same Action from a Controller.</p> <p>Is there a clever way to do this? Currently I'm stashing <code>ID</code> in tempdata, but when you hit f5 to refresh the page again after going back, the tempdata is gone and the page crashes.</p>
1,257,632
16
1
null
2009-08-10 22:05:09.077 UTC
102
2022-04-26 06:17:20.55 UTC
2018-02-13 12:46:47.177 UTC
null
5,978,553
null
86,431
null
1
690
c#|asp.net-mvc|controller|redirecttoaction
967,686
<p>You can pass the id as part of the routeValues parameter of the RedirectToAction() method.</p> <pre><code>return RedirectToAction("Action", new { id = 99 }); </code></pre> <p>This will cause a redirect to Site/Controller/Action/99. No need for temp or any kind of view data.</p>
226,663
Parse RSS with jQuery
<p>I want to use jQuery to parse RSS feeds. Can this be done with the base jQuery library out of the box or will I need to use a plugin?</p>
6,271,906
20
3
null
2008-10-22 16:49:58.017 UTC
122
2019-10-15 07:52:05.897 UTC
2012-07-12 04:34:09.693 UTC
pkaeding
9,314
null
12,442
null
1
195
jquery|jquery-plugins|rss|feedparser
223,819
<p><strong>WARNING</strong></p> <blockquote> <p><a href="https://developers.google.com/feed/" rel="nofollow noreferrer">The Google Feed API</a> is officially <strong>deprecated</strong> and <strong>doesn't work anymore</strong>!</p> </blockquote> <hr> <p>No need for a whole plugin. This will return your RSS as a JSON object to a callback function:</p> <pre><code>function parseRSS(url, callback) { $.ajax({ url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&amp;num=10&amp;callback=?&amp;q=' + encodeURIComponent(url), dataType: 'json', success: function(data) { callback(data.responseData.feed); } }); } </code></pre>
1,056,316
Algorithm for Determining Tic Tac Toe Game Over
<p>I've written a game of tic-tac-toe in Java, and my current method of determining the end of the game accounts for the following possible scenarios for the game being over:</p> <ol> <li>The board is full, and no winner has yet been declared: Game is a draw.</li> <li>Cross has won.</li> <li>Circle has won.</li> </ol> <p>Unfortunately, to do so, it reads through a predefined set of these scenarios from a table. This isn't necessarily bad considering that there are only 9 spaces on a board, and thus the table is somewhat small, but is there a better algorithmic way of determining if the game is over? The determination of whether someone has won or not is the meat of the problem, since checking if 9 spaces are full is trivial. </p> <p>The table method might be the solution, but if not, what is? Also, what if the board were not size <code>n=9</code>? What if it were a much larger board, say <code>n=16</code>, <code>n=25</code>, and so on, causing the number of consecutively placed items to win to be <code>x=4</code>, <code>x=5</code>, etc? A general algorithm to use for all <code>n = { 9, 16, 25, 36 ... }</code>?</p>
1,056,352
25
1
null
2009-06-29 02:18:21.727 UTC
72
2022-01-10 08:46:45.69 UTC
2021-06-11 17:15:50.983 UTC
null
1,373,465
null
112,765
null
1
116
algorithm|state|tic-tac-toe
252,451
<p>You know a winning move can only happen after X or O has made their most recent move, so you can only search row/column with optional diag that are contained in that move to limit your search space when trying to determine a winning board. Also since there are a fixed number of moves in a draw tic-tac-toe game once the last move is made if it wasn't a winning move it's by default a draw game.</p> <p>This code is for an n by n board with n in a row to win (3x3 board requires 3 in a row, etc)</p> <pre class="lang-js prettyprint-override"><code>public class TripleT { enum State{Blank, X, O}; int n = 3; State[][] board = new State[n][n]; int moveCount; void Move(int x, int y, State s){ if(board[x][y] == State.Blank){ board[x][y] = s; } moveCount++; //check end conditions //check col for(int i = 0; i &lt; n; i++){ if(board[x][i] != s) break; if(i == n-1){ //report win for s } } //check row for(int i = 0; i &lt; n; i++){ if(board[i][y] != s) break; if(i == n-1){ //report win for s } } //check diag if(x == y){ //we're on a diagonal for(int i = 0; i &lt; n; i++){ if(board[i][i] != s) break; if(i == n-1){ //report win for s } } } //check anti diag (thanks rampion) if(x + y == n - 1){ for(int i = 0; i &lt; n; i++){ if(board[i][(n-1)-i] != s) break; if(i == n-1){ //report win for s } } } //check draw if(moveCount == (Math.pow(n, 2) - 1)){ //report draw } } } </code></pre>
492,558
Removing multiple files from a Git repo that have already been deleted from disk
<p>I have a Git repo that I have deleted four files from using <code>rm</code> (<strong>not</strong> <code>git rm</code>), and my Git status looks like this:</p> <pre><code># deleted: file1.txt # deleted: file2.txt # deleted: file3.txt # deleted: file4.txt </code></pre> <p>How do I remove these files from Git without having to manually go through and add each file like this:</p> <pre><code>git rm file1 file2 file3 file4 </code></pre> <p>Ideally, I'm looking for something that works in the same way that <code>git add .</code> does, if that's possible.</p>
1,402,793
31
6
null
2009-01-29 17:18:14.777 UTC
879
2021-12-22 09:43:15.33 UTC
2015-06-24 06:12:48.897 UTC
null
2,790,048
Mr. Matt
12,037
null
1
1,367
git|git-commit|git-add|git-rm
533,980
<h3>For Git 1.x</h3> <pre><code>$ git add -u </code></pre> <p>This tells git to automatically stage tracked files -- including deleting the previously tracked files. </p> <h3>For Git 2.0</h3> <p>To stage your whole working tree:</p> <pre><code>$ git add -u :/ </code></pre> <p>To stage just the current path:</p> <pre><code>$ git add -u . </code></pre>
359,732
Why is it considered a bad practice to omit curly braces?
<p>Why does everyone tell me writing code like this is a bad practice?</p> <pre><code>if (foo) Bar(); //or for(int i = 0 i &lt; count; i++) Bar(i); </code></pre> <p>My biggest argument for omitting the curly braces is that it can sometimes be twice as many lines with them. For example, here is some code to paint a glow effect for a label in C#.</p> <pre><code>using (Brush br = new SolidBrush(Color.FromArgb(15, GlowColor))) { for (int x = 0; x &lt;= GlowAmount; x++) { for (int y = 0; y &lt;= GlowAmount; y++) { g.DrawString(Text, this.Font, br, new Point(IconOffset + x, y)); } } } //versus using (Brush br = new SolidBrush(Color.FromArgb(15, GlowColor))) for (int x = 0; x &lt;= GlowAmount; x++) for (int y = 0; y &lt;= GlowAmount; y++) g.DrawString(Text, this.Font, br, new Point(IconOffset + x, y)); </code></pre> <p>You can also get the added benefit of chaining <code>usings</code> together without having to indent a million times.</p> <pre><code>using (Graphics g = Graphics.FromImage(bmp)) { using (Brush brush = new SolidBrush(backgroundColor)) { using (Pen pen = new Pen(Color.FromArgb(penColor))) { //do lots of work } } } //versus using (Graphics g = Graphics.FromImage(bmp)) using (Brush brush = new SolidBrush(backgroundColor)) using (Pen pen = new Pen(Color.FromArgb(penColor))) { //do lots of work } </code></pre> <hr> <p>The most common argument for curly braces revolves around maintance programming, and the problems that would ensue by inserting code between the original if statement and its intended result:</p> <pre><code>if (foo) Bar(); Biz(); </code></pre> <hr> <h3>Questions:</h3> <ol> <li>Is it wrong to want to use the more compact syntax which the language offers? The people that design these languages are smart, I can't imagine they would put a feature which is always bad to use.</li> <li>Should we or Shouldn't we write code so the lowest common denominator can understand and have no problems working with it? </li> <li>Is there another argument that I'm missing?</li> </ol>
359,753
52
20
2008-12-11 16:47:01.76 UTC
2008-12-11 15:34:22.827 UTC
48
2016-08-19 17:07:33.35 UTC
2016-08-19 17:07:33.35 UTC
Gortok
1,413,395
Bob
45
null
1
184
java|c#|c++|c|coding-style
64,590
<p>Actually, the only time that's ever really bit me was when I was debugging, and commented out bar():</p> <pre><code>if(foo) // bar(); doSomethingElse(); </code></pre> <p>Other than that, I tend to use:</p> <pre><code>if(foo) bar(); </code></pre> <p>Which takes care of the above case.</p> <p><strong>EDIT</strong> Thanks for clarifying the question, I agree, we should not write code to the lowest common denominator.</p>
6,616,599
Does the ^ symbol replace C#'s "ref" in parameter passing in C++/CLI code?
<p>In C#, passing by reference is:</p> <pre><code>void MyFunction(ref Dog dog) </code></pre> <p>But in C++/CLI code examples I have seen so far, there is no use of <code>ref</code> but instead <code>^</code> symbol is used:</p> <pre><code>void MyFunction(Dog ^ dog) </code></pre> <p>Is the use of <code>^</code> symbol a direct replacement for <code>ref</code> when parameter passing? or does it have some other meaning I'm not aware of?</p> <p>Additional Question: I also see a lot of:</p> <pre><code>Dog ^ myDog = gcnew Dog(); </code></pre> <p>It looks like it's used like <code>*</code> (pointer) in C++.. Does it work similarly?</p> <p>Thanks!</p>
6,616,684
5
2
null
2011-07-07 20:16:58.423 UTC
10
2020-01-06 11:25:12.993 UTC
null
null
null
null
1,418,093
null
1
20
c#|c++-cli
25,963
<p>If <code>Dog</code> is a reference type (<code>class</code> in C#) then the C++/CLI equivalent is:</p> <pre><code>void MyFunction(Dog^% dog) </code></pre> <p>If <code>Dog</code> is a value type (<code>struct</code> in C#) then the C++/CLI equivalent is:</p> <pre><code>void MyFunction(Dog% dog) </code></pre> <p>As a <em>type decorator</em>, <code>^</code> roughly correlates to <code>*</code> in C++, and <code>%</code> roughly correlates to <code>&amp;</code> in C++.</p> <p>As a <em>unary operator</em>, you typically still need to use <code>*</code> in C++/CLI where you use <code>*</code> in C++, but you typically need to use <code>%</code> in C++/CLI where you use <code>&amp;</code> in C++.</p>
6,497,373
Make content horizontally scroll inside a div
<p>I have a division in which I wanna show images and on click open them in a lightbox. I have floated them left and displayed them inline. set overflow-x to scroll but it still puts the images below once the row space is not enough. I wanna get them to be inline and display a horizontal scroll when needed.</p> <p><strong>NOTE:</strong> I can't change the structure of the images inside. It has to be a img inside an anchor. My lightbox requires it like that.</p> <p>HTML:</p> <pre><code>&lt;div id=&quot;myWorkContent&quot;&gt; &lt;a href=&quot;assets/work/1.jpg&quot;&gt;&lt;img src=&quot;assets/work/1.jpg&quot; height=&quot;190&quot; /&gt;&lt;/a&gt; &lt;a href=&quot;assets/work/2.jpg&quot;&gt;&lt;img src=&quot;assets/work/2.jpg&quot; height=&quot;190&quot; /&gt;&lt;/a&gt; &lt;a href=&quot;assets/work/3.jpg&quot;&gt;&lt;img src=&quot;assets/work/3.jpg&quot; height=&quot;190&quot; /&gt;&lt;/a&gt; &lt;a href=&quot;assets/work/4.jpg&quot;&gt;&lt;img src=&quot;assets/work/4.jpg&quot; height=&quot;190&quot; /&gt;&lt;/a&gt; &lt;a href=&quot;assets/work/5.jpg&quot;&gt;&lt;img src=&quot;assets/work/5.jpg&quot; height=&quot;190&quot; /&gt;&lt;/a&gt; &lt;a href=&quot;assets/work/6.jpg&quot;&gt;&lt;img src=&quot;assets/work/6.jpg&quot; height=&quot;190&quot; /&gt;&lt;/a&gt; &lt;/div&gt;&lt;!-- end myWorkContent --&gt; </code></pre> <p>CSS:</p> <pre class="lang-css prettyprint-override"><code>#myWorkContent{ width:530px; height:210px; border: 13px solid #bed5cd; overflow-x: scroll; overflow-y: hidden; } #myWorkContent a { display: inline; float:left } </code></pre> <p>I know this is very basic but I just can't get it done. Don't know what's wrong.</p>
6,497,462
5
0
null
2011-06-27 18:40:06.317 UTC
19
2021-10-05 01:57:06.857 UTC
2021-10-05 01:57:06.857 UTC
null
5,052,024
null
159,475
null
1
60
html|css
131,742
<p>It may be something like this in HTML:</p> <pre class="lang-html prettyprint-override"><code>&lt;div class=&quot;container-outer&quot;&gt; &lt;div class=&quot;container-inner&quot;&gt; &lt;!-- Your images over here --&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>With this stylesheet:</p> <pre class="lang-css prettyprint-override"><code>.container-outer { overflow: scroll; width: 500px; height: 210px; } .container-inner { width: 10000px; } </code></pre> <p>You can even create an intelligent script to calculate the inner container width, like this one:</p> <pre class="lang-js prettyprint-override"><code>$(document).ready(function() { var container_width = SINGLE_IMAGE_WIDTH * $(&quot;.container-inner a&quot;).length; $(&quot;.container-inner&quot;).css(&quot;width&quot;, container_width); }); </code></pre>
15,866,451
How to insert row at end of table with HTMLTableElement.insertRow
<h3>Background and Setup</h3> <p>I'm trying to create a table from tabular data in javascript, but when I try inserting rows into a table element, it inserts in the opposite order from what I expect and the opposite order of what you get from using <code>appendChild</code>. (Here's <a href="http://jsfiddle.net/jtratner/9uA9k/" rel="noreferrer">a jsfiddle with a live demo</a> of this).</p> <p>Say I have some data like this:</p> <pre class="lang-js prettyprint-override"><code>var data = [ {"a": 1, "b": 2, "c": 3}, {"a": 4, "b": 5, "c": 6}, {"a": 7, "b": 8, "c": 9} ], keys = ["a", "b", "c"]; </code></pre> <p>If I try using the <code>insertRow()</code> and <code>insertCell()</code> methods for creating tables, iterating over the data and keys above. I get the reverse order of what I expect:</p> <p><img src="https://i.stack.imgur.com/oyjSY.png" alt="InsertRows pic"></p> <p>Generated by using the following code:</p> <pre class="lang-js prettyprint-override"><code>// insert a table into the DOM var insertTable = insertDiv.appendChild(document.createElement("table")), thead = insertTable.createTHead(), // thead element thRow = thead.insertRow(), // trow element tbody = insertTable.createTBody(); // tbody element thRow.insertCell().innerText = "#"; // add row header // insert columns for (var i = 0, l = keys.length; i &lt; l; i ++) { var k = keys[i]; thRow.insertCell().innerText = k; } // insert rows of data for (var i = 0, l = data.length; i &lt; l; i ++) { var rowData = data[i], row = tbody.insertRow(); row.insertCell().innerText = i; for (var j = 0, l = keys.length; j &lt; l; j ++) { var elem = rowData[keys[j]]; row.insertCell().innerText = elem; } } </code></pre> <p>Whereas, if I create a table using <code>document.createElement</code> and <code>appendChild</code>, I get the order I would expect:</p> <p><img src="https://i.stack.imgur.com/Fvp7R.png" alt="AppendChild pic"></p> <p>Generated by:</p> <pre class="lang-js prettyprint-override"><code>// now do the same thing, but using appendChild var byChildTable = document.createElement("table"); byChildTable.setAttribute("class", "table"); thead = byChildTable.appendChild(document.createElement("thead")); thRow = thead.appendChild(document.createElement("tr")); // create table header thRow.appendChild(document.createElement("td")).innerText = "#"; for (var i = 0, l = keys.length; i &lt; l; i ++) { var key = keys[i]; thRow.appendChild(document.createElement("td")).innerText = key; } // insert table data by row tbody = byChildTable.appendChild(document.createElement("tbody")); for (var i = 0, l = data.length; i &lt; l; i ++) { var rowData = data[i], row = tbody.appendChild(document.createElement("tr")); row.appendChild(document.createElement("td")).innerText = i; for (var j = 0, l = keys.length; j &lt; l; j ++) { var elem = rowData[keys[j]]; row.appendChild(document.createElement("td")).innerText = elem; } } </code></pre> <h3>Question</h3> <p>How do I control the order it puts the elements in the DOM? Is there any way to change this? I guess otherwise I could iterate in reverse order, but even that way, you still can't insert with <code>table.insertRow()</code>. It's just a bummer because the <code>insertRow()</code> and <code>insertCell()</code> methods seem much clearer than <code>table.appendChild(document.createElement("tr"))</code> etc.</p>
15,866,688
4
6
null
2013-04-07 18:55:48.063 UTC
5
2018-11-20 07:09:54.847 UTC
null
null
null
null
1,316,786
null
1
22
javascript|html|dom|html-table
82,617
<p>The <code>.insertRow</code> and <code>.insertCell</code> methods take an index. In absence of the index, the default value is <code>-1</code> in most browsers, however some browsers may use <code>0</code> or may throw an error, so it's best to provide this explicitly.</p> <p>To to an append instead, just provide <code>-1</code>, and an append will be done</p> <pre><code>var row = table.insertRow(-1); var cell = row.insertCell(-1); </code></pre> <p><a href="https://developer.mozilla.org/en-US/docs/DOM/table.insertRow" rel="noreferrer">https://developer.mozilla.org/en-US/docs/DOM/table.insertRow</a></p>
15,602,667
Possible approach to secure a Rest API endpoints using Facebook OAuth
<p>I've been reading a lot about the topic but all I find are obsolete or partial answers, which don't really help me that much and actually just confused me more. I'm writing a Rest API (Node+Express+MongoDB) that is accessed by a web app (hosted on the same domain than the API) and an Android app. </p> <p>I want the API to be accessed only by my applications and only by authorized users. I also want the users to be able to signup and login only using their Facebook account, and I need to be able to access some basic info like name, profile pic and email.</p> <p>A possible scenario that I have in mind is:</p> <ol> <li>The user logs-in on the web app using Facebook, the app is granted permission to access the user Facebook information and receives an access token. </li> <li>The web app asks the API to confirm that this user is actually registered on our system, sending the email and the token received by Facebook.</li> <li>The API verifies that the user exists, it stores into the DB (or Redis) the username, the token and a timestamp and then goes back to the client app.</li> <li>Each time the client app hits one of the API endpoint, it will have to provide the username and the token, other than other info.</li> <li>The API each time verifies that the provided pair username/token matches the most recent pair username/token stored into the DB (using the timestamp to order), and that no more than 1 hour has passed since we stored these info (again using the timestamp). If that's the case, the API will process the request, otherwise will issue a 401 Unauthorized response.</li> </ol> <p>Does this make sense? Does this approach have any macroscopic security hole that I'm missing? One problem I see using MongoDB to store these info is that the collection will quickly become bloated with old tokens. In this sense I think it would be best to use Redis with an expire policy of 1 hour so that old info will be automatically removed by Redis.</p>
15,603,312
1
0
null
2013-03-24 19:01:59.877 UTC
19
2013-03-24 20:01:09.137 UTC
null
null
null
null
874,634
null
1
23
facebook|api|rest|oauth
6,016
<p>I think the better solution would be this:</p> <ol> <li>Login via Facebook</li> <li>Pass the Facebook AccessToken to the server (over SSL for the android app, and for the web app just have it redirect to an API endpoint after FB login)</li> <li>Check the <code>fb_access_token</code> given, make sure its valid. Get <code>user_id</code>,<code>email</code> and cross-reference this with existing users to see if its a new or old one.</li> <li>Now, create a random, separate <code>api_access_token</code> that you give back to the webapp and android app. If you need Facebook for anything other than login, store that <code>fb_access_token</code> and in your DB associate it with the new <code>api_access_token</code> and your <code>user_id</code>.</li> <li>For every call hereafter, send <code>api_access_token</code> to authenticate it. If you need the <code>fb_access_token</code> for getting more info, you can do so by retrieving it from the DB.</li> </ol> <p><strong>In summary</strong>: Whenever you can, avoid passing the <code>fb_access_token</code>. If the <code>api_access_token</code> is compromised, you have more control to see who the attacker is, what they're doing etc than if they were to get ahold of the <code>fb_access_token</code>. You also have more control over settings an expiration date, extending <code>fb_access_token</code>s, etc</p> <p>Just make sure whenever you pass a access_token of any sort via HTTP, use SSL. </p>
15,738,847
Sending Files using HTTP POST in c#
<p>I have a small C# web application.How can I get the c# code that allows user to send files by HTTP POST.It should be able to send text files,image files,excel, csv, doc (all types of files) without using stream reader and all.</p>
15,739,043
3
3
null
2013-04-01 06:41:26.873 UTC
8
2013-10-29 17:17:48.61 UTC
2013-04-01 06:49:22.293 UTC
null
1,925,983
null
1,925,983
null
1
23
c#|file|web-applications|http-post
60,413
<p>You can try the following code:</p> <pre><code> public void PostMultipleFiles(string url, string[] files) { string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x"); HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url); httpWebRequest.ContentType = "multipart/form-data; boundary=" + boundary; httpWebRequest.Method = "POST"; httpWebRequest.KeepAlive = true; httpWebRequest.Credentials = System.Net.CredentialCache.DefaultCredentials; Stream memStream = new System.IO.MemoryStream(); byte[] boundarybytes =System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary +"\r\n"); string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}"; string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n"; memStream.Write(boundarybytes, 0, boundarybytes.Length); for (int i = 0; i &lt; files.Length; i++) { string header = string.Format(headerTemplate, "file" + i, files[i]); //string header = string.Format(headerTemplate, "uplTheFile", files[i]); byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header); memStream.Write(headerbytes, 0, headerbytes.Length); FileStream fileStream = new FileStream(files[i], FileMode.Open, FileAccess.Read); byte[] buffer = new byte[1024]; int bytesRead = 0; while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { memStream.Write(buffer, 0, bytesRead); } memStream.Write(boundarybytes, 0, boundarybytes.Length); fileStream.Close(); } httpWebRequest.ContentLength = memStream.Length; Stream requestStream = httpWebRequest.GetRequestStream(); memStream.Position = 0; byte[] tempBuffer = new byte[memStream.Length]; memStream.Read(tempBuffer, 0, tempBuffer.Length); memStream.Close(); requestStream.Write(tempBuffer, 0, tempBuffer.Length); requestStream.Close(); try { WebResponse webResponse = httpWebRequest.GetResponse(); Stream stream = webResponse.GetResponseStream(); StreamReader reader = new StreamReader(stream); string var = reader.ReadToEnd(); } catch (Exception ex) { response.InnerHtml = ex.Message; } httpWebRequest = null; } </code></pre>
15,882,991
Range of UTF-8 Characters in C++11 Regex
<p>This question is an extension of <a href="https://stackoverflow.com/questions/11254232/do-c11-regular-expressions-work-with-utf-8-strings">Do C++11 regular expressions work with UTF-8 strings?</a></p> <pre><code>#include &lt;regex&gt; if (std::regex_match ("中", std::regex("中") )) // "\u4e2d" also works std::cout &lt;&lt; "matched\n"; </code></pre> <p>The program is compiled on Mac Mountain Lion with <code>clang++</code> with the following options:</p> <pre><code>clang++ -std=c++0x -stdlib=libc++ </code></pre> <p>The code above works. This is a standard range regex <code>"[一-龠々〆ヵヶ]"</code> for matching any Japanese Kanji or Chinese character. It works in Javascript and Ruby, but I can't seem to get ranges working in C++11, even with using a similar version <code>[\u4E00-\u9fa0]</code>. The code below does not match the string.</p> <pre><code>if (std::regex_match ("中", std::regex("[一-龠々〆ヵヶ]"))) std::cout &lt;&lt; "range matched\n"; </code></pre> <p>Changing locale hasn't helped either. Any ideas?</p> <h1>EDIT</h1> <p>So I have found that all ranges work if you add a <code>+</code> to the end. In this case <code>[一-龠々〆ヵヶ]+</code>, but if you add <code>{1}</code> <code>[一-龠々〆ヵヶ]{1}</code> it does not work. Moreover, it seems to overreach it's boundaries. It won't match latin characters, but it will match <code>は</code> which is <code>\u306f</code> and <code>ぁ</code> which is <code>\u3041</code>. They both lie below <code>\u4E00</code></p> <p>nhahtdh also suggested regex_search which also works without adding <code>+</code> but it still runs into the same problem as above by pulling values outside of its range. Played with the locales a bit as well. Mark Ransom suggests it treats the UTF-8 string as a dumb set of bytes, I think this is possibly what it is doing.</p> <p>Further pushing the theory that UTF-8 is getting jumbled some how, <code>[a-z]{1}</code> and <code>[a-z]+</code> matches <code>a</code>, but only <code>[一-龠々〆ヵヶ]+</code> matches any of the characters, not <code>[一-龠々〆ヵヶ]{1}</code>.</p>
15,895,746
1
11
null
2013-04-08 15:22:38.957 UTC
7
2013-04-16 07:40:53.25 UTC
2017-05-23 10:29:37.407 UTC
null
-1
null
412,417
null
1
30
c++|regex|unicode|utf-8|c++11
7,179
<p>Encoded in UTF-8, the string <code>"[一-龠々〆ヵヶ]"</code> is equal to this one: <code>"[\xe4\xb8\x80-\xe9\xbe\xa0\xe3\x80\x85\xe3\x80\x86\xe3\x83\xb5\xe3\x83\xb6]"</code>. And this is not the <strike>droid</strike> character class you are looking for.</p> <p>The character class you are looking for is the one that includes:</p> <ul> <li>any character in the range U+4E00..U+9FA0; or</li> <li>any of the characters 々, 〆, ヵ, ヶ.</li> </ul> <p>The character class you specified is the one that includes:</p> <ul> <li>any of the "characters" \xe4 or \xb8; or</li> <li>any "character" in the range \x80..\xe9; or</li> <li>any of the "characters" \xbe, \xa0, \xe3, \x80, \x85, \xe3 (again), \x80 (again), \x86, \xe3 (again), \x83, \xb5, \xe3 (again), \x83 (again), \xb6.</li> </ul> <p>Messy isn't it? Do you see the problem?</p> <p>This will not match "latin" characters (which I assume you mean things like a-z) because in UTF-8 those all use a single byte below 0x80, and none of those is in that messy character class.</p> <p>It will not match <code>"中"</code> either because <code>"中"</code> has three "characters", and your regex matches only one "character" out of that weird long list. Try <code>assert(std::regex_match("中", std::regex("...")))</code> and you will see.</p> <p>If you add a <code>+</code> it works because <code>"中"</code> has three of those "characters" in your weird long list, and now your regex matches one or more.</p> <p>If you instead add <code>{1}</code> it does not match because we are back to matching three "characters" against one.</p> <p>Incidentally <code>"中"</code> matches <code>"中"</code> because we are matching the three "characters" against the same three "characters" in the same order.</p> <p>That the regex with <code>+</code> will actually match some undesired things because it does not care about order. Any character that can be made from that list of bytes in UTF-8 will match. It will match <code>"\xe3\x81\x81"</code> (ぁ U+3041) and it will even match invalid UTF-8 input like <code>"\xe3\xe3\xe3\xe3"</code>.</p> <p>The bigger problem is that you are using a regex library that does not even have level 1 support for Unicode, the bare minimum required. It munges bytes and there isn't much your precious tiny regex can do about it.</p> <p>And the even bigger problem is that you are using a hardcoded set of characters to specify "any Japanese Kanji or Chinese character". Why not use the Unicode Script property for that?</p> <p><code>R"(\p{Script=Han})"</code></p> <p>Oh right, this won't work with C++11 regexes. For a moment there I almost forgot those are annoyingly worse than useless with Unicode.</p> <p>So what should you do?</p> <p>You could decode your input into a <code>std::u32string</code> and use <code>char32_t</code> all over for the matching. That would not give you this mess, but you would still be hardcoding ranges and exceptions when you mean "a set of characters that share a certain property".</p> <p>I recommend you forget about C++11 regexes and use some regular expression library that has the bare minimum level 1 Unicode support, like the one in <a href="http://icu-project.org">ICU</a>.</p>
15,962,421
How can I disable scratch preview window?
<p>While coding Python, I like Vim's omnicompletion function, but I don't want Scratch Window to pop up at top. </p> <p>How can I disable it?</p> <p>(I'm using gVim 7.3)</p>
15,963,488
2
0
null
2013-04-12 03:11:38.743 UTC
4
2019-03-11 09:19:50.2 UTC
2017-04-12 23:28:37.357 UTC
null
4,694,621
null
423,905
null
1
38
vim|autocomplete
17,439
<p>This behavior is defined by the presence of <code>preview</code> in the value of the <code>'completeopt'</code> option.</p> <p>The default value is:</p> <pre><code>menu,preview </code></pre> <p>To remove <code>preview</code>, simply add this line to your <code>~/.vimrc</code> or modify an existing <code>completeopt</code> line:</p> <pre><code>set completeopt-=preview </code></pre>
32,108,179
Linear Regression :: Normalization (Vs) Standardization
<p>I am using Linear regression to predict data. But, I am getting totally contrasting results when I Normalize (Vs) Standardize variables. </p> <p>Normalization = x -xmin/ xmax – xmin   Zero Score Standardization = x - xmean/ xstd  </p> <pre><code>a) Also, when to Normalize (Vs) Standardize ? b) How Normalization affects Linear Regression? c) Is it okay if I don't normalize all the attributes/lables in the linear regression? </code></pre> <p>Thanks, Santosh</p>
32,113,835
5
2
null
2015-08-20 01:32:29.85 UTC
39
2022-02-10 11:18:00.097 UTC
2015-08-20 16:23:00.883 UTC
null
4,443,264
null
4,443,264
null
1
39
machine-learning|linear-regression|feature-extraction
56,005
<p>Note that the results might not necessarily be so different. You might simply need different hyperparameters for the two options to give similar results.</p> <p>The ideal thing is to test what works best for your problem. If you can't afford this for some reason, most algorithms will probably benefit from standardization more so than from normalization.</p> <p>See <a href="http://spartanideas.msu.edu/2014/07/11/about-feature-scaling-and-normalization/" rel="noreferrer">here</a> for some examples of when one should be preferred over the other:</p> <blockquote> <p>For example, in clustering analyses, standardization may be especially crucial in order to compare similarities between features based on certain distance measures. Another prominent example is the Principal Component Analysis, where we usually prefer standardization over Min-Max scaling, since we are interested in the components that maximize the variance (depending on the question and if the PCA computes the components via the correlation matrix instead of the covariance matrix; but more about PCA in my previous article).</p> <p>However, this doesn’t mean that Min-Max scaling is not useful at all! A popular application is image processing, where pixel intensities have to be normalized to fit within a certain range (i.e., 0 to 255 for the RGB color range). Also, typical neural network algorithm require data that on a 0-1 scale.</p> </blockquote> <p>One disadvantage of normalization over standardization is that it loses some information in the data, especially about outliers.</p> <p>Also on the linked page, there is this picture:</p> <p><a href="https://i.stack.imgur.com/hcP4l.png" rel="noreferrer"><img src="https://i.stack.imgur.com/hcP4l.png" alt="Plots of a standardized and normalized data set" /></a></p> <p>As you can see, scaling clusters all the data very close together, which may not be what you want. It might cause algorithms such as gradient descent to take longer to converge to the same solution they would on a standardized data set, or it might even make it impossible.</p> <p>&quot;Normalizing variables&quot; doesn't really make sense. The correct terminology is &quot;normalizing / scaling the features&quot;. If you're going to normalize or scale one feature, you should do the same for the rest.</p>
56,622,926
Safari Viewport Bug, Issues with Fixed Position and Bottom or Top
<p>I'm experiencing something strange in iOS 12.3.1 Safari. <strong>This issue dates back to at least iOS 12.2,</strong> but I imagine it's been a problem for much longer than that.</p> <p>The issue manifests itself when trying to align an element to the bottom axis of the viewport, and is a problem in both portrait and landscape mode.</p> <p>In order to reproduce the problem, the element must have a <code>position</code> of <code>fixed</code> or <code>absolute</code>, yet it doesn't matter whether you position the element with <code>top</code> and <code>transform</code> or <code>bottom</code>.</p> <h1>Portrait Mode</h1> <p>The issue only manifests itself in portrait mode <strong>if Safari is displaying its condensed URL bar,</strong> which replaces the normal URL and menu bars, <strong>and there is no vertical overflow.</strong></p> <p><em><strong>Normal URL and Menu Bars // Condensed URL Bar</strong></em></p> <p><a href="https://i.stack.imgur.com/AASvam.png" rel="noreferrer"><img src="https://i.stack.imgur.com/AASvam.png" alt="enter image description here" /></a> <a href="https://i.stack.imgur.com/1jDcWm.png" rel="noreferrer"><img src="https://i.stack.imgur.com/1jDcWm.png" alt="enter image description here" /></a></p> <p>Notably, the condensed menu bar is only ever displayed when there is either vertical overflow and the browser is scrolled downwards or when the browser's orientation has been changed from portrait to landscape and then back again (despite whether or not there is vertical overflow).</p> <p><em><strong>Changing Orientation with Vertical Overflow // Without Overflow</strong></em></p> <p><a href="https://i.stack.imgur.com/LfdtKm.png" rel="noreferrer"><img src="https://i.stack.imgur.com/LfdtKm.png" alt="enter image description here" /></a> <a href="https://i.stack.imgur.com/VFRyfm.png" rel="noreferrer"><img src="https://i.stack.imgur.com/VFRyfm.png" alt="enter image description here" /></a></p> <p>I'm not sure exactly what's happening here.</p> <h1>Landscape Mode</h1> <p>The issue with landscape mode always and only occurs when the normal navigation bar is displayed at the top of the page. The navigation bar is only ever hidden in landscape mode due to downward scrolling or orientation change from portrait to landscape.</p> <p><em><strong>With Vertical Overflow</strong></em></p> <p><a href="https://i.stack.imgur.com/2yL5Im.png" rel="noreferrer"><img src="https://i.stack.imgur.com/2yL5Im.png" alt="enter image description here" /></a> <a href="https://i.stack.imgur.com/03OGcm.png" rel="noreferrer"><img src="https://i.stack.imgur.com/03OGcm.png" alt="enter image description here" /></a></p> <p><em><strong>Without Vertical Overflow</strong></em></p> <p><a href="https://i.stack.imgur.com/2yL5Im.png" rel="noreferrer"><img src="https://i.stack.imgur.com/2yL5Im.png" alt="enter image description here" /></a> <a href="https://i.stack.imgur.com/wNvg0m.png" rel="noreferrer"><img src="https://i.stack.imgur.com/wNvg0m.png" alt="enter image description here" /></a></p> <p>What's interesting is that the height of the navigation bar in landscape mode clearly offsets the viewport so that position of <code>bottom: 0</code> or <code>top: 100%</code> is pushed outside of the viewport when the navigation bar is being displayed.</p> <h1>Crappy &quot;Workaround&quot; for Portrait Mode</h1> <p>It's a super hack-ish workaround, and a crappy workaround at that, but it's the only thing so far that causes <code>position: fixed; bottom: 0;</code> to actually position an element at the bottom of the viewport after switching orientations if there is no overflow.</p> <pre><code>&lt;div style='height: 0'&gt; &lt;!-- the quantity of &lt;br&gt; elements must create vertical overflow --&gt; &lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt; &lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt; &lt;!-- this does not work without the space character --&gt; &amp;nbsp; &lt;/div&gt; </code></pre> <p>However, I just noticed that it creates an invisible vertical overflow and thus unnecessary vertical scrolling in at least Safari and Chrome. I'm also worried that it might cause other issues on other devices in other browser that I'm unable to test.</p> <hr> <p>It absolutely sucks that a website has to sometimes look like crap for the sake of user-experience due to this bug.</p> <h1>Does anybody out there have any idea what is happening?</h1> <h1>Anybody aware of any workarounds?</h1> <h1>Anybody aware of an actual solution?</h1>
56,671,096
1
4
null
2019-06-16 22:01:18.273 UTC
9
2019-06-21 03:15:22.703 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
7,543,162
null
1
33
html|css|iphone|mobile|safari
19,967
<p>Hello this question kind of got me at first and I thought back to my days poking around in HTML and CSS for hours on end trying to get things right. Alas all those hours of missery have been for this moment. </p> <p><code>vh</code> used to be calculated by the current viewport of your browser. If you loaded a site in your browser, <code>1vh</code> would be the same as 1% of your screen height, and then minus the browser interface.</p> <p>But! If you wanted to scroll, it gets tricky. Once you brush past the browser interface (in this case your address bar), you would have a wierd jump in your content because the <code>vh</code> would be updated.</p> <p>Safari for iOS was actually was one of the first to implement a fix. They set a fixed <code>vh</code> value based on the max screen height. Then the user wouldn't experience the jump in content, but .... yup, there's always a but...</p> <p>Having the fixed value is awesome, except when you wanna have a full sized element, or <strong>an element with fixed position at the bottom of the screen</strong> because then it would get cropped out! </p> <p>That is your problem....and say goodbye to it, because...</p> <p>This is your solution!!</p> <p><strong>css:</strong></p> <pre><code>.my-element { height: 100vh; /* This is for browsers that don't support custom properties */ height: calc(var(--vh, 1vh) * 100); } </code></pre> <p><strong>js:</strong></p> <pre><code>// Get the viewport height and multiply it by 1% to get a value for a vh unit let vh = window.innerHeight * 0.01; // Then set the custom --vh value to the root of the document document.documentElement.style.setProperty('--vh', `${vh}px`); </code></pre> <p>Now you can use --vh as your height value like we would any other vh unit, multiply it by 100 and you have the full height we want.</p> <p>One thing left, the js up there runs, but we never update the element's size when the viewport changes, so that wouldn't work yet, you need a listener...</p> <p><strong>more js:</strong></p> <pre><code>// We listen to the resize event window.addEventListener('resize', () =&gt; { // Update the element's size let vh = window.innerHeight * 0.01; document.documentElement.style.setProperty('--vh', `${vh}px`); }); </code></pre> <p>Cheers!</p>
13,408,419
How do I tell if Intent extras exist in Android?
<p>I have this code that checks for a value of an extra in an Intent on an Activity that is called from many places in my app:</p> <pre><code>getIntent().getExtras().getBoolean("isNewItem") </code></pre> <p>If isNewItem isn't set, will my code crash? Is there any way to tell if it's been set or not before I call it?</p> <p>What is the proper way to handle this?</p>
13,408,731
5
0
null
2012-11-16 00:05:52.873 UTC
16
2018-01-31 19:05:22.14 UTC
2012-11-16 01:01:07.18 UTC
null
639,520
null
546,509
null
1
57
java|android|android-intent
65,113
<p>As others have said, both <code>getIntent()</code> and <code>getExtras()</code> may return null. Because of this, you don't want to chain the calls together, otherwise you might end up calling <code>null.getBoolean("isNewItem");</code> which will throw a <code>NullPointerException</code> and cause your application to crash.</p> <p>Here's how I would accomplish this. I think it's formatted in the nicest way and is very easily understood by someone else who might be reading your code.</p> <pre><code>// You can be pretty confident that the intent will not be null here. Intent intent = getIntent(); // Get the extras (if there are any) Bundle extras = intent.getExtras(); if (extras != null) { if (extras.containsKey("isNewItem")) { boolean isNew = extras.getBoolean("isNewItem", false); // TODO: Do something with the value of isNew. } } </code></pre> <p>You don't actually need the call to <code>containsKey("isNewItem")</code> as <code>getBoolean("isNewItem", false)</code> will return false if the extra does not exist. You could condense the above to something like this:</p> <pre><code>Bundle extras = getIntent().getExtras(); if (extras != null) { boolean isNew = extras.getBoolean("isNewItem", false); if (isNew) { // Do something } else { // Do something else } } </code></pre> <p>You can also use the <code>Intent</code> methods to access your extras directly. This is probably the cleanest way to do so:</p> <pre><code>boolean isNew = getIntent().getBooleanExtra("isNewItem", false); </code></pre> <p>Really any of the methods here are acceptable. Pick one that makes sense to you and do it that way.</p>
13,265,153
How do I import a CSV file in R?
<p>I have a <code>.csv</code> file in my workstation. How can I open that file in R and do statistical calculation?</p>
13,265,177
1
1
null
2012-11-07 07:38:45.59 UTC
10
2018-05-07 18:43:05.92 UTC
2015-12-22 06:58:03.987 UTC
null
1,079,354
null
1,758,521
null
1
118
r|csv|import
314,312
<p>You would use the <code>read.csv</code> function; for example:</p> <pre><code>dat = read.csv("spam.csv", header = TRUE) </code></pre> <p>You can also reference <a href="http://www.cyclismo.org/tutorial/R/input.html#read" rel="noreferrer">this tutorial</a> for more details.</p> <p><strong>Note:</strong> make sure the <code>.csv</code> file to read is in your working directory (using <code>getwd()</code>) or specify the right path to file. If you want, you can set the current directory using <a href="https://www.rdocumentation.org/packages/base/versions/3.4.3/topics/getwd" rel="noreferrer"><code>setwd</code></a>.</p>
20,444,578
Get current language with angular-translate
<p>Is there a way to get the current used language in a controller (without <code>$translateProvider</code>)?</p> <p>Couldn't find anything in the <code>$translate</code> service.</p>
20,445,143
9
2
null
2013-12-07 17:53:46.857 UTC
19
2022-09-22 07:50:43.457 UTC
2018-04-04 10:00:28.007 UTC
null
1,423,874
null
1,641,422
null
1
86
angularjs|angular-translate
83,698
<p><code>$translate.use()</code> is a getter and setter.</p> <p>See this demo found in links of docs:</p> <p><a href="http://jsfiddle.net/PascalPrecht/eUGWJ/7/" rel="noreferrer">http://jsfiddle.net/PascalPrecht/eUGWJ/7/</a></p>
24,244,326
Swift: Global constant naming convention?
<p>In Swift, it seems that global constants should be camelCase.</p> <p>For example:</p> <pre><code>let maximumNumberOfLoginAttempts = 10 </code></pre> <p>Is that correct?</p> <p>I'm used to all caps, e.g., <code>MAXIMUM_NUMBER_OF_LOGIN_ATTEMPTS</code>, from C, but I want to acquiesce to Swift conventions.</p>
38,078,903
8
3
null
2014-06-16 12:58:02.513 UTC
13
2022-04-22 02:01:33.43 UTC
null
null
null
null
242,933
null
1
71
naming-conventions|constants|swift|global
29,996
<p>Swift 3 API guidelines state that &quot;Names of types and protocols are UpperCamelCase. Everything else is lowerCamelCase.&quot;</p> <p><a href="https://swift.org/documentation/api-design-guidelines/" rel="nofollow noreferrer">https://swift.org/documentation/api-design-guidelines/</a></p> <p>Ideally your global constants will be located within an <code>enum</code>, <code>extension</code>, or <code>struct</code> of some sort, which would be UpperCamelCase, and all properties in that space would be lowerCamelCase.</p> <pre class="lang-swift prettyprint-override"><code>struct LoginConstants { static let maxAttempts = 10 } </code></pre> <p>And accessed like so,</p> <pre><code>if attempts &gt; LoginConstants.maxAttempts { ...} </code></pre> <p>(credit to <a href="https://stackoverflow.com/a/62028779">Ryan Maloney's answer</a> for calling out the benefits of <code>enum</code>)</p>
3,648,564
python subclass access to class variable of parent
<p>I was surprised to to learn that a class variable of a subclass can't access a class variable of the parent without specifically indicating the class name of the parent:</p> <pre><code>&gt;&gt;&gt; class A(object): ... x = 0 ... &gt;&gt;&gt; class B(A): ... y = x+1 ... Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 2, in B NameError: name 'x' is not defined &gt;&gt;&gt; class B(A): ... y = A.x + 1 ... &gt;&gt;&gt; B.x 0 &gt;&gt;&gt; B.y 1 </code></pre> <p>Why is it that in defining B.y I have to refer to A.x and not just x? This is counter to my intuition from instance variables, and since I can refer to B.x after B is defined.</p>
3,648,653
2
0
null
2010-09-06 01:34:42.243 UTC
13
2010-09-06 02:28:09.34 UTC
null
null
null
null
136,598
null
1
41
python|subclass|class-variables
42,004
<p>In Python, the body of a class is executed in its own namespace before the class is created (after which, the members of that namespace become the members of the class). So when the interpreter reaches y = x+1, class B does not exist yet at that point and, therefore, has no parent.</p> <p>For more details, see <a href="http://docs.python.org/reference/compound_stmts.html#class-definitions" rel="noreferrer">http://docs.python.org/reference/compound_stmts.html#class-definitions</a></p>