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
11,082,062
how to read a csv file from a url?
<p>Im trying to create a web service which gets to a URL e.g. <code>www.domain.co.uk/prices.csv</code> and then reads the csv file. Is this possible and how? Ideally without downloading the csv file?</p>
11,082,228
5
3
null
2012-06-18 11:40:53.373 UTC
4
2019-12-30 09:51:41.847 UTC
2012-06-18 11:50:57.247 UTC
null
1,181,553
null
569,654
null
1
22
c#|csv
40,337
<p>You could use:</p> <pre><code>public string GetCSV(string url) { HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); StreamReader sr = new StreamReader(resp.GetResponseStream()); string results = sr.ReadToEnd(); sr.Close(); return results; } </code></pre> <p>And then to split it:</p> <pre><code>public static void SplitCSV() { List&lt;string&gt; splitted = new List&lt;string&gt;(); string fileList = getCSV("http://www.google.com"); string[] tempStr; tempStr = fileList.Split(','); foreach (string item in tempStr) { if (!string.IsNullOrWhiteSpace(item)) { splitted.Add(item); } } } </code></pre> <p>Though there are plenty of CSV parsers out there and i would advise against rolling your own. <a href="http://www.filehelpers.net/" rel="noreferrer">FileHelpers</a> is a good one.</p>
11,114,625
Android Canvas Redo and Undo Operation
<p>I am working on a drawing project. My code is working perfectly other than canvas redo and undo operations. My undo operation removes paths from the <code>paths</code> ArrayList and saves to the <code>undonePaths</code> ArrayList, and the redo operation removes the last element from <code>undonePaths</code> and saves to <code>paths</code>.</p> <p>Here's my code:</p> <pre><code>import java.util.ArrayList; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; public class DrawView extends View implements OnTouchListener { private Canvas mCanvas; private Path mPath; private Paint mPaint; private ArrayList&lt;Path&gt; paths = new ArrayList&lt;Path&gt;(); private ArrayList&lt;Path&gt; undonePaths = new ArrayList&lt;Path&gt;(); private Bitmap im; public DrawView(Context context) { super(context); setFocusable(true); setFocusableInTouchMode(true); this.setOnTouchListener(this); mPaint = new Paint(); mPaint.setAntiAlias(true); mPaint.setDither(true); mPaint.setColor(0xFFFFFFFF); mPaint.setStyle(Paint.Style.STROKE); mPaint.setStrokeJoin(Paint.Join.ROUND); mPaint.setStrokeCap(Paint.Cap.ROUND); mPaint.setStrokeWidth(6); mCanvas = new Canvas(); mPath = new Path(); paths.add(mPath); im=BitmapFactory.decodeResource(context.getResources(),R.drawable.ic_launcher); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); } @Override protected void onDraw(Canvas canvas) { //mPath = new Path(); //canvas.drawPath(mPath, mPaint); for (Path p : paths){ canvas.drawPath(p, mPaint); } } private float mX, mY; private static final float TOUCH_TOLERANCE = 4; private void touch_start(float x, float y) { mPath.reset(); mPath.moveTo(x, y); mX = x; mY = y; } private void touch_move(float x, float y) { float dx = Math.abs(x - mX); float dy = Math.abs(y - mY); if (dx &gt;= TOUCH_TOLERANCE || dy &gt;= TOUCH_TOLERANCE) { mPath.quadTo(mX, mY, (x + mX)/2, (y + mY)/2); mX = x; mY = y; } } private void touch_up() { mPath.lineTo(mX, mY); // commit the path to our offscreen mCanvas.drawPath(mPath, mPaint); // kill this so we don't double draw mPath = new Path(); paths.add(mPath); } public void onClickUndo () { if (paths.size()&gt;0) { undonePaths.add(paths.remove(paths.size()-1)); invalidate(); } else { } //toast the user } public void onClickRedo (){ if (undonePaths.size()&gt;0) { paths.add(undonePaths.remove(undonePaths.size()-1)); invalidate(); } else { } //toast the user } @Override public boolean onTouch(View arg0, MotionEvent event) { float x = event.getX(); float y = event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: touch_start(x, y); invalidate(); break; case MotionEvent.ACTION_MOVE: touch_move(x, y); invalidate(); break; case MotionEvent.ACTION_UP: touch_up(); invalidate(); break; } return true; } } </code></pre> <p>This code is working perfectly for drawing but not working perfectly for undo and redo operations. What's wrong with my code?</p> <p>Here's my full source code:</p> <p><a href="http://www.4shared.com/rar/8PQQEZdH/test_draw.html" rel="noreferrer">http://www.4shared.com/rar/8PQQEZdH/test_draw.html</a></p> <h2><strong>UPDATED:</strong></h2> <p><strong>Finally my problem was solved; here's my drawing class:</strong></p> <pre><code>import java.util.ArrayList; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; public class DrawView extends View implements OnTouchListener { private Canvas mCanvas; private Path mPath; private Paint mPaint; private ArrayList&lt;Path&gt; paths = new ArrayList&lt;Path&gt;(); private ArrayList&lt;Path&gt; undonePaths = new ArrayList&lt;Path&gt;(); private Bitmap im; public DrawView(Context context) { super(context); setFocusable(true); setFocusableInTouchMode(true); this.setOnTouchListener(this); mPaint = new Paint(); mPaint.setAntiAlias(true); mPaint.setDither(true); mPaint.setColor(0xFFFFFFFF); mPaint.setStyle(Paint.Style.STROKE); mPaint.setStrokeJoin(Paint.Join.ROUND); mPaint.setStrokeCap(Paint.Cap.ROUND); mPaint.setStrokeWidth(6); mCanvas = new Canvas(); mPath = new Path(); im=BitmapFactory.decodeResource(context.getResources(),R.drawable.ic_launcher); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); } @Override protected void onDraw(Canvas canvas) { //mPath = new Path(); //canvas.drawPath(mPath, mPaint); for (Path p : paths){ canvas.drawPath(p, mPaint); } canvas.drawPath(mPath, mPaint); } private float mX, mY; private static final float TOUCH_TOLERANCE = 4; private void touch_start(float x, float y) { undonePaths.clear(); mPath.reset(); mPath.moveTo(x, y); mX = x; mY = y; } private void touch_move(float x, float y) { float dx = Math.abs(x - mX); float dy = Math.abs(y - mY); if (dx &gt;= TOUCH_TOLERANCE || dy &gt;= TOUCH_TOLERANCE) { mPath.quadTo(mX, mY, (x + mX)/2, (y + mY)/2); mX = x; mY = y; } } private void touch_up() { mPath.lineTo(mX, mY); // commit the path to our offscreen mCanvas.drawPath(mPath, mPaint); // kill this so we don't double draw paths.add(mPath); mPath = new Path(); } public void onClickUndo () { if (paths.size()&gt;0) { undonePaths.add(paths.remove(paths.size()-1)); invalidate(); } else { } //toast the user } public void onClickRedo (){ if (undonePaths.size()&gt;0) { paths.add(undonePaths.remove(undonePaths.size()-1)); invalidate(); } else { } //toast the user } @Override public boolean onTouch(View arg0, MotionEvent event) { float x = event.getX(); float y = event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: touch_start(x, y); invalidate(); break; case MotionEvent.ACTION_MOVE: touch_move(x, y); invalidate(); break; case MotionEvent.ACTION_UP: touch_up(); invalidate(); break; } return true; } } </code></pre> <p><strong>That code is working perfectly...!</strong></p>
11,114,928
3
0
null
2012-06-20 07:17:33.02 UTC
16
2019-04-14 05:48:06.463 UTC
2019-04-14 05:48:06.463 UTC
null
1,427,098
null
1,269,086
null
1
24
android
21,132
<p>At first glance I see the following problems:</p> <ul> <li>By adding your empty <code>Path</code> to <code>paths</code> as soon as you make it, you're going to have a problem as soon as you undo: you're popping that empty <code>Path</code> first, making the first undo not seem to work. Then if you draw into that <code>Path</code>, it's not added to <code>paths</code>. The solution is to add the completed <code>Path</code> to paths in <code>touch_up()</code> before creating a new one.</li> </ul> <p>That is, remove</p> <pre><code>paths.add(mPath); </code></pre> <p>from the constructor, and in <code>touch_up()</code>, change</p> <pre><code>mPath = new Path(); paths.add(mPath); </code></pre> <p>to</p> <pre><code>paths.add(mPath); mPath = new Path(); </code></pre> <p>You'll also want to add</p> <pre><code>canvas.drawPath(mPath, mPaint); </code></pre> <p>after your <code>for</code> loop in <code>onDraw()</code> in order to draw the in-progress <code>Path</code>.</p> <ul> <li>You're not emptying <code>undonePaths</code> when the user starts drawing again.</li> </ul>
10,969,673
What is the order of ActiveRecord callbacks and validations?
<p>I was wondering in what order are callbacks and validations called when an ActiveRecord object is created.</p> <p>Let’s say I have some custom validations &amp; callbacks like the following:</p> <pre><code>validates :reference_code, :if =&gt; :reference_code, :on =&gt; :create before_create :assign_reference </code></pre> <p>which one will run first? The callback needs to happen first or else the validation may fail.</p>
11,021,211
3
1
null
2012-06-10 14:51:51.567 UTC
25
2022-06-01 16:03:20.983 UTC
2013-01-16 01:33:05.657 UTC
null
211,563
null
395,842
null
1
58
ruby-on-rails|ruby-on-rails-3|validation|activerecord
36,169
<p>The most-up-to-date version of this list for the latest version of Rails can be found in the <a href="http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html" rel="noreferrer"><code>ActiveRecord::Callbacks</code> documentation</a>. The lists for Rails 4, 3 &amp; 2 are below.</p> <h2>Rails 4</h2> <p>The most up-to-date version of this list can be found in the <a href="http://guides.rubyonrails.org/active_record_callbacks.html#available-callbacks" rel="noreferrer">Rails 4 Guides</a>.</p> <h3>Creating an object</h3> <ul> <li><code>before_validation</code></li> <li><code>after_validation</code></li> <li><code>before_save</code></li> <li><code>around_save</code></li> <li><code>before_create</code></li> <li><code>around_create</code></li> <li><code>after_create</code></li> <li><code>after_save</code></li> <li><code>after_commit/after_rollback</code></li> </ul> <h3>Updating an object</h3> <ul> <li><code>before_validation</code></li> <li><code>after_validation</code></li> <li><code>before_save</code></li> <li><code>around_save</code></li> <li><code>before_update</code></li> <li><code>around_update</code></li> <li><code>after_update</code></li> <li><code>after_save</code></li> <li><code>after_commit/after_rollback</code></li> </ul> <h3>Destroying an object</h3> <ul> <li><code>before_destroy</code></li> <li><code>around_destroy</code></li> <li><code>after_destroy</code></li> <li><code>after_commit/after_rollback</code></li> </ul> <h2>Rails 3</h2> <p>The most up-to-date version of this list can be found in the <a href="http://guides.rubyonrails.org/v3.2.21/active_record_validations_callbacks.html#available-callbacks" rel="noreferrer">Rails 3 Guides</a>.</p> <h3>Creating an object</h3> <ul> <li><code>before_validation</code></li> <li><code>after_validation</code></li> <li><code>before_save</code></li> <li><code>around_save</code></li> <li><code>before_create</code></li> <li><code>around_create</code></li> <li><code>after_create</code></li> <li><code>after_save</code></li> </ul> <h3>Updating an object</h3> <ul> <li><code>before_validation</code></li> <li><code>after_validation</code></li> <li><code>before_save</code></li> <li><code>around_save</code></li> <li><code>before_update</code></li> <li><code>around_update</code></li> <li><code>after_update</code></li> <li><code>after_save</code></li> </ul> <h3>Destroying an object</h3> <ul> <li><code>before_destroy</code></li> <li><code>around_destroy</code></li> <li><code>after_destroy</code></li> </ul> <h2>Rails 2</h2> <p>The most up-to-date version of this list can be found in the <a href="http://guides.rubyonrails.org/v2.3.11/activerecord_validations_callbacks.html#available-callbacks" rel="noreferrer">Rails 2.3 Guides</a></p> <h3>Creating an object</h3> <ul> <li><code>before_validation</code></li> <li><code>before_validation_on_create</code></li> <li><code>after_validation</code></li> <li><code>after_validation_on_create</code></li> <li><code>before_save</code></li> <li><code>before_create</code></li> <li><em><code>INSERT</code></em> operation</li> <li><code>after_create</code></li> <li><code>after_save</code></li> </ul> <h3>Updating an object</h3> <ul> <li><code>before_validation</code></li> <li><code>before_validation_on_update</code></li> <li><code>after_validation</code></li> <li><code>after_validation_on_update</code></li> <li><code>before_save</code></li> <li><code>before_update</code></li> <li><em><code>UPDATE</code></em> operation</li> <li><code>after_update</code></li> <li><code>after_save</code></li> </ul> <h3>Destroying an object</h3> <ul> <li><code>before_destroy</code></li> <li><em><code>DELETE</code> operation</em></li> <li><code>after_destroy</code></li> </ul> <p>Since you need to first validate the <code>reference_code</code>, the <code>assign_reference</code> method can be called in the <code>after_validation</code> callback or any callback appearing after it in the list I provided above.</p>
11,373,536
Play framework hangs on startup at: "Loading project definition from"
<p>I am just getting started with Play Framework. I have downloaded and installed play and created a sample java application. When I try to start the play console in the application directory it hangs at "Loading project definition".</p> <pre><code>PS C:\dev\play\javatest&gt; play.bat Getting org.scala-sbt sbt_2.9.1 0.11.3 ... :: retrieving :: org.scala-sbt#boot-app confs: [default] 37 artifacts copied, 0 already retrieved (7245kB/283ms) [info] Loading project definition from C:\dev\play\myFirstApp\project </code></pre> <p>When i try running a Scala application i get a message about it waiting for a lock:</p> <pre><code>PS C:\dev\play\scalatest&gt; play [info] Loading project definition from C:\dev\play\test1\project Waiting for lock on C:\lib\play\repository\.sbt.ivy.lock to be available... </code></pre> <p>Running Windows 7, JDK 1.7.0_05 and Play Framework 2.0.2. Any ideas?</p>
12,605,068
3
0
null
2012-07-07 08:34:52.66 UTC
13
2014-07-24 15:58:58.927 UTC
2013-09-27 21:27:07.337 UTC
null
675,552
null
230,809
null
1
61
playframework
20,330
<p>I just experienced this myself with Play 2 and it turns out it wasn't truly hanging, it was just pulling a maven and downloading the Internet. To verify this is the same behavior you were experiencing edit <code>project/plugins.sbt</code> and replace:</p> <pre><code>logLevel := Level.Warn </code></pre> <p>with</p> <pre><code>logLevel := Level.Debug </code></pre> <p>(Though I am building on OSX I imagine you will experience similar output on Windows.)</p>
11,406,786
What is the combinatory logic equivalent of intuitionistic type theory?
<p>I recently completed a university course which featured Haskell and Agda (a dependent typed functional programming language), and was wondering if it was possible to replace lambda calculus in these with combinatory logic. With Haskell this seems possible using the S and K combinators, thus making it point-free. I was wondering what the equivalent was for Agda. I.e., can one make a dependently typed functional programming language equivalent to Agda without using any variables?</p> <p>Also, is it possible to somehow replace quantification with combinators? I don't know if this is a coincidence but universal quantification for example makes a type signature look like a lambda expression. Is there a way to remove universal quantification from a type signature without changing its meaning? E.g. in:</p> <pre><code>forall a : Int -&gt; a &lt; 0 -&gt; a + a &lt; a </code></pre> <p>Can the same thing be expressed without using a forall?</p>
11,795,066
2
1
null
2012-07-10 04:47:50.26 UTC
36
2012-08-08 06:13:56.83 UTC
2012-07-11 08:41:09.457 UTC
null
759,019
null
1,010,494
null
1
87
haskell|types|functional-programming|logic|agda
5,029
<p>So I thought about it a bit more and made some progress. Here's a first stab at encoding Martin-Löf's delightfully simple (but inconsistent) <code>Set : Set</code> system in a combinatory style. It's not a good way to finish, but it's the easiest place to get started. The syntax of this type theory is just lambda-calculus with type annotations, Pi-types, and a universe Set.</p> <h3>The Target Type Theory</h3> <p>For completeness' sake, I'll present the rules. Context validity just says you can build contexts from empty by adjoining fresh variables inhabiting <code>Set</code>s. </p> <pre><code> G |- valid G |- S : Set -------------- ----------------------------- x fresh for G . |- valid G, x:S |- valid </code></pre> <p>And now we can say how to synthesize types for terms in any given context, and how to change the type of something up to the computational behaviour of the terms it contains.</p> <pre><code> G |- valid G |- S : Set G |- T : Pi S \ x:S -&gt; Set ------------------ --------------------------------------------- G |- Set : Set G |- Pi S T : Set G |- S : Set G, x:S |- t : T x G |- f : Pi S T G |- s : S ------------------------------------ -------------------------------- G |- \ x:S -&gt; t : Pi S T G |- f s : T s G |- valid G |- s : S G |- T : Set -------------- x:S in G ----------------------------- S ={beta} T G |- x : S G |- s : T </code></pre> <p>In a small variation from the original, I've made lambda the only binding operator, so the second argument of Pi should be a function computing the way the return type depends on the input. By convention (e.g. in Agda, but sadly not in Haskell), scope of lambda extends rightwards as far as possible, so you can often leave abstractions unbracketed when they're the last argument of a higher-order operator: you can see I did that with Pi. Your Agda type <code>(x : S) -&gt; T</code> becomes <code>Pi S \ x:S -&gt; T</code>.</p> <p>(<em>Digression</em>. Type annotations on lambda are necessary if you want to be able to <em>synthesize</em> the type of abstractions. If you switch to type <em>checking</em> as your modus operandi, you still need annotations to check a beta-redex like <code>(\ x -&gt; t) s</code>, as you have no way to guess the types of the parts from that of the whole. I advise modern designers to check types and exclude beta-redexes from the very syntax.)</p> <p>(<em>Digression</em>. This system is inconsistent as <code>Set:Set</code> allows the encoding of a variety of "liar paradoxes". When Martin-Löf proposed this theory, Girard sent him an encoding of it in his own inconsistent System U. The subsequent paradox due to Hurkens is the neatest toxic construction we know.)</p> <h3>Combinator Syntax and Normalization</h3> <p>Anyhow, we have two extra symbols, Pi and Set, so we might perhaps manage a combinatory translation with S, K and two extra symbols: I chose U for the universe and P for the product.</p> <p>Now we can define the untyped combinatory syntax (with free variables):</p> <pre><code>data SKUP = S | K | U | P deriving (Show, Eq) data Unty a = C SKUP | Unty a :. Unty a | V a deriving (Functor, Eq) infixl 4 :. </code></pre> <p>Note that I've included the means to include free variables represented by type <code>a</code> in this syntax. Apart from being a reflex on my part (every syntax worthy of the name is a free monad with <code>return</code> embedding variables and <code>&gt;&gt;=</code> perfoming substitution), it'll be handy to represent intermediate stages in the process of converting terms with binding to their combinatory form.</p> <p>Here's normalization:</p> <pre><code>norm :: Unty a -&gt; Unty a norm (f :. a) = norm f $. a norm c = c ($.) :: Unty a -&gt; Unty a -&gt; Unty a -- requires first arg in normal form C S :. f :. a $. g = f $. g $. (a :. g) -- S f a g = f g (a g) share environment C K :. a $. g = a -- K a g = a drop environment n $. g = n :. norm g -- guarantees output in normal form infixl 4 $. </code></pre> <p>(An exercise for the reader is to define a type for exactly the normal forms and sharpen the types of these operations.)</p> <h3>Representing Type Theory</h3> <p>We can now define a syntax for our type theory.</p> <pre><code>data Tm a = Var a | Lam (Tm a) (Tm (Su a)) -- Lam is the only place where binding happens | Tm a :$ Tm a | Pi (Tm a) (Tm a) -- the second arg of Pi is a function computing a Set | Set deriving (Show, Functor) infixl 4 :$ data Ze magic :: Ze -&gt; a magic x = x `seq` error "Tragic!" data Su a = Ze | Su a deriving (Show, Functor, Eq) </code></pre> <p>I use a de Bruijn index representation in the Bellegarde and Hook manner (as popularised by Bird and Paterson). The type <code>Su a</code> has one more element than <code>a</code>, and we use it as the type of free variables under a binder, with <code>Ze</code> as the newly bound variable and <code>Su x</code> being the shifted representation of the old free variable <code>x</code>.</p> <h3>Translating Terms to Combinators</h3> <p>And with that done, we acquire the usual translation, based on <em>bracket abstraction</em>.</p> <pre><code>tm :: Tm a -&gt; Unty a tm (Var a) = V a tm (Lam _ b) = bra (tm b) tm (f :$ a) = tm f :. tm a tm (Pi a b) = C P :. tm a :. tm b tm Set = C U bra :: Unty (Su a) -&gt; Unty a -- binds a variable, building a function bra (V Ze) = C S :. C K :. C K -- the variable itself yields the identity bra (V (Su x)) = C K :. V x -- free variables become constants bra (C c) = C K :. C c -- combinators become constant bra (f :. a) = C S :. bra f :. bra a -- S is exactly lifted application </code></pre> <h3>Typing the Combinators</h3> <p>The translation shows the way we use the combinators, which gives us quite a clue about what their types should be. <code>U</code> and <code>P</code> are just set constructors, so, writing untranslated types and allowing "Agda notation" for Pi, we should have</p> <pre><code>U : Set P : (A : Set) -&gt; (B : (a : A) -&gt; Set) -&gt; Set </code></pre> <p>The <code>K</code> combinator is used to lift a value of some type <code>A</code> to a constant function over some other type <code>G</code>.</p> <pre><code> G : Set A : Set ------------------------------- K : (a : A) -&gt; (g : G) -&gt; A </code></pre> <p>The <code>S</code> combinator is used to lift applications over a type, upon which all of the parts may depend.</p> <pre><code> G : Set A : (g : G) -&gt; Set B : (g : G) -&gt; (a : A g) -&gt; Set ---------------------------------------------------- S : (f : (g : G) -&gt; (a : A g) -&gt; B g a ) -&gt; (a : (g : G) -&gt; A g ) -&gt; (g : G) -&gt; B g (a g) </code></pre> <p>If you look at the type of <code>S</code>, you'll see that it exactly states the <em>contextualised</em> application rule of the type theory, so that's what makes it suitable to reflect the application construct. That's its job!</p> <p>We then have application only for closed things</p> <pre><code> f : Pi A B a : A -------------- f a : B a </code></pre> <p>But there's a snag. I've written the types of the combinators in ordinary type theory, not combinatory type theory. Fortunately, I have a machine that will make the translation.</p> <h3>A Combinatory Type System</h3> <pre><code>--------- U : U --------------------------------------------------------- P : PU(S(S(KP)(S(S(KP)(SKK))(S(KK)(KU))))(S(KK)(KU))) G : U A : U ----------------------------------------- K : P[A](S(S(KP)(K[G]))(S(KK)(K[A]))) G : U A : P[G](KU) B : P[G](S(S(KP)(S(K[A])(SKK)))(S(KK)(KU))) -------------------------------------------------------------------------------------- S : P(P[G](S(S(KP)(S(K[A])(SKK)))(S(S(KS)(S(S(KS)(S(KK)(K[B])))(S(KK)(SKK)))) (S(S(KS)(KK))(KK)))))(S(S(KP)(S(S(KP)(K[G]))(S(S(KS)(S(KK)(K[A]))) (S(S(KS)(KK))(KK)))))(S(S(KS)(S(S(KS)(S(KK)(KP)))(S(KK)(K[G])))) (S(S(KS)(S(S(KS)(S(KK)(KS)))(S(S(KS)(S(S(KS)(S(KK)(KS))) (S(S(KS)(S(KK)(KK)))(S(KK)(K[B])))))(S(S(KS)(S(S(KS)(S(KK)(KS)))(S(KK)(KK)))) (S(KK)(KK))))))(S(S(KS)(S(S(KS)(S(KK)(KS)))(S(S(KS)(S(KK)(KK))) (S(S(KS)(KK))(KK)))))(S(S(KS)(S(S(KS)(S(KK)(KS)))(S(KK)(KK))))(S(KK)(KK))))))) M : A B : U ----------------- A ={norm} B M : B </code></pre> <p>So there you have it, in all its unreadable glory: a combinatory presentation of <code>Set:Set</code>!</p> <p>There's still a bit of a problem. The syntax of the system gives you no way to guess the <code>G</code>, <code>A</code> and <code>B</code> parameters for <code>S</code> and similarly for <code>K</code>, just from the terms. Correspondingly, we can verify <em>typing derivations</em> algorithmically, but we can't just typecheck combinator terms as we could with the original system. What might work is to require the input to the typechecker to bear type annotations on uses of S and K, effectively recording the derivation. But that's another can of worms...</p> <p><strong>This is a good place to stop, if you've been keen enough to start. The rest is "behind the scenes" stuff.</strong></p> <h3>Generating the Types of the Combinators</h3> <p>I generated those combinatory types using the bracket abstraction translation from the relevant type theory terms. To show how I did it, and make this post not entirely pointless, let me offer my equipment.</p> <p>I can write the types of the combinators, fully abstracted over their parameters, as follows. I make use of my handy <code>pil</code> function, which combines Pi and lambda to avoid repeating the domain type, and rather helpfully allows me to use Haskell's function space to bind variables. Perhaps you can almost read the following!</p> <pre><code>pTy :: Tm a pTy = fmap magic $ pil Set $ \ _A -&gt; pil (pil _A $ \ _ -&gt; Set) $ \ _B -&gt; Set kTy :: Tm a kTy = fmap magic $ pil Set $ \ _G -&gt; pil Set $ \ _A -&gt; pil _A $ \ a -&gt; pil _G $ \ g -&gt; _A sTy :: Tm a sTy = fmap magic $ pil Set $ \ _G -&gt; pil (pil _G $ \ g -&gt; Set) $ \ _A -&gt; pil (pil _G $ \ g -&gt; pil (_A :$ g) $ \ _ -&gt; Set) $ \ _B -&gt; pil (pil _G $ \ g -&gt; pil (_A :$ g) $ \ a -&gt; _B :$ g :$ a) $ \ f -&gt; pil (pil _G $ \ g -&gt; _A :$ g) $ \ a -&gt; pil _G $ \ g -&gt; _B :$ g :$ (a :$ g) </code></pre> <p>With these defined, I extracted the relevant <em>open</em> subterms and ran them through the translation.</p> <h3>A de Bruijn Encoding Toolkit</h3> <p>Here's how to build <code>pil</code>. Firstly, I define a class of <code>Fin</code>ite sets, used for variables. Every such set has a constructor-preserving <code>emb</code>edding into the set above, plus a new <code>top</code> element, and you can tell them apart: the <code>embd</code> function tells you if a value is in the image of <code>emb</code>.</p> <pre><code>class Fin x where top :: Su x emb :: x -&gt; Su x embd :: Su x -&gt; Maybe x </code></pre> <p>We can, of course, instantiate <code>Fin</code> for <code>Ze</code> and <code>Suc</code></p> <pre><code>instance Fin Ze where top = Ze -- Ze is the only, so the highest emb = magic embd _ = Nothing -- there was nothing to embed instance Fin x =&gt; Fin (Su x) where top = Su top -- the highest is one higher emb Ze = Ze -- emb preserves Ze emb (Su x) = Su (emb x) -- and Su embd Ze = Just Ze -- Ze is definitely embedded embd (Su x) = fmap Su (embd x) -- otherwise, wait and see </code></pre> <p>Now I can define less-or-equals, with a <em>weakening</em> operation.</p> <pre><code>class (Fin x, Fin y) =&gt; Le x y where wk :: x -&gt; y </code></pre> <p>The <code>wk</code> function should embed the elements of <code>x</code> as the <em>largest</em> elements of <code>y</code>, so that the extra things in <code>y</code> are smaller, and thus in de Bruijn index terms, bound more locally.</p> <pre><code>instance Fin y =&gt; Le Ze y where wk = magic -- nothing to embed instance Le x y =&gt; Le (Su x) (Su y) where wk x = case embd x of Nothing -&gt; top -- top maps to top Just y -&gt; emb (wk y) -- embedded gets weakened and embedded </code></pre> <p>And once you've got that sorted out, a bit of rank-n skullduggery does the rest.</p> <pre><code>lam :: forall x. Tm x -&gt; ((forall y. Le (Su x) y =&gt; Tm y) -&gt; Tm (Su x)) -&gt; Tm x lam s f = Lam s (f (Var (wk (Ze :: Su x)))) pil :: forall x. Tm x -&gt; ((forall y . Le (Su x) y =&gt; Tm y) -&gt; Tm (Su x)) -&gt; Tm x pil s f = Pi s (lam s f) </code></pre> <p>The higher-order function doesn't just give you a term representing the variable, it gives you an <em>overloaded</em> thing which becomes the correct representation of the variable in any scope where the variable is visible. That is, the fact that I go to the trouble of distinguishing the different scopes <em>by type</em> gives the Haskell typechecker enough information to compute the shifting required for the translation to de Bruijn representation. Why keep a dog and bark yourself?</p>
12,894,824
double and stringstream formatting
<pre><code>double val = 0.1; std::stringstream ss; ss &lt;&lt; val; std::string strVal= ss.str(); </code></pre> <p>In the Visual Studio debugger, <code>val</code> has the value 0.10000000000000001 (because 0.1 can't be represented). When <code>val</code> is converted using stringstream, <code>strVal</code> is equal to <code>"0.1"</code>. However, when using boost::lexical_cast, the resulting <code>strVal</code> is <code>"0.10000000000000001"</code>.</p> <p>Another example is the following:</p> <p><code>double val = 12.12305000012;</code></p> <p>Under visual studio <code>val</code> appears as 12.123050000119999, and using stringstream and default precision (6) it becomes 12.1231. I don't really understand why it is not 12.12305(...).</p> <p>Is there a default precision, or does stringstream have a particular algorithm to convert a double value which can't be exactly represented?</p> <p>Thanks.</p>
12,895,137
4
0
null
2012-10-15 11:37:28.117 UTC
2
2019-04-02 12:49:20.29 UTC
2015-05-04 11:46:24.477 UTC
null
196,312
null
619,570
null
1
17
c++|double
47,871
<p>You can change the floating-point precision of a <code>stringstream</code> as follows:</p> <pre><code>double num = 2.25149; std::stringstream ss(stringstream::in | stringstream::out); ss &lt;&lt; std::setprecision(5) &lt;&lt; num &lt;&lt; endl; ss &lt;&lt; std::setprecision(4) &lt;&lt; num &lt;&lt; endl; </code></pre> <p>Output:</p> <pre><code>2.2515 2.251 </code></pre> <p>Note how the numbers are also rounded when appropriate.</p>
12,673,357
How to get only City, State, Country from lat, long in android
<p>I have the below code to convert lat, long to human readable address. Now iam getting full details including street name. How can i get only city, state, country? I don't want anything more details. Please help me. </p> <pre><code>Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault()); try { List&lt;Address&gt; addresses = geoCoder.getFromLocation(latitude, longitude, 1); String add = ""; if (addresses.size() &gt; 0) { for (int i=0; i&lt;addresses.get(0).getMaxAddressLineIndex();i++) add += addresses.get(0).getAddressLine(i) + "\n"; } showToastMessage(add); } catch (IOException e1) { e1.printStackTrace(); } </code></pre>
12,673,476
6
0
null
2012-10-01 12:33:54.793 UTC
2
2018-08-07 12:16:31.757 UTC
2012-10-01 12:41:52.777 UTC
null
100,957
null
1,670,443
null
1
21
android|google-geocoder|street-address
46,536
<p>The amount of detail in a reverse geocoded location description may vary, for example one might contain the full street address of the closest building, while another might contain only a city name and postal code. This will return the city name and country name</p> <pre><code> if (addresses.size() &gt; 0) { System.out.println(addresses.get(0).getLocality()); System.out.println(addresses.get(0).getCountryName()); } </code></pre> <p>For details you can look into the <a href="http://developer.android.com/reference/android/location/Address.html">Address</a> object</p>
13,091,719
Converting LastLogon to DateTime format
<p>My objective is to get a list of users from my domain with the following info:</p> <p>-Display name -Country -Manager Name -Last login date</p> <p>I am running the following script, and everything looks good except for the LastLogon. It outputs the time into a bunch of random numbers like "129948127853609000". How can I convert this to DateTime format?</p> <pre><code>Search-ADAccount -UsersOnly -SearchBase "OU=International,DC=mycompany,DC=com" -AccountDisabled:$false | Get-ADUser -Properties Name, manager, LastLogon | Select Name, manager, LastLogon | export-csv C:\Australia.csv -NoTypeInformation </code></pre>
13,091,821
6
0
null
2012-10-26 17:37:04.817 UTC
7
2022-03-09 18:32:10.043 UTC
2012-10-26 17:43:37.407 UTC
null
1,211,933
null
1,211,933
null
1
29
powershell|active-directory
269,260
<p><code>DateTime.FromFileTime</code> should do the trick:</p> <pre><code>PS C:\&gt; [datetime]::FromFileTime(129948127853609000) Monday, October 15, 2012 3:13:05 PM </code></pre> <p>Then depending on how you want to format it, check out <a href="http://msdn.microsoft.com/en-us/library/az4se3k1.aspx" rel="noreferrer">standard</a> and <a href="http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx" rel="noreferrer">custom</a> datetime format strings.</p> <pre><code>PS C:\&gt; [datetime]::FromFileTime(129948127853609000).ToString('d MMMM') 15 October PS C:\&gt; [datetime]::FromFileTime(129948127853609000).ToString('g') 10/15/2012 3:13 PM </code></pre> <p>If you want to integrate this into your one-liner, change your <code>select</code> statement to this:</p> <pre><code>... | Select Name, manager, @{N='LastLogon'; E={[DateTime]::FromFileTime($_.LastLogon)}} | ... </code></pre>
13,187,877
Why can't I update to the latest MongoDB with Homebrew?
<p>I have version 2.0.2 of mongo installed on my mac, which I installed using Homebrew. The course I'm taking is using the 'aggregate' function, which is only available in version 2.2 of Mongo. I tried to do </p> <pre><code> brew upgrade mongodb </code></pre> <p>and I get </p> <pre><code>Error: mongodb already upgraded </code></pre> <p>Is there a way to install the latest version of Mongo with Homebrew?</p>
13,191,004
5
1
null
2012-11-02 01:10:16.45 UTC
7
2022-08-19 06:23:05.897 UTC
2015-09-14 11:44:40.023 UTC
null
304,151
null
1,647,484
null
1
35
mongodb|homebrew
26,149
<p>This command should update your homebrew formulae to their latest version:</p> <pre><code>brew update </code></pre> <p>And then:</p> <pre><code>brew upgrade mongodb-community </code></pre> <p>To install the latest version of mongodb.</p>
12,663,639
How to hide databases that I am not allowed to access
<p>When I connect to my <code>Heroku</code> - <code>Postgresql</code> database via <code>pgAdmin3</code>, It lists all the tables (about 2600). Every time I open the pgAdmin3 I have to find my own database.</p> <p>Is there a way to hide databases that I'm <code>not allowed</code> to access ?</p>
13,298,802
5
0
null
2012-09-30 18:00:25.153 UTC
42
2021-11-12 11:28:14.493 UTC
2016-02-10 16:26:06.23 UTC
null
1,845,432
null
1,510,671
null
1
199
heroku|pgadmin
29,411
<p>Had the same issue, as its a shared space on AWS with 1000 other DBs.</p> <p><strong>pgAdmin 3</strong></p> <ol> <li>Make sure you are disconnected from your server.</li> <li>Right click your Server -&gt; properties -&gt; Advanced tab.</li> <li>In 'DB restriction' type in the name of your database(s) <strong>enclosed in <em>single</em> quotes and separated by spaces</strong>. E.g. <code>'dback447'</code></li> </ol> <p><strong>pgAdmin 4</strong></p> <p>Same as above, but on step 3 do not use quotes, just the plain DB name. E.g <code>dback447</code></p> <p><strong>pgAdmin 4 version 6.1</strong></p> <p>Same as above, but press <kbd>Tab</kbd> after entering the name of each database. Commas or spaces take your string as a name of one single database.</p> <p>And you have to press <kbd>Tab</kbd> even if you want to type only one database name, otherwise the <kbd>Save</kbd> button ignores your changes.</p> <p><a href="https://i.stack.imgur.com/IZPdP.png" rel="noreferrer"><img src="https://i.stack.imgur.com/IZPdP.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/VO3B5.png" rel="noreferrer"><img src="https://i.stack.imgur.com/VO3B5.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/DTQg5.png" rel="noreferrer"><img src="https://i.stack.imgur.com/DTQg5.png" alt="enter image description here" /></a></p>
17,078,151
Submit a form using <a> anchor element, without javascript
<p>How to replace the submit button with a link without using javascript ? is there any way to add the submit attribute to a link ? because the form will not be sent by a simple link without "submit".</p> <pre><code>&lt;form:form action="/getPage" &gt; &lt;div class="buttons"&gt; &lt;a class="link" href=""&gt; &lt;img src="icon.png" /&gt; &lt;/a&gt; &lt;/div&gt; &lt;/form:form&gt; </code></pre> <p>I work in an application web so if i use javascript the link will not be mapped by the server .. </p>
17,078,212
4
3
null
2013-06-13 02:11:20.453 UTC
2
2018-08-10 18:31:27.387 UTC
2013-06-13 02:26:38.607 UTC
null
1,166,285
null
2,337,243
null
1
14
html|forms
51,110
<p>Try this:</p> <p><strong>CSS</strong> </p> <pre><code>button { background:none!important; border:none; padding:0!important; /*border is optional*/ border-bottom:1px solid #444; } </code></pre> <p><strong>HTML</strong></p> <pre><code>&lt;button&gt;your button that looks like a link&lt;/button&gt; </code></pre>
16,907,825
How to implement sublime text like fuzzy search?
<p>How can i implement a sublime-like fuzzy search on select2?</p> <p>Example, typing "sta jav sub" would match "Stackoverflow javascript sublime like"</p>
16,907,844
7
0
null
2013-06-04 00:10:05.33 UTC
9
2018-11-26 13:25:20.89 UTC
2013-06-04 00:15:46.167 UTC
null
23,020
null
23,020
null
1
28
javascript|jquery-select2
9,029
<p>select2 allows you to implement your own "matcher" functions (<a href="http://ivaynberg.github.io/select2" rel="noreferrer">as seen on their docs</a>), using that and some regexp you can do something like:</p> <pre><code>$("#element").select2({ matcher: function(term, text, opt) { //We call to uppercase to do a case insensitive match //We replace every group of whitespace characters with a .+ //matching any number of characters return text.toUpperCase().match(term.toUpperCase().replace(/\s+/g, '.+')); } }); </code></pre> <p>A matcher function is invoked against every select2 list element when filtering / searching the list, you could implement any kind of custom search using that.</p>
17,108,122
_.isFunction(a) vs. typeof a === 'function'? javascript
<p>I think it might be only performance case - <a href="http://jsperf.com/comparing-underscore-js-isfunction-with-typeof-function/2">http://jsperf.com/comparing-underscore-js-isfunction-with-typeof-function/2</a></p> <p>And seems that <code>typeof</code> is faster.. so my question is - which is more appropriate to use?</p>
17,108,198
2
1
null
2013-06-14 12:06:17.543 UTC
7
2013-06-14 12:17:48.18 UTC
null
null
null
null
2,117,550
null
1
53
javascript|performance|underscore.js|typeof
61,331
<p>There is no reason not to use <code>typeof</code>.</p> <p>Not only is it faster but the <a href="http://es5.github.io/#x11.4.3">ECMAScript specification</a> ensures that all functions have a type of "function" and that only functions can have a type of "function" :</p> <p><img src="https://i.stack.imgur.com/9AUle.png" alt="enter image description here"></p> <p>This operator was specifically designed to get the type of a value, so why not use it ?</p>
4,293,026
CoreData Edit/Overwrite Object
<p>I am playing around with a new project, a split view iPad app using <strong>Core Data</strong>, and I was wondering, as its fairly clear how to add and remove an item. If I was to say alter this to hold text, then that text be shown in a <code>UITextView</code>, how can I edit or overwrite an object in <strong>CoreData</strong>?</p> <p>So the user types their note in the <code>UITextView</code> and when they leave that it edits and saves the note (object in the table view) they have currently selected.</p> <p>Appreciate any help thanks.</p>
4,293,065
2
0
null
2010-11-27 17:47:50.637 UTC
11
2013-11-22 20:57:21.377 UTC
2013-11-22 20:57:21.377 UTC
null
2,888,113
null
427,292
null
1
17
objective-c|ipad|core-data|uitextview|uisplitviewcontroller
18,350
<p>You simply request the existing object using an <code>NSFetchRequest</code>, change whatever fields need to be updated (a simple myObject.propertyName setter is all that's required), and then perform a <strong>save</strong> action on the data context.</p> <p><strong>EDIT</strong> to add code example. I agree with MCannon, Core Data is definitely worth reading up about.</p> <p>This code assumes you created the project with a template that includes Core Data stuff, such that your app delegate has a managed object context, etc. Note that there is NO error checking here, this is just basic code.</p> <p><strong>Fetching the object</strong> </p> <pre><code>// Retrieve the context if (managedObjectContext == nil) { managedObjectContext = [(YourAppNameAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext]; } // Retrieve the entity from the local store -- much like a table in a database NSEntityDescription *entity = [NSEntityDescription entityForName:@"YourEntityName" inManagedObjectContext:managedObjectContext]; NSFetchRequest *request = [[NSFetchRequest alloc] init]; [request setEntity:entity]; // Set the predicate -- much like a WHERE statement in a SQL database NSPredicate *predicate = [NSPredicate predicateWithFormat:@"YourIdentifyingObjectProperty == %@", yourIdentifyingQualifier]; [request setPredicate:predicate]; // Set the sorting -- mandatory, even if you're fetching a single record/object NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"yourIdentifyingQualifier" ascending:YES]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; [request setSortDescriptors:sortDescriptors]; [sortDescriptors release]; sortDescriptors = nil; [sortDescriptor release]; sortDescriptor = nil; // Request the data -- NOTE, this assumes only one match, that // yourIdentifyingQualifier is unique. It just grabs the first object in the array. YourEntityName *thisYourEntityName = [[managedObjectContext executeFetchRequest:request error:&amp;error] objectAtIndex:0]; [request release]; request = nil; </code></pre> <p><strong>Update the object</strong></p> <pre><code>thisYourEntityName.ExampleNSStringAttributeName = @"The new value"; thisYourEntityName.ExampleNSDateAttributeName = [NSDate date]; </code></pre> <p><strong>Save the change</strong></p> <pre><code>NSError *error; [self.managedObjectContext save:&amp;error]; </code></pre> <p>Now your object/row is updated.</p>
41,272,168
compare text inside 2 div elements using javascript or jquery
<p>I have following 2 div tags</p> <pre><code>&lt;div class="one"&gt; + +++ + &lt;/div&gt; </code></pre> <p>second div tag</p> <pre><code>&lt;div class="two"&gt; + + ++++ + ++ + + + + ++ +++ + +++ ++ + +++ + ++ + + ++ + + + + ++ &lt;/div&gt; </code></pre> <p>Now what I want to find if <code>.one</code> is exist in <code>.two</code>. Is it possible if yes how can we do it in javascript?</p> <p><strong>Update</strong></p> <p>I want to check the <code>+</code> pattern. I mean does </p> <p><code>+ +++ +</code></p> <p>exist in <code>.two</code>? The pattern has to be in that same order in <code>.two</code>.</p> <p>@shub answer does not seem to be working. Here is <a href="https://jsfiddle.net/6L99q3a7/">JSFiddle</a> of that answer.</p>
41,308,741
13
6
null
2016-12-21 21:28:25.22 UTC
9
2017-04-25 10:10:10.263 UTC
2016-12-21 21:49:45.81 UTC
null
1,136,062
null
1,136,062
null
1
38
javascript|jquery|html
2,705
<p><strong>Part 1:</strong></p> <p>To see how the data would match, you may want to try turning this into letters, instead of pluses.</p> <pre><code>&lt;div class="one"&gt; g tuv J &lt;/div&gt; &lt;div class="two"&gt; a b cdef g hi j k l m no pqr s tuv wx y zAB C DE F G HI J K L M NO &lt;/div&gt; </code></pre> <p>You'd have to do something like this:</p> <p>Since: one.innerText = g \n tuv \n J</p> <p>It would need to be turned into a regular expression like: /g|tuv|J/g</p> <p>To see the cross matching, copy &amp; paste the contents of class two into this site &amp; delete the spacing before "a", "m" &amp; "C": <a href="http://regexr.com/3eumc" rel="nofollow noreferrer">http://regexr.com/3eumc</a></p> <p><strong>Part 2</strong></p> <p>The problem is if "tuv" moves around in string 2, it wouldn't be locked with "g" above "u" above "J".</p> <p>To fix that "g" above "u" above "J" problem, we'd have to think of this as a 2-dimensional dataset for a game board. That means turning the string into a matrix (array of arrays), where each letter plus each space gets dropped into an array slot. Like so:</p> <pre><code>var matrix = [ // 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 = columns. Remember to add +10, +20! [a| |b| | | |c|d|e|f| | |g| |h|i| | |j| |k| |l], // row 0 [m| |n|o| |p|q|r| |s| |t|u|v| |w|x| |y| |z|A|B], // row 1 [C| |D|E| |F| |G| |H|I| |J| |K| |L| |M| |N|O] // row 2 ]; </code></pre> <p>Now you can check to see if:</p> <pre><code>if ((matrix[0][13] === 'g') &amp;&amp; (matrix[1][12] === 't') &amp;&amp; (matrix[1][13] === 'u') &amp;&amp; (matrix[1][14] === 'v') &amp;&amp; (matrix[2][13] === 'J')) { /* SUCCESS when all 5 letters appear &amp; "g" is above "u" &amp; "u" is above "J". The entire cross can move left or right, but lines 1, 2 &amp; 3 can't shift independently of the other 3 lines. Otherwise it should fail. */ } else { // FAIL } </code></pre> <p><strong>Part 3...</strong> </p> <p>I've solved this matrix search puzzle. See my jsFiddle at <a href="https://jsfiddle.net/briankueck/pern32vv/" rel="nofollow noreferrer">https://jsfiddle.net/briankueck/pern32vv/</a></p> <p>Here is the core of how the code looks. Turn on the debugging switch at that jsFiddle link to see how it runs. :)</p> <pre><code>function getMatrix(cssSelector, canTrim) { // Built by, Clomp! @briankueck http://www.clomp.com var obj = $(cssSelector); if (obj) { var matrix = obj.text() /* Makes sure that we are selecting 3 lines, not 5 * as the example has a \n after &lt;div ...&gt;\n and before \n&lt;/div&gt; */ if (canTrim) { matrix = matrix.trim(); } // Now split those 3 lines. matrix = matrix.split(/\n/); /* Trims each array in the matrix. Note: matrix[row] is a string, * but we can treat a string as an array of characters. */ if (canTrim) { // Trims each row, if desired. for (var row = 0; row &lt; matrix.length; row++) { matrix[row] = matrix[row].trim(); } } else { // Gets rid of spaces before matrix 1 in this demo. var maxLength = 0; var space = ' '; // You can also use a period here to see how it works. var tempMatrix = []; for (var row = 0; row &lt; matrix.length; row++) { // This cuts the rows down (vertically) from 5 to 3. if (matrix[row].trim().length &gt; 0) { matrix[row] = matrix[row].replace(/\s/g, space); matrix[row] = matrix[row].replace(/\t/g, space); tempMatrix.push(matrix[row]); if (matrix[row].length &gt; maxLength) { maxLength = matrix[row].length; } } } /* This loops those 3 rows (horizontally) &amp; slices the 1st character off * each array if they are all identical &amp; only contain spaces, which we are * tracking with the period character '.' as dots. */ var charactersToStrip = 0; for (var column = 0; column &lt;= maxLength; column++) { for (var row = 0; row &lt; tempMatrix.length; row++) { if (tempMatrix[row][column] !== space) { break; } else if (row === (tempMatrix.length - 1)) { charactersToStrip++; } } } /* Strips characters, without removing the space before "g" * and the space before "J". */ for (var column = 0; column &lt; charactersToStrip; column++) { for (var row = 0; row &lt; tempMatrix.length; row++) { tempMatrix[row] = tempMatrix[row].substring(1); } } matrix = tempMatrix; } } return matrix; } function matrixSearch(matrixOne, matrixTwo) { // Built by, Clomp! @briankueck http://www.clomp.com var space = ' '; // You can also use a period here to see how it works. // This is for " g". First we trim it, as we only want the "g" character. var searchChar = matrixOne[0].trim(); // Next we find the lock position. var firstCharPosition = matrixTwo[0].indexOf(searchChar); var matchingRows = -1; if (firstCharPosition &gt; -1) { // This should be 1 &amp; not 0. var matchingCharInMatrixOne = matrixOne[0].indexOf(searchChar); // Now we can find the starting index of character 0 in each row of matrixTwo: var startIndex = firstCharPosition - matchingCharInMatrixOne; // This simultaneously scans rows 1, 2 &amp; 3 in both matricies. var matchingRows = 0; for (var row = 0; row &lt; matrixOne.length; row++) { /* We now know both the startIndex = 11 &amp; the lock position = 12. * So let's use them for "tuv" and " J". */ var endIndex = startIndex + matrixOne[row].length; var i = -1; for (var column = startIndex; column &lt; endIndex; column++) { i++; if (matrixOne[row][i] !== space) { var matrixOneCharacter = matrixOne[row][i]; var matrixTwoCharacter = matrixTwo[row][column]; if (matrixOneCharacter !== matrixTwoCharacter) { break; } else if (column === (endIndex - 1)) { // Found it! matchingRows++; } } } } } // Now we can find it: var isFoundInMatrixTwo = ((matchingRows &gt; -1) &amp;&amp; (matchingRows === matrixTwo.length)) ? true : false; return isFoundInMatrixTwo; } var cssSelector1 = '.one'; var cssSelector2 = '.two'; var matrixOne = getMatrix(cssSelector1, false); var matrixTwo = getMatrix(cssSelector2, true); var isFound = matrixSearch(matrixOne, matrixTwo); console.log('Is matrix 1 in matrix 2? ', isFound); </code></pre> <p>Enjoy!</p> <p>Btw, Merry Christmas Stack Overflow community from Clomp!</p>
9,790,924
Excel VBA, How to select rows based on data in a column?
<pre><code>Sub SelectAllReleventText() Do While Range(“A1”).Offset(1, 6) &lt;&gt; Empty Rows(ActiveCell.Row).Select ActiveCell.Offset(1, 0).Select Loop End Sub </code></pre> <p>Here is my script, I've been told it doesn't do what it is meant to, which I expected since this was my first attempt. I am coming up with a variable not defined error. I thought I defined the variable, but I guess it wasn't specific enough for Excel VBA. </p> <p>This is what I am attempting to do. </p> <ol> <li>In Workbook 1, On B6 there is an alphanumeric name, I want that row to be selected.</li> <li>Go down one row, if there is text there select that row.</li> <li>Continue till text is no longer prevalent. </li> <li>Copy selected rows.</li> <li>Paste into another workbook (Workbook2), into tab 1, starting on row 2, since row 1 has headers.</li> </ol> <p>Thanks in advance. Just a heads up, I am using the Options Explicit in my VBA because I was told it was the "right way to do thing"...</p>
9,791,133
2
1
null
2012-03-20 16:31:54.073 UTC
null
2016-01-28 16:20:32.77 UTC
2018-07-09 19:34:03.733 UTC
null
-1
null
1,048,319
null
1
5
excel|vba
114,958
<p>Yes using <code>Option Explicit</code> is a good habit. Using <code>.Select</code> however is not :) it reduces the speed of the code. Also fully justify sheet names else the code will always run for the <code>Activesheet</code> which might not be what you actually wanted.</p> <p>Is this what you are trying?</p> <pre><code>Option Explicit Sub Sample() Dim lastRow As Long, i As Long Dim CopyRange As Range '~~&gt; Change Sheet1 to relevant sheet name With Sheets("Sheet1") lastRow = .Range("A" &amp; .Rows.Count).End(xlUp).Row For i = 2 To lastRow If Len(Trim(.Range("A" &amp; i).Value)) &lt;&gt; 0 Then If CopyRange Is Nothing Then Set CopyRange = .Rows(i) Else Set CopyRange = Union(CopyRange, .Rows(i)) End If Else Exit For End If Next If Not CopyRange Is Nothing Then '~~&gt; Change Sheet2 to relevant sheet name CopyRange.Copy Sheets("Sheet2").Rows(1) End If End With End Sub </code></pre> <p><strong>NOTE</strong></p> <p>If if you have data from Row 2 till Row 10 and row 11 is blank and then you have data again from Row 12 then the above code will only copy data from Row 2 till Row 10</p> <p>If you want to copy all rows which have data then use this code.</p> <pre><code>Option Explicit Sub Sample() Dim lastRow As Long, i As Long Dim CopyRange As Range '~~&gt; Change Sheet1 to relevant sheet name With Sheets("Sheet1") lastRow = .Range("A" &amp; .Rows.Count).End(xlUp).Row For i = 2 To lastRow If Len(Trim(.Range("A" &amp; i).Value)) &lt;&gt; 0 Then If CopyRange Is Nothing Then Set CopyRange = .Rows(i) Else Set CopyRange = Union(CopyRange, .Rows(i)) End If End If Next If Not CopyRange Is Nothing Then '~~&gt; Change Sheet2 to relevant sheet name CopyRange.Copy Sheets("Sheet2").Rows(1) End If End With End Sub </code></pre> <p>Hope this is what you wanted?</p> <p>Sid</p>
10,021,892
How to renew/extend facebook access tokens with PHP?
<p>Facebook has removed the offline_access token functionality, now tokens have to be renewed whenever the user visits your website to keep them active.</p> <p>Say someone has already given your website access and you have a token stored for them. What code would you use with Facebook's PHP library to renew that token? </p>
10,060,245
4
17
null
2012-04-05 02:28:15.133 UTC
9
2015-04-22 05:42:28.663 UTC
null
null
null
null
49,153
null
1
12
php|facebook
14,537
<p>You can extend your token the following way:</p> <p>Original scenario</p> <ul> <li>Your app requests permissions from the user</li> <li>You prompt user to log in / grant permissions</li> <li>You get user's token (short-lived one) and exchange via CURL or other means for a 60 day one using grant_type=fb_exchange_token</li> <li>You persist the token</li> </ul> <p>Now you have that token to do what you wish with it for up to 60 days. Up to, because user can change password, de-authorize app, etc and token would become invalid. What you can do to extend the token is EVERY TIME user comes to your page(s), you can check if they are logged in via javascript and if they are, make an ajax call to your server to extend existing token for 60 days from today. You can make as many calls as you want, only the first one is valid. Here's how I do it:</p> <ol> <li><p>On your page somewhere during load event, add something like:</p> <pre><code> FB.getLoginStatus(function (response) { if (response.status === 'connected') { $.ajax({ type: "POST", async: false, url: YOUR_URL, dataType: "text", data: {token : response.authResponse.accessToken } }); } }); //rest of jquery ajax call here </code></pre></li> </ol> <p>That will get a new client-side access token for the user and send it to the server</p> <ol> <li><p>Server can then take that token and exchange it for a 60 day one </p> <pre><code>$token_url = "https://graph.facebook.com/oauth/access_token?client_id=".FACEBOOK_CLIENT_ID."&amp;client_secret=".FACEBOOK_SECRET."&amp;grant_type=fb_exchange_token&amp;fb_exchange_token=".$token; $c = curl_init(); curl_setopt($c, CURLOPT_RETURNTRANSFER, 1); curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($c, CURLOPT_URL, $token_url); $contents = curl_exec($c); $err = curl_getinfo($c,CURLINFO_HTTP_CODE); curl_close($c); $paramsfb = null; parse_str($contents, $paramsfb); </code></pre></li> </ol> <p>Reference:</p> <p><a href="https://developers.facebook.com/roadmap/offline-access-removal/" rel="nofollow">https://developers.facebook.com/roadmap/offline-access-removal/</a> </p> <p>That would only extend the token if the user comes back to your site within 60 days. If not, you will need to prompt for permissions again.</p>
10,192,663
Why can't I use record selectors with an existentially quantified type?
<p>When using Existential types, we have to use a pattern-matching syntax for extracting the <code>forall</code>ed value. We can't use the ordinary record selectors as functions. GHC reports an error and suggest using pattern-matching with this definition of <code>yALL</code>:</p> <pre><code>{-# LANGUAGE ExistentialQuantification #-} data ALL = forall a. Show a =&gt; ALL { theA :: a } -- data ok xALL :: ALL -&gt; String xALL (ALL a) = show a -- pattern matching ok -- ABOVE: heaven -- BELOW: hell yALL :: ALL -&gt; String yALL all = show $ theA all -- record selector failed </code></pre> <hr> <pre><code>forall.hs:11:19: Cannot use record selector `theA' as a function due to escaped type variables Probable fix: use pattern-matching syntax instead In the second argument of `($)', namely `theA all' In the expression: show $ theA all In an equation for `yALL': yALL all = show $ theA all </code></pre> <p>Some of my data take more than 5 elements. It's hard to maintain the code if I use pattern-matching:</p> <pre><code>func1 (BigData _ _ _ _ elemx _ _) = func2 elemx </code></pre> <p>Is there a good method to make code like that maintainable or to wrap it up so that I can use some kind of selectors?</p>
10,192,884
2
4
null
2012-04-17 13:56:44.643 UTC
6
2014-11-30 06:14:00.623 UTC
2014-11-30 06:14:00.623 UTC
null
1,186,208
null
683,727
null
1
31
haskell|record|existential-type
3,048
<p>You can use record syntax in pattern matching,</p> <pre><code>func1 BigData{ someField = elemx } = func2 elemx </code></pre> <p>works and is much less typing for huge types.</p>
10,202,456
How to create a JPA query with LEFT OUTER JOIN
<p>I am starting to learn JPA, and have implemented an example with JPA query, based on the following native SQL that I tested in SQL Server:</p> <pre><code>SELECT f.StudentID, f.Name, f.Age, f.Class1, f.Class2 FROM Student f LEFT OUTER JOIN ClassTbl s ON s.ClassID = f.Class1 OR s.ClassID = f.Class2 WHERE s.ClassName = 'abc' </code></pre> <p>From the above SQL I have constructed the following JPQL query:</p> <pre><code>SELECT f FROM Student f LEFT JOIN f.Class1 s; </code></pre> <p>As you can see, I still lack the condition <code>OR s.ClassID = f.Class2</code> from my original query. My question is, how can I put it into my JPQL?</p>
10,202,914
4
1
null
2012-04-18 03:40:58.67 UTC
4
2021-08-16 20:07:00.23 UTC
2017-03-21 12:18:48.66 UTC
null
4,823,977
null
2,351,597
null
1
33
java|jpa|jpql
144,999
<p>Write this;</p> <pre><code> SELECT f from Student f LEFT JOIN f.classTbls s WHERE s.ClassName = 'abc' </code></pre> <p>Because your Student entity has One To Many relationship with ClassTbl entity.</p>
11,703,124
Plugin not found in plugin repository - How fix an issue when my company Nexus is down?
<p>I am trying to buld <code>Hadoop</code> locally and when I do</p> <pre><code>$ mvn -U clean install -Pdist -Dtar -Ptest-patch </code></pre> <p>as mentioned - <a href="http://wiki.apache.org/hadoop/HowToSetupYourDevelopmentEnvironment" rel="noreferrer">http://wiki.apache.org/hadoop/HowToSetupYourDevelopmentEnvironment</a></p> <pre><code>[ERROR] Error resolving version for plugin 'org.apache.maven.plugins:maven-javadoc-plugin' from the repositories [local (/Users/me/.m2/repository), nexus (http://beefy.myorg.local:8081/nexus/content/groups/public)]: Plugin not found in any plugin repository -&gt; [Help 1] </code></pre> <p>As I see logs on console, I see</p> <pre><code>[INFO] Apache Hadoop Distribution [INFO] Apache Hadoop Client [INFO] Apache Hadoop Mini-Cluster [INFO] [INFO] ------------------------------------------------------------------------ [INFO] Building Apache Hadoop Main 3.0.0-SNAPSHOT [INFO] ------------------------------------------------------------------------ Downloading: http://beefy.myorg.local:8081/nexus/content/groups/public/org/apache/maven/plugins/maven-javadoc-plugin/maven-metadata.xml [WARNING] Could not transfer metadata org.apache.maven.plugins:maven-javadoc-plugin/maven-metadata.xml from/to nexus (http://beefy.myorg.local:8081/nexus/content/groups/public): Error transferring file: Operation timed out </code></pre> <p>Since <code>nexus</code> in my company is down, is there any way I can resolve this and let hadoop build?</p> <p><strong>UPDATE</strong></p> <p>After adding the <code>repository</code> in my project pom, it still fails </p> <pre><code>[ERROR] Failed to execute goal on project hadoop: Could not resolve dependencies for project groupId:hadoop:jar:master-SNAPSHOT: Failed to collect dependencies for [org.apache.hadoop:hadoop-core:jar:0.20.2 (compile)]: Failed to read artifact descriptor for org.apache.hadoop:hadoop-core:jar:0.20.2: Could not transfer artifact org.apache.hadoop:hadoop-core:pom:0.20.2 from/to nexus (http://beefy.myorg.local:8081/nexus/content/groups/public): Error transferring file: Operation timed out -&gt; [Help 1] </code></pre> <p>and this is <code>pom.xml</code></p> <pre><code> &lt;repositories&gt; &lt;repository&gt; &lt;id&gt;mvnrepository&lt;/id&gt; &lt;url&gt;http://mvnrepository.com/artifact/&lt;/url&gt; &lt;/repository&gt; &lt;/repositories&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.hadoop&lt;/groupId&gt; &lt;artifactId&gt;hadoop-core&lt;/artifactId&gt; &lt;version&gt;0.20.2&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; </code></pre>
11,703,397
2
0
null
2012-07-28 17:19:04.273 UTC
1
2016-12-21 08:21:45.44 UTC
2012-07-29 06:42:54.523 UTC
null
379,235
null
379,235
null
1
7
java|maven|hadoop|nexus
58,422
<p>If you have access to internet, simply declare a new maven repository (in you pom, or in you settings.xml) : </p> <pre class="lang-xml prettyprint-override"><code> &lt;repositories&gt; &lt;repository&gt; &lt;id&gt;your-internal-repo&lt;/id&gt; &lt;url&gt;http://beefy.myorg.local:8081/nexus/content/&lt;/url&gt; &lt;/repository&gt; &lt;repository&gt; &lt;id&gt;mvnrepository&lt;/id&gt; &lt;url&gt;http://mvnrepository.com/artifact/&lt;/url&gt; &lt;/repository&gt; &lt;/repositories&gt; </code></pre> <p>This configuration will first try to download from you repository, then fail. And maven will try all declared repositories, until it works .... or not :)</p> <p>Indeed, your internal repository is a proxy, that caches the distant one (mvnrepository).</p>
11,538,875
How to download all subtitles from Opensubtitles.org in a specific language?
<p>Excuse me if this post is not related to this forum, but I couldn't find any other place to ask my question. It would be appreciated if you introduce me a suitable place for this post. By the way, I am trying to download all the subtitles from Opensubtitles.org in a specific language (say English) and find their translations in another language (say Arabic). I tried wget, but I couldn't download anything useful from this site. (I need .srt, .zip and .txt files) Can everyone help me?</p> <p>Bests.</p>
11,539,639
2
0
null
2012-07-18 10:01:49.213 UTC
9
2012-11-29 12:51:38.793 UTC
null
null
null
null
1,265,960
null
1
16
linux|wget
31,736
<p>The download link is something like:</p> <pre><code>http://dl.opensubtitles.org/en/download/sub/4617044 </code></pre> <p>Where 4617044 is the ID of the subtitle. You can use this URL with wget to download it, but it won't have the correct filename.</p> <p>Alternatively, you can use the <a href="http://trac.opensubtitles.org/projects/opensubtitles/wiki/XMLRPC" rel="noreferrer">XML-RPC api</a> to search and download subtitles.</p>
11,609,532
Breaking the nested loop
<p>I'm having problem with nested loop. I have multiple number of posts, and each post has multiple number of images. </p> <p>I want to get total of 5 images from all posts. So I am using nested loop to get the images, and want to break the loop when the number reaches to 5. The following code will return the images, but does not seem to break the loop.</p> <p> <pre><code>foreach($query-&gt;posts as $post){ if ($images = get_children(array( 'post_parent' =&gt; $post-&gt;ID, 'post_type' =&gt; 'attachment', 'post_mime_type' =&gt; 'image')) ){ $i = 0; foreach( $images as $image ) { .. //break the loop? if (++$i == 5) break; } } } </code></pre>
11,609,551
2
2
null
2012-07-23 09:12:32.963 UTC
7
2019-12-27 15:40:57.373 UTC
2019-12-27 15:40:57.373 UTC
null
293,099
null
1,355,300
null
1
80
php|loops|nested-loops
56,076
<p>Unlike other languages such as C/C++, in PHP you can use the optional param of break like this:</p> <pre><code>break 2; </code></pre> <p>In this case if you have two loops such that:</p> <pre><code>while(...) { while(...) { // do // something break 2; // skip both } } </code></pre> <p><code>break 2</code> will skip both while loops.</p> <p>Doc: <a href="http://php.net/manual/en/control-structures.break.php" rel="noreferrer">http://php.net/manual/en/control-structures.break.php</a></p> <p>This makes jumping over nested loops more readable than for example using <code>goto</code> of other languages</p>
3,251,600
How do I get first name and last name as whole name in a MYSQL query?
<p>I want to be able to do something like this</p> <pre><code>SELECT `first_name` + " " + `last_name` as `whole_name` FROM `users` </code></pre> <p>So basically I get one column back <code>whole_name</code> which is <code>first_name</code> and <code>last_name</code> concatenated together with a <code></code> (space).</p> <p>How do I do that in SQL, or more specifically, MySQL ?</p>
3,251,610
4
0
null
2010-07-15 00:24:45.463 UTC
11
2020-03-06 13:57:05.637 UTC
2013-06-01 12:25:26.39 UTC
null
31,671
null
31,671
null
1
24
sql|mysql
134,178
<p><a href="http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_concat-ws" rel="noreferrer">http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_concat-ws</a></p> <pre><code>SELECT CONCAT_WS(" ", `first_name`, `last_name`) AS `whole_name` FROM `users` </code></pre>
4,018,851
final and static in Java
<p>I have read this sentence in a book but I didn't understand it:</p> <blockquote> <p>A field that is both static and final has only one piece of storage that cannot be changed.</p> </blockquote> <p>Can anyone explain it for me?</p>
4,018,987
4
1
null
2010-10-25 21:04:54.897 UTC
8
2021-01-01 21:56:42.293 UTC
2021-01-01 21:56:42.293 UTC
null
213,269
null
367,018
null
1
25
java
42,746
<p>The source of your confusion may be that the word "static" in english and it's meaning in Java are only loosely related.</p> <p>A variable defined in a class Cat in the "normal" way can be referred to as an instance variable.</p> <pre><code>class Cat { int weight; } </code></pre> <p>Each time you create a new object of type Cat, you create a new copy of the variable 'weight'. If you create 10 objects of type Cat, each one has it's own copy of the weight variable.</p> <p>A 'static' variable can be thought of as a class level variable, as opposed to an instance variable. A static variable has only one copy and belongs to the class Cat itself, rather than there being one copy for <em>each</em> object of type Cat.</p> <pre><code>class Cat { static String speciesName; int weight; } </code></pre> <p>Here, no matter how many objects of type Cat we create, there is only one copy of speciesName.</p> <p>If the static variable is also 'final,' than this one copy of the variable is the only piece of storage that cannot be changed. If the variable 'weight' were final in the above example, there would be 10 pieces of storage which could not be changed -- one for each object of type Cat that we had created.</p>
3,316,431
How do I set Layout and Text size to DP inside program?
<p>Basically I have this inside XML, but I have to recreate it inside a code. How do I do it?</p> <pre><code>&lt;EditText android:layout_width="140dp" android:layout_height="20dp" android:background="@drawable/input_bg01" android:textSize="10dp" android:gravity="center" android:text="111-222-333 FOOO" /&gt; </code></pre> <p>I can use this to set text size, but what about the layout_width and height?</p> <pre><code>edTxt.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 10); </code></pre> <p>Is there a way to tell the code to use DP unit instead of pixel? Or a conversion function to convert DP into pixel?</p>
5,032,267
4
2
null
2010-07-23 08:13:56.933 UTC
10
2021-03-28 01:43:08.227 UTC
null
null
null
null
271,736
null
1
40
java|android|layout
53,180
<p>Solved <a href="https://stackoverflow.com/questions/5012840/android-specifying-pixel-units-like-sp-px-dp-without-using-xml/5012893#5012893">here</a>.</p> <p>Extract:</p> <pre><code>DisplayMetrics metrics = getContext().getResources().getDisplayMetrics(); float dp = 20f; float fpixels = metrics.density * dp; int pixels = (int) (fpixels + 0.5f); </code></pre>
3,490,216
HTML/CSS - Adding an Icon to a button
<p>I making some css buttons and I want to add an icon before the text, "Button Text". </p> <p>But I dont know how I should do this...</p> <p>HTML <code>&lt;div class="btn btn_red"&gt;&lt;a href="#"&gt;Crimson&lt;/a&gt;&lt;span&gt;&lt;/span&gt;&lt;/div&gt;</code></p> <p>CSS</p> <pre><code>body { margin: 0; padding: 10px; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 14px; } /* Glassy Buttons */ .btn { float: left; clear: both; background: url(imgs/button_left.png) no-repeat; padding: 0 0 0 10px; margin: 5px 0; } .btn a{ float: left; height: 40px; background: url(imgs/button_middle.png) repeat-x left top; line-height: 40px; padding: 0 10px; color: #fff; font-size: 1em; text-decoration: none; } .btn span { background: url(imgs/button_right.png) no-repeat; float: left; width: 10px; height: 40px; } .btn_gray {background-color: #808080;} .btn_green { background-color: #ADFF2F;} .btn_blue {background-color: #0000CD;} .btn_red {background-color: #DC143C;} </code></pre>
3,490,236
5
0
null
2010-08-16 02:18:21.957 UTC
2
2022-07-19 15:02:43.383 UTC
null
null
null
null
377,419
null
1
19
html|css
205,116
<p>You could add a span before the link with a specific class like so:</p> <pre><code>&lt;div class="btn btn_red"&gt;&lt;span class="icon"&gt;&lt;/span&gt;&lt;a href="#"&gt;Crimson&lt;/a&gt;&lt;span&gt;&lt;/span&gt;&lt;/div&gt; </code></pre> <p>And then give that a specific width and a background image just like you are doing with the button itself.</p> <pre><code>.btn span.icon { background: url(imgs/icon.png) no-repeat; float: left; width: 10px; height: 40px; } </code></pre> <p>I am no CSS guru but off the top of my head I think that should work.</p>
3,734,829
DateTime field and Html.TextBoxFor() helper. How to use it correctly?
<p>I have a DateTime field in my Model. If I try to use this field in a strong typed partial view this way</p> <pre><code>&lt;%= Html.TextBoxFor(model =&gt; model.DataUdienza.ToString("dd/MM/yyyy"), new { style = "width: 120px" }) %&gt; </code></pre> <p>I will get the following compilation error at runtime</p> <pre><code>System.InvalidOperationException : Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions. </code></pre> <p>Anyway if I use it removing the formatting, <strong>ToString("dd/MM/yyyy")</strong>, everything works but the field is formatted using the time part which I dont need at all.</p> <p>Where I am doing wrong? Which is the correct way to handle this?</p> <p>thanks for helping!</p> <p><strong>EDIT</strong></p> <p>This is the property declaration in the model class</p> <pre><code>[Required] [DisplayName("Data Udienza")] [DataType(DataType.Date)] [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")] public DateTime DataUdienza { get; set; } </code></pre>
3,735,801
5
0
null
2010-09-17 11:19:34.353 UTC
7
2013-09-10 19:35:38.737 UTC
2010-09-17 11:32:13.81 UTC
null
431,537
null
431,537
null
1
21
asp.net-mvc|html-helper
58,360
<p>Create an editor template called DateTime.ascx</p> <pre><code>&lt;%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl&lt;System.DateTime?&gt;" %&gt; &lt;%=Html.TextBox("", (Model.HasValue ? Model.Value.ToString("MM/dd/yyyy") : string.Empty), ViewData) %&gt; </code></pre> <p>Put it in your Views/Shared/EditorTemplates folder. Now when you call:</p> <pre><code>&lt;%= Html.EditorFor(model =&gt; model.DataUdienza) %&gt; </code></pre> <p>Your DateTime will be formatted without the time.</p> <p>This will happen with all DateTimes called this way, though...</p> <p>Custom html attributes can be used in this way:</p> <pre><code>&lt;%= Html.EditorFor(model =&gt; model.DataUdienza, new {customAttr = "custom", @class = "class"}) %&gt; </code></pre> <p>It passes through to the EditorTemplate as ViewData.</p>
3,424,860
What characters are allowed in the HTML Name attribute inside input tag?
<p>I have a PHP script that will generate <code>&lt;input&gt;</code>s dynamically, so I was wondering if I needed to filter any characters in the <code>name</code> attribute.</p> <p><s>I know that the name has to start with a letter, but</s> I don't know any other rules. I figure square brackets must be allowed, since PHP uses these to create arrays from form data. How about parentheses? Spaces?</p>
3,424,964
5
0
null
2010-08-06 14:43:19.613 UTC
9
2017-03-19 20:05:39.63 UTC
2015-02-01 16:28:47.123 UTC
null
3,204,551
null
119,853
null
1
93
html|forms|web-standards|html-input
51,276
<p>The only real restriction on what characters can appear in form control names is when a form is submitted with GET</p> <p>"The "get" method restricts form data set values to ASCII characters." <a href="http://www.w3.org/TR/html401/interact/forms.html#h-17.13.1" rel="noreferrer">reference</a></p> <p>There's a good thread on it <a href="http://bytes.com/topic/html-css/answers/95687-use-within-id-name-attribute-input-tag" rel="noreferrer">here</a>.</p>
3,426,843
What is the default initialization of an array in Java?
<p>So I'm declaring and initializing an int array:</p> <pre><code>static final int UN = 0; int[] arr = new int[size]; for (int i = 0; i &lt; size; i++) { arr[i] = UN; } </code></pre> <p>Say I do this instead... </p> <pre><code>int[] arr = new int[5]; System.out.println(arr[0]); </code></pre> <p>... <code>0</code> will print to standard out. Also, if I do this:</p> <pre><code>static final int UN = 0; int[] arr = new int[5]; System.out.println(arr[0]==UN); </code></pre> <p>... <code>true</code> will print to standard out. So how is Java initializing my array by default? Is it safe to assume that the default initialization is setting the array indices to <code>0</code> which would mean I don't have to loop through the array and initialize it? </p> <p>Thanks.</p>
3,426,854
8
2
null
2010-08-06 18:58:42.593 UTC
57
2021-11-08 09:24:47.55 UTC
null
null
null
null
196,921
null
1
167
java|arrays|initialization
331,104
<p>Everything in a Java program not explicitly set to something by the programmer, is initialized to a zero value. </p> <ul> <li>For references (anything that holds an object) that is <code>null</code>.</li> <li>For int/short/byte/long that is a <code>0</code>.</li> <li>For float/double that is a <code>0.0</code></li> <li>For booleans that is a <code>false</code>.</li> <li>For char that is the null character <code>'\u0000'</code> (whose decimal equivalent is 0).</li> </ul> <p>When you create an array of something, all entries are also zeroed. So <strong>your array contains five zeros right after it is created by <code>new</code></strong>.</p> <p>Note (based on comments): The Java Virtual Machine is not required to zero out the underlying memory when allocating local variables (this allows efficient stack operations if needed) so to avoid random values the Java Language Specification requires local variables to be initialized.</p>
3,442,333
PHP REGEX: Get domain from URL
<p><strong>What I want</strong></p> <hr> <p>I want to get from a <code>URL</code> the <code>domain</code> part so from <code>http://example.com/</code> -> <code>example.com</code></p> <p><strong>Examples:</strong></p> <hr> <pre><code>+----------------------------------------------+-----------------------+ | input | output | +----------------------------------------------+-----------------------+ | http://www.stackoverflow.com/questions/ask | www.stackoverflow.com | | http://validator.w3.org/check | validator.w3.org | | http://www.google.com/?q=hello | www.google.com | | http://google.de/?q=hello | google.de | +----------------------------------------------+-----------------------+ </code></pre> <p>I found some related questions in <code>stackoverflow</code> but none of them was exactly what I was looking for. </p> <p>Thanks for any help!</p>
3,442,365
9
1
null
2010-08-09 17:00:23.483 UTC
9
2019-07-27 05:36:51.227 UTC
null
null
null
null
380,562
null
1
24
php|regex|url|dns
32,640
<p>There's no need to use a regex for this. PHP has an inbuilt function to do just this. Use <a href="http://php.net/manual/en/function.parse-url.php" rel="noreferrer"><code>parse_url()</code></a>:</p> <pre><code>$domain = parse_url($url, PHP_URL_HOST); </code></pre>
3,698,200
window.onload vs $(document).ready()
<p>What are the differences between JavaScript's <a href="https://developer.mozilla.org/en/docs/Web/API/GlobalEventHandlers/onload" rel="noreferrer"><code>window.onload</code></a> and jQuery's <a href="https://learn.jquery.com/using-jquery-core/document-ready/" rel="noreferrer"><code>$(document).ready()</code></a> method?</p>
3,698,214
17
4
null
2010-09-13 06:24:52.57 UTC
397
2022-08-30 15:30:17.03 UTC
2020-06-26 08:52:47.05 UTC
null
4,194,079
null
197,878
null
1
1,352
javascript|jquery|dom-events|unobtrusive-javascript
1,091,221
<p>The <code>ready</code> event occurs after the HTML document has been loaded, while the <code>onload</code> event occurs later, when all content (e.g. images) also has been loaded.</p> <p>The <code>onload</code> event is a standard event in the DOM, while the <code>ready</code> event is specific to jQuery. The purpose of the <code>ready</code> event is that it should occur as early as possible after the document has loaded, so that code that adds functionality to the elements in the page doesn't have to wait for all content to load.</p>
3,437,897
How do I get a class instance of generic type T?
<p>I have a generics class, <code>Foo&lt;T&gt;</code>. In a method of <code>Foo</code>, I want to get the class instance of type <code>T</code>, but I just can't call <code>T.class</code>.</p> <p>What is the preferred way to get around it using <code>T.class</code>?</p>
3,437,930
23
6
null
2010-08-09 06:58:45.707 UTC
253
2022-08-21 08:06:40.143 UTC
2020-03-18 12:47:51.213 UTC
null
1,898,563
null
448,452
null
1
837
java|generics
894,807
<p>The short answer is, that there is no way to find out the runtime type of generic type parameters in Java. I suggest reading the chapter about type erasure in the <a href="http://download.oracle.com/javase/tutorial/java/generics/erasure.html" rel="noreferrer">Java Tutorial</a> for more details.</p> <p>A popular solution to this is to pass the <code>Class</code> of the type parameter into the constructor of the generic type, e.g.</p> <pre><code>class Foo&lt;T&gt; { final Class&lt;T&gt; typeParameterClass; public Foo(Class&lt;T&gt; typeParameterClass) { this.typeParameterClass = typeParameterClass; } public void bar() { // you can access the typeParameterClass here and do whatever you like } } </code></pre>
8,186,133
Faster ways to calculate frequencies and cast from long to wide
<p>I am trying to obtain counts of each combination of levels of two variables, "week" and "id". I'd like the result to have "id" as rows, and "week" as columns, and the counts as the values.</p> <p>Example of what I've tried so far (tried a bunch of other things, including adding a dummy variable = 1 and then <code>fun.aggregate = sum</code> over that): </p> <pre><code>library(plyr) ddply(data, .(id), dcast, id ~ week, value_var = "id", fun.aggregate = length, fill = 0, .parallel = TRUE) </code></pre> <p>However, I must be doing something wrong because this function is not finishing. Is there a better way to do this?</p> <p>Input:</p> <pre><code>id week 1 1 1 2 1 3 1 1 2 3 </code></pre> <p>Output:</p> <pre><code> 1 2 3 1 2 1 1 2 0 0 1 </code></pre>
8,186,229
4
0
null
2011-11-18 17:07:18.103 UTC
8
2022-02-02 02:28:41.53 UTC
2018-10-06 10:11:54.16 UTC
null
1,851,712
null
592,419
null
1
17
r|aggregate|plyr|reshape2
4,560
<p>You don't need <code>ddply</code> for this. The <code>dcast</code> from <code>reshape2</code> is sufficient:</p> <pre><code>dat &lt;- data.frame( id = c(rep(1, 4), 2), week = c(1:3, 1, 3) ) library(reshape2) dcast(dat, id~week, fun.aggregate=length) id 1 2 3 1 1 2 1 1 2 2 0 0 1 </code></pre> <hr> <p><strong>Edit :</strong> For a base R solution (other than <code>table</code> - as posted by Joshua Uhlrich), try <code>xtabs</code>:</p> <pre><code>xtabs(~id+week, data=dat) week id 1 2 3 1 2 1 1 2 0 0 1 </code></pre>
7,802,014
Remove Commas with Jquery
<p>I am in need of some code that removes commas from a string. I currently have a variety of numbers in the number_format() for PHP. I use Jquery to post certain things to a update page and I need the commas removed from a class.</p> <p>for instance here is some code.</p> <pre><code>&lt;span class="money"&gt;1,234,567&lt;/span&gt; </code></pre> <p>I want the value of the code I post to be 1234567 instead of 1,234,567. I would like to use Jquery if that's possible.</p> <p>Thanks</p>
7,802,018
6
0
null
2011-10-18 03:16:31.74 UTC
3
2018-11-27 17:55:55.833 UTC
null
null
null
null
917,117
null
1
18
php|jquery
42,076
<p><a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace" rel="noreferrer">replace</a></p> <pre><code>var noCommas = $('.money').text().replace(/,/g, ''), asANumber = +noCommas; </code></pre>
7,961,721
How do I install a custom font on an HTML site
<p>I am not using flash or php - and I have been asked to add a custom font to a simple HTML layout. "KG June Bug"</p> <p>I have it downloaded locally - is there a simple CSS trick to accomplish this?</p>
7,961,750
6
1
null
2011-11-01 01:53:38.007 UTC
57
2022-04-11 22:04:00.067 UTC
2022-04-11 22:04:00.067 UTC
null
1,946,501
null
411,472
null
1
184
html|css|fonts|webfonts|custom-font
501,362
<p>Yes, you can use the CSS feature named @font-face. It has only been officially approved in CSS3, but been proposed and implemented in CSS2 and has been supported in IE for quite a long time.</p> <p>You declare it in the CSS like this:</p> <pre><code> @font-face { font-family: Delicious; src: url('Delicious-Roman.otf'); } @font-face { font-family: Delicious; font-weight: bold; src: url('Delicious-Bold.otf');} </code></pre> <p>Then, you can just reference it like the other standard fonts:</p> <pre><code> h3 { font-family: Delicious, sans-serif; } </code></pre> <p>So, in this case,</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;style&gt; @font-face { font-family: JuneBug; src: url('JUNEBUG.TTF'); } h1 { font-family: JuneBug } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Hey, June&lt;/h1&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>And you just need to put the JUNEBUG.TFF in the same location as the html file.</p> <p>I downloaded the font from the <a href="http://www.dafont.com/" rel="noreferrer">dafont.com</a> website:</p> <p><a href="http://www.dafont.com/junebug.font" rel="noreferrer">http://www.dafont.com/junebug.font</a></p>
8,158,516
Invalid conversion from "const char*" to "char" error
<p>I wanted to post this because I was not really sure what issue I was having with a simple assignment statement. I am doing a homework assignment that asks me to write structs and functions in a simple program to draw out shapes of ASCII characters. Right now I am just trying to test the functions I have written, and I am trying to assign a value to the symbol element of a Circle struct just to test out the DrawShape function I wrote. When I try to assign it a * char, I get an error message saying "error: invalid conversion from 'const char*' to 'char'". I will put the whole code in, though it is very long and unfinished. Any help with this would be appreciated. The problem I am getting is right in the beginning of the main at "circle1.char = '*' "</p> <pre><code>#include &lt;iostream&gt; #include &lt;math.h&gt; #include &lt;cstdlib&gt; using namespace std; const int NUMBER_OF_ROWS = 26; const int NUMBER_OF_COLUMNS = 81; char drawSpace[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]; struct Point{ int x; int y; }; struct Circle{ Point center; int radius; char symbol; bool buffer[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]; }; bool setCircleRadius(Circle &amp;b, int r); bool setCircleCenter(Circle &amp;b, int x, int y); bool moveCircle(Circle &amp;b, int x, int y); void drawCircle (Circle b); void lineChars(Line a); void circleChars(Circle b); void drawShapes(); int main() { Circle circle1; circle1.radius = 5; circle1.symbol = "*"; circle1.center.x = 40; circle1.center.y = 10; drawCircle(circle1); return 0; } </code></pre>
8,158,537
7
6
null
2011-11-16 20:53:06.437 UTC
null
2014-12-29 19:27:34.263 UTC
2011-11-16 20:57:16.3 UTC
null
427,309
null
895,387
null
1
18
c++
83,628
<p>You should be using single quotes for characters. Double quotes means you're using a (potentially single-character) string literal, which is represented as a <code>const char *</code> (pointer to constant character).</p> <p>Correct syntax: <code>circle1.symbol = '*';</code></p>
8,287,949
Android How to draw a smooth line following your finger
<p><a href="http://marakana.com/tutorials/android/2d-graphics-example.html">http://marakana.com/tutorials/android/2d-graphics-example.html</a></p> <p>I am using this example below. But when I move my fingers too fast across the screen the line turns to individual dots.</p> <p>I am not sure whether I can speed up the drawing. Or I should connect the two last points with a straight line. The second of these two solutions seems like a good option, except when moving your finger very fast you will have long sections of a straight line then sharp curves.</p> <p>If there are any other solutions it would be great to hear them.</p> <p>Thanks for any help in advance.</p>
8,289,516
11
4
null
2011-11-27 18:31:30.057 UTC
78
2021-06-22 02:41:00.67 UTC
2011-11-27 19:49:14.863 UTC
null
211,160
null
614,460
null
1
72
java|android|touch|interpolation|curve-fitting
94,816
<p>An easy solution, as you mentioned, is to simply connect the points with a straight line. Here's the code to do so:</p> <pre><code>public void onDraw(Canvas canvas) { Path path = new Path(); boolean first = true; for(Point point : points){ if(first){ first = false; path.moveTo(point.x, point.y); } else{ path.lineTo(point.x, point.y); } } canvas.drawPath(path, paint); } </code></pre> <p>make sure you change your paint from fill to stroke:</p> <pre><code>paint = new Paint(Paint.ANTI_ALIAS_FLAG); paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(2); paint.setColor(Color.WHITE); </code></pre> <p>Another option is to connect the points with iterpolation using the quadTo method:</p> <pre><code>public void onDraw(Canvas canvas) { Path path = new Path(); boolean first = true; for(int i = 0; i &lt; points.size(); i += 2){ Point point = points.get(i); if(first){ first = false; path.moveTo(point.x, point.y); } else if(i &lt; points.size() - 1){ Point next = points.get(i + 1); path.quadTo(point.x, point.y, next.x, next.y); } else{ path.lineTo(point.x, point.y); } } canvas.drawPath(path, paint); } </code></pre> <p>This still results in some sharp edges.</p> <p>If you're really ambitious, you can start to calculate the cubic splines as follows:</p> <pre><code>public void onDraw(Canvas canvas) { Path path = new Path(); if(points.size() &gt; 1){ for(int i = points.size() - 2; i &lt; points.size(); i++){ if(i &gt;= 0){ Point point = points.get(i); if(i == 0){ Point next = points.get(i + 1); point.dx = ((next.x - point.x) / 3); point.dy = ((next.y - point.y) / 3); } else if(i == points.size() - 1){ Point prev = points.get(i - 1); point.dx = ((point.x - prev.x) / 3); point.dy = ((point.y - prev.y) / 3); } else{ Point next = points.get(i + 1); Point prev = points.get(i - 1); point.dx = ((next.x - prev.x) / 3); point.dy = ((next.y - prev.y) / 3); } } } } boolean first = true; for(int i = 0; i &lt; points.size(); i++){ Point point = points.get(i); if(first){ first = false; path.moveTo(point.x, point.y); } else{ Point prev = points.get(i - 1); path.cubicTo(prev.x + prev.dx, prev.y + prev.dy, point.x - point.dx, point.y - point.dy, point.x, point.y); } } canvas.drawPath(path, paint); } </code></pre> <p>Also, I found that you needed to change the following to avoid duplicate motion events:</p> <pre><code>public boolean onTouch(View view, MotionEvent event) { if(event.getAction() != MotionEvent.ACTION_UP){ Point point = new Point(); point.x = event.getX(); point.y = event.getY(); points.add(point); invalidate(); Log.d(TAG, "point: " + point); return true; } return super.onTouchEvent(event); } </code></pre> <p>and add the dx &amp; dy values to the Point class:</p> <pre><code>class Point { float x, y; float dx, dy; @Override public String toString() { return x + ", " + y; } } </code></pre> <p>This produces smooth lines, but sometimes has to connect the dots using a loop. Also, for long drawing sessions, this becomes computationally intensive to calculate.</p> <p>Hope that helps... fun stuff to play around with.</p> <p><strong>Edit</strong></p> <p>I threw together a quick project demonstrating these different techniques, including Square's suggessted signature implementation. Enjoy: <a href="https://github.com/johncarl81/androiddraw" rel="noreferrer">https://github.com/johncarl81/androiddraw</a></p>
8,074,368
CodeIgniter PHP Model Access "Unable to locate the model you have specified"
<p>I have been trying to load some models for this website I am building. However, for an unknown reason, it will bring the following error :</p> <pre><code>An Error Was Encountered Unable to locate the model you have specified: logon_model </code></pre> <p>Now , I have done my research. The problem would be that IC processes file names in lowercase. However, both my file and the file calling is in lower case, as shown here :</p> <pre><code>echo "VALIDATING"; // Validation passed. Off we go to account info verification from AA's database. God help us all. $this-&gt;load-&gt;model('logon_model'); echo "FOUND MODEL"; $res = $this-&gt;logon_model-&gt;verify_user($this-&gt;input-&gt;post('username'),$this-&gt;input-&gt;post('password')); echo $this-&gt;input-&gt;post('username'); echo $this-&gt;input-&gt;post('password'); </code></pre> <p>The execution does <strong>not</strong> reach "FOUND MODEL", thus stops on the model loading. I have tried to use:</p> <pre><code> $this-&gt;load-&gt;model(site_url('logon_model')); </code></pre> <p>With no results. Need to mention the model file is correctly placed in the right model folder ?</p> <p>How can I fix this ?</p> <p>EDIT : Header for the model file :</p> <pre><code>class Logon_model extends CI_Model { .... </code></pre>
8,077,427
16
3
null
2011-11-10 02:38:46.42 UTC
13
2020-01-14 08:07:36.68 UTC
2019-08-16 12:14:22.157 UTC
null
315,550
null
1,038,763
null
1
42
php|model|codeigniter-2
175,011
<p>When creating models, you need to place the file in <code>application/models/</code> and name the file in all lowercase - like <code>logon_model.php</code></p> <p>The <code>logon_model.php</code> should contain the following:</p> <pre><code>&lt;?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Logon_model extends CI_Model { public function __construct() { parent::__construct(); } ... </code></pre> <p>Now, what you can do, to test if your application model is reachable, is to try opening it in the browser - like so:<br> <a href="http://example.org/application/models/logon_model.php">http://example.org/application/models/logon_model.php</a></p> <p>If you see the text <strong>No direct script access allowed</strong> it means you hit the right file (if you are in doubt, try writing something else in the exit() in the first line).</p> <p>Secondly, for loading the model in your controllers, you should be able to do like this:</p> <pre><code>public function index() { $this-&gt;load-&gt;model('logon_model'); ... } </code></pre> <p>If everything above checks out as expected I would begin looking at file permissions and/or possibly symlinks if you are using any.</p>
4,696,041
Using the "With Clause" SQL Server 2008
<p>Can someone show me a sample SQL server script that I can look at that uses the <strong>"With Clause"</strong>? </p> <p>I am trying to use this clause to iterate through 200 databases that contain the same table that I am trying to run a query on. I am trying to avoid using a cursor because the query time takes too long as well as using a while a loop. </p> <p>Can someone advise me as to what I can do. </p> <p>Thank you.</p>
4,707,985
3
2
null
2011-01-14 21:16:33.203 UTC
6
2011-01-16 21:09:22.737 UTC
null
null
null
null
2,012,590
null
1
24
sql-server-2008|sql-server-2008-r2
133,852
<p>Just a poke, but here's another way to write FizzBuzz :) 100 rows is enough to show the WITH statement, I reckon.</p> <pre><code>;WITH t100 AS ( SELECT n=number FROM master..spt_values WHERE type='P' and number between 1 and 100 ) SELECT ISNULL(NULLIF( CASE WHEN n % 3 = 0 THEN 'Fizz' Else '' END + CASE WHEN n % 5 = 0 THEN 'Buzz' Else '' END, ''), RIGHT(n,3)) FROM t100 </code></pre> <p>But the real power behind WITH (known as Common Table Expression <a href="http://msdn.microsoft.com/en-us/library/ms190766.aspx" rel="noreferrer" title="CTE">http://msdn.microsoft.com/en-us/library/ms190766.aspx</a> "CTE") in SQL Server 2005 and above is the Recursion, as below where the table is built up through iterations adding to the virtual-table each time.</p> <pre><code>;WITH t100 AS ( SELECT n=1 union all SELECT n+1 FROM t100 WHERE n &lt; 100 ) SELECT ISNULL(NULLIF( CASE WHEN n % 3 = 0 THEN 'Fizz' Else '' END + CASE WHEN n % 5 = 0 THEN 'Buzz' Else '' END, ''), RIGHT(n,3)) FROM t100 </code></pre> <p>To run a similar query in all database, you can use the undocumented <strong>sp_msforeachdb</strong>. It has been mentioned in another answer, but it is sp_msforeachdb, not sp_foreachdb.</p> <p>Be careful when using it though, as some things are not what you expect. Consider this example</p> <pre><code>exec sp_msforeachdb 'select count(*) from sys.objects' </code></pre> <p>Instead of the counts of objects within each DB, you will get the SAME count reported, begin that of the current DB. To get around this, always "use" the database first. Note the square brackets to qualify multi-word database names.</p> <pre><code>exec sp_msforeachdb 'use [?]; select count(*) from sys.objects' </code></pre> <p>For your specific query about populating a tally table, you can use something like the below. Not sure about the DATE column, so this tally table has only the DBNAME and IMG_COUNT columns, but hope it helps you.</p> <pre><code>create table #tbl (dbname sysname, img_count int); exec sp_msforeachdb ' use [?]; if object_id(''tbldoc'') is not null insert #tbl select ''?'', count(*) from tbldoc' select * from #tbl </code></pre>
4,141,324
Function caller in linux kernel
<p>Is there a way to get function caller in linux kernel? I know <strong>__<em>func</em>__</strong> returns the function name which is executing. I am looking for the function which called "<strong>__<em>func</em>__</strong>"</p>
4,145,666
4
1
null
2010-11-10 04:50:20.09 UTC
21
2015-09-30 10:27:25.627 UTC
null
null
null
null
73,216
null
1
20
linux-kernel|linux-device-driver|embedded-linux|kernel|kernel-mode
17,767
<p>You can get the caller with <code>__builtin_return_address(0)</code>.</p> <p>The caller's caller is <code>__builtin_return_address(1)</code> and so on.</p> <p>It's a GCC extension, documented in the gcc manual: <a href="http://gcc.gnu.org/onlinedocs/gcc/Return-Address.html">http://gcc.gnu.org/onlinedocs/gcc/Return-Address.html</a></p> <p><strong>Edit:</strong> I should probably point out, that gets you the address of the caller. If you want the function name you can print it with <code>%pS</code>, eg:</p> <pre><code>printk("Caller is %pS\n", __builtin_return_address(0)); </code></pre> <p>If you don't want to print it, you can use <code>kallsyms_lookup()</code> etc.</p>
4,050,798
GitHub: Is it possible to collaborate with someone on a private gist?
<p>I have a private gist. If I send the URL to a friend he can view it, but cannot edit it, unless he forks it.</p> <p>Is there a way to edit it directly without forking it?</p>
4,051,606
4
1
null
2010-10-29 09:56:59.31 UTC
8
2020-01-16 07:08:45.08 UTC
null
null
null
null
184,367
null
1
48
git|github
19,004
<p>2010: I am not sure it is possible.<br> To make a gist public (which is not what you want, but illustrates the lack of management features around gist), the <a href="http://groups.google.com/group/github/browse_thread/thread/199f8312fa7f8036" rel="nofollow noreferrer">only solution was to re-post it</a>.</p> <p>There doesn't seem to be a GUI for adding public ssh key for collaborators, like there is for a GitHub project.</p> <hr> <p>Since my original answer in 2010, the ability to <a href="https://help.github.com/en/github/writing-on-github/forking-and-cloning-gists#forking-gists" rel="nofollow noreferrer">fork a gist</a> (as mentioned in <a href="https://stackoverflow.com/users/7012/avi-flax">Avi Flax</a>'s <a href="https://stackoverflow.com/a/24316203/6309">answer</a>) was added (around 2014-2015). </p> <blockquote> <p>Each gist indicates which forks have activity, making it easy to find interesting changes from coworkers or complete strangers.</p> </blockquote> <p><a href="https://i.stack.imgur.com/gUgll.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gUgll.png" alt="Gist forks -- https://help.github.com/assets/images/help/gist/gist_forks.png"></a></p> <p>See for instance "<a href="http://giovanni.curlybrackets.it/2015/04/06/a-basic-collaboration-workflow-on-gist.html" rel="nofollow noreferrer">A basic collaboration workflow on Gist</a>" (Apr. 2015) from <a href="http://giovanni.curlybrackets.it/about.html" rel="nofollow noreferrer">Giovanni Cappellotto</a> (<a href="https://github.com/potomak" rel="nofollow noreferrer"><code>potomak</code></a> on GitHub).</p> <p>There is <a href="https://stackoverflow.com/a/8767309/6309">no direct pull request supported though</a> (still valid in 2020).</p>
4,113,307
Pythonic way to select list elements with different probability
<pre><code>import random pos = ["A", "B", "C"] x = random.choice["A", "B", "C"] </code></pre> <p>This code gives me either "A", "B" or "C" with equal probability. Is there a nice way to express it when you want "A" with 30%, "B" with 40% and "C" with 30% probability?</p>
4,113,516
6
3
null
2010-11-06 13:39:46.597 UTC
20
2022-04-07 13:58:16.373 UTC
null
null
null
null
25,282
null
1
45
python
57,938
<p>Weights define a probability distribution function (pdf). Random numbers from any such pdf can be generated by <a href="http://en.wikipedia.org/wiki/Pseudorandom_number_generator#Non-uniform_generators" rel="noreferrer">applying its associated inverse cumulative distribution function</a> to uniform random numbers between 0 and 1.</p> <p>See also this <a href="https://stackoverflow.com/questions/977354/generating-non-uniform-random-numbers/977508#977508">SO explanation</a>, or, as explained by <a href="http://en.wikipedia.org/wiki/Cumulative%5Fdistribution%5Ffunction#Inverse" rel="noreferrer">Wikipedia</a>:</p> <blockquote> <p>If Y has a U[0,1] distribution then F⁻¹(Y) is distributed as F. This is used in random number generation using the inverse transform sampling-method.</p> </blockquote> <pre><code>import random import bisect import collections def cdf(weights): total = sum(weights) result = [] cumsum = 0 for w in weights: cumsum += w result.append(cumsum / total) return result def choice(population, weights): assert len(population) == len(weights) cdf_vals = cdf(weights) x = random.random() idx = bisect.bisect(cdf_vals, x) return population[idx] weights=[0.3, 0.4, 0.3] population = 'ABC' counts = collections.defaultdict(int) for i in range(10000): counts[choice(population, weights)] += 1 print(counts) # % test.py # defaultdict(&lt;type 'int'&gt;, {'A': 3066, 'C': 2964, 'B': 3970}) </code></pre> <p>The <code>choice</code> function above uses <code>bisect.bisect</code>, so selection of a weighted random variable is done in <code>O(log n)</code> where <code>n</code> is the length of <code>weights</code>. </p> <hr> <p>Note that as of version 1.7.0, NumPy has a Cythonized <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.choice.html" rel="noreferrer">np.random.choice function</a>. For example, this generates 1000 samples from the population <code>[0,1,2,3]</code> with weights <code>[0.1, 0.2, 0.3, 0.4]</code>:</p> <pre><code>import numpy as np np.random.choice(4, 1000, p=[0.1, 0.2, 0.3, 0.4]) </code></pre> <p><code>np.random.choice</code> also has a <code>replace</code> parameter for sampling with or without replacement.</p> <hr> <p>A theoretically better algorithm is the <a href="http://en.wikipedia.org/wiki/Alias_method" rel="noreferrer">Alias Method</a>. It builds a table which requires <code>O(n)</code> time, but after that, samples can be drawn in <code>O(1)</code> time. So, if you need to draw many samples, in theory the Alias Method may be faster. There is a Python implementation of the Walker Alias Method <a href="http://code.activestate.com/recipes/576564-walkers-alias-method-for-random-objects-with-diffe/" rel="noreferrer">here</a>, and a <a href="https://gist.github.com/ntamas/1109133" rel="noreferrer">numpy version here</a>.</p>
4,081,100
C: finding the number of elements in an array[]
<p>In C: How do you find the number of elements in an array of structs, after sending it to a function?</p> <pre><code>int main(void) { myStruct array[] = { struct1, struct2, struct3, struct4, struct5, struct6 }; printf("%d\n", sizeof(array)); printf("%d\n", sizeof(array[0])); f(array); } void f(myStruct* array) { printf("%d\n", sizeof(array)); printf("%d\n", sizeof(array[0])); } </code></pre> <p>For some reason the printf in main shows different results than the printf in f. My need is to know how many elements are in the array.</p>
4,081,132
12
1
null
2010-11-02 18:50:31.267 UTC
3
2021-06-28 06:50:52.407 UTC
null
null
null
null
483,647
null
1
15
c|arrays|pointers
49,014
<p>You can't.</p> <p>You have to pass the size to the function, eg:</p> <pre><code>void f(myStruct* array, size_t siz); </code></pre> <p>Also notice that in <code>f</code> array is a pointer, while in <code>main</code> it is an array. Arrays and pointers are different things.</p>
4,585,929
How to use 'cp' command to exclude a specific directory?
<p>I want to copy all files in a directory except some files in a specific sub-directory. I have noticed that <code>cp</code> command didn't have the <code>--exclude</code> option. So, how can I achieve this?</p>
14,789,400
20
4
null
2011-01-03 15:53:52.997 UTC
196
2022-05-04 17:23:38.183 UTC
2022-01-13 00:00:51.253 UTC
null
8,172,439
null
554,241
null
1
612
linux|bash|terminal|command|cp
603,249
<p><code>rsync</code> is fast and easy:</p> <pre><code>rsync -av --progress sourcefolder /destinationfolder --exclude thefoldertoexclude </code></pre> <p>You can use <code>--exclude</code> multiples times.</p> <pre><code>rsync -av --progress sourcefolder /destinationfolder --exclude thefoldertoexclude --exclude anotherfoldertoexclude </code></pre> <p><strong>Note that the dir <code>thefoldertoexclude</code> after <code>--exclude</code> option is relative to the <code>sourcefolder</code>, i.e., <code>sourcefolder/thefoldertoexclude</code>.</strong></p> <p>Also you can add <code>-n</code> for dry run to see what will be copied before performing real operation, and if everything is ok, remove <code>-n</code> from command line.</p>
14,801,955
PHP file_get_contents returning false
<p>Maybe I've been sat here too long staring at this but WHY would <code>file_get_contents</code> return <code>false</code> here? I've cut and paste the URL and it works fine?</p> <pre><code>$url = &quot;http://jobs.github.com/positions.json?search=&quot; . $as_any . &quot;&amp;location=&quot; . $location; // URL contains http://jobs.github.com/positions.json?search=Project Manager&amp;location=London var_dump($url); $json = file_get_contents($url); var_dump($json); $results = json_decode($json, TRUE); var_dump($results); exit; </code></pre> <p><strong>EDIT:</strong></p> <p>I have checked for <code>allow_url_fopen</code> and its definitely on.</p>
14,802,259
5
2
null
2013-02-10 19:56:07.413 UTC
2
2021-05-07 12:09:46.47 UTC
2020-11-29 10:50:20.1 UTC
null
6,089,612
null
1,175,948
null
1
25
php|json
54,179
<p>Try this:</p> <pre><code>$query = http_build_query(array('search'=&gt;$as_any, 'location'=&gt;$location)); $url = "http://jobs.github.com/positions.json?" . $query; </code></pre> <p>The problem is that you weren't URL-encoding the search term, which contains a space. The request was returning a 400 error from the server, which you'd have noticed if you had error reporting enabled.</p>
14,689,237
What is a "Manager" in django?
<p>I have read the definition in the official Django <a href="https://docs.djangoproject.com/en/dev/topics/db/managers/" rel="noreferrer">documentation</a>, and I am still confused by what a <code>Manager</code> does.</p> <p>The documentation says that they allow you to operate on database tables/models, but I still don't understand this.</p> <p>Can someone explain managers and their role to me? An answer with an example would be preferable.</p>
14,689,377
3
1
null
2013-02-04 14:49:42.343 UTC
11
2021-11-29 21:52:59.623 UTC
2020-07-25 22:32:05.49 UTC
null
3,705,840
null
1,555,306
null
1
28
python|django
13,075
<p>A manager is usually something hidden away from django programmers that django uses to interface between <code>model</code> code and the database backend. </p> <p>When you query the django ORM, you do so through calls to </p> <pre><code>from my_app.models import MyModel mms = MyModel.objects.all() </code></pre> <p>In this case, the <code>objects</code> part of the function is what is returned by the manager. If you wanted MyModel to only ever get <code>blue</code> <code>MyModel</code> instances (the database might contain <code>red</code> models too) then you could create a manager and hack your model thus</p> <pre><code>class BlueManager(models.Manager): def get_query_set(self): return super(BlueManager, self).get_query_set().filter(colour='Blue') class MyModel(models.Model): colour = models.CharField(max_length=64) blue_objects = BlueManager() </code></pre> <p>and calling</p> <pre><code>MyModel.blue_objects.all() </code></pre> <p>would only return objects with <code>colour</code> as <code>blue</code>. Note, this is a very poor way to filter models!</p> <p>One would usually need to modify a <code>Manager</code> interface if they were going to modify the <code>QuerySet</code>s that a manager would usually return or if you needed to add "table" level queries (rather than regular django "row" level). The <a href="https://docs.djangoproject.com/en/dev/topics/db/managers/" rel="noreferrer">documentation</a> for managers is quite complete and contains several examples.</p>
14,786,179
How to convert a 1 channel image into a 3 channel with opencv2?
<p>I'm really stumped on this one. I have an image that was <em>[BGR2GRAY]'d</em> earlier in my code, and now I need to add colored circles and such to it. Of course this can't be done in a 1 channel matrix, and I can't seem to turn the damned thing back into 3.</p> <p><code>numpy.dstack()</code> crashes everything</p> <p>GRAY2BGR does not exist in opencv2</p> <p><code>cv.merge(src1, src2, src3, dst)</code> has been turned into <code>cv2.merge(mv)</code> where mv = &quot;a vector of matrices&quot;, whatever that means.</p> <p>Any ideas?</p> <p><a href="https://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=2&amp;ved=0CDcQFjAB&amp;url=http%3A%2F%2Ffossies.org%2Funix%2Fmisc%2FOpenCV-2.4.3.tar.gz%3Aa%2FOpenCV-2.4.3%2Fdoc%2Fopencv2refman.pdf&amp;ei=awUWUfnbJ4Ly0wGmuoC4Cw&amp;usg=AFQjCNHZZKb8aioAVevF3gpQQeuRT7SxyQhttps://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=2&amp;ved=0CDcQFjAB&amp;url=http%3A%2F%2Ffossies.org%2Funix%2Fmisc%2FOpenCV-2.4.3.tar.gz%3Aa%2FOpenCV-2.4.3%2Fdoc%2Fopencv2refman.pdf&amp;ei=awUWUfnbJ4Ly0wGmuoC4Cw&amp;usg=AFQjCNHZZKb8aioAVevF3gpQQeuRT7SxyQ" rel="noreferrer">Opencv2.4.3 refmanual</a></p>
14,786,995
6
0
null
2013-02-09 08:10:18.807 UTC
4
2022-09-12 18:26:38.527 UTC
2021-05-21 22:30:27.97 UTC
null
15,527,965
null
945,762
null
1
30
python|arrays|opencv
50,313
<p>Here's a way of doing that in Python:</p> <pre><code>img = cv2.imread("D:\\img.jpg") gray = cv2.cvtColor(img, cv.CV_BGR2GRAY) img2 = np.zeros_like(img) img2[:,:,0] = gray img2[:,:,1] = gray img2[:,:,2] = gray cv2.circle(img2, (10,10), 5, (255,255,0)) cv2.imshow("colour again", img2) cv2.waitKey() </code></pre> <p>Here's the complete code for OpenCV3:</p> <pre><code>import cv2 import numpy as np img = cv2.imread('10524.jpg') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img2 = np.zeros_like(img) img2[:,:,0] = gray img2[:,:,1] = gray img2[:,:,2] = gray cv2.imwrite('10524.jpg', img2) </code></pre>
14,390,945
suppress Scrapy Item printed in logs after pipeline
<p>I have a scrapy project where the item that ultimately enters my pipeline is relatively large and stores lots of metadata and content. Everything is working properly in my spider and pipelines. The logs, however, are printing out the entire scrapy Item as it leaves the pipeline (I believe):</p> <pre><code>2013-01-17 18:42:17-0600 [tutorial] DEBUG: processing Pipeline pipeline module 2013-01-17 18:42:17-0600 [tutorial] DEBUG: Scraped from &lt;200 http://www.example.com&gt; {'attr1': 'value1', 'attr2': 'value2', 'attr3': 'value3', ... snip ... 'attrN': 'valueN'} 2013-01-17 18:42:18-0600 [tutorial] INFO: Closing spider (finished) </code></pre> <p>I would rather not have all this data puked into log files if I can avoid it. Any suggestions about how to suppress this output?</p>
16,303,725
9
0
null
2013-01-18 01:06:38.487 UTC
9
2022-06-07 13:23:06.64 UTC
null
null
null
null
564,709
null
1
30
python|scrapy
11,444
<p>Another approach is to override the <code>__repr__</code> method of the <code>Item</code> subclasses to selectively choose which attributes (if any) to print at the end of the pipeline:</p> <pre><code>from scrapy.item import Item, Field class MyItem(Item): attr1 = Field() attr2 = Field() # ... attrN = Field() def __repr__(self): """only print out attr1 after exiting the Pipeline""" return repr({"attr1": self.attr1}) </code></pre> <p>This way, you can keep the log level at <code>DEBUG</code> and show only the attributes that you want to see coming out of the pipeline (to check <code>attr1</code>, for example).</p>
14,890,402
Instruments Allocations track alloc and dealloc of objects of user defined classes
<p>Is it possible to track the allocation and deallocation of my Objective-C objects? For instance if I have a class Book, I want to track all the allocations and deallocations of the objects of Book type. I can track all the default SKD classes, such as UIViewController, UIWindow, UIView, NSDictionary and all that, but I want to track also the objects that are created from my defined classes.</p>
14,891,837
1
0
null
2013-02-15 08:01:38.68 UTC
56
2017-10-09 18:16:59.483 UTC
2013-04-01 15:36:54.783 UTC
null
644,348
null
1,225,334
null
1
61
ios|objective-c|xcode|instruments
20,810
<p>You can use the Allocations instrument to track the lifecycle of your objects. If you use the “Allocations” template, it is configured to record <code>malloc</code> and <code>free</code> events. You may want to configure it to also record <code>retain</code>, <code>release</code>, and <code>autorelease</code> events by turning on the “Record reference counts” checkbox in the Allocations instrument settings:</p> <p><img src="https://i.stack.imgur.com/SotDR.png" alt="record reference counts checkbox"></p> <p>(You cannot toggle this while Instruments is recording, which it starts by default as soon as you choose your template.)</p> <blockquote> <p><strong>Update for Xcode 9:</strong> Apple has made it more difficult to find these settings. Now you need to select the Allocations instrument, then from the menu bar choose File > Recording Options.</p> </blockquote> <p>After your run, you can find your objects using the Allocations > Statistics > Object Summary view, which is the default setting for the Detail pane (the bottom half of the window):</p> <p><img src="https://i.stack.imgur.com/08ued.png" alt="Object Summary setting for Detail pane"></p> <p>If you want to see objects that had been deallocated before you stopped the run, you need to change the Allocation Lifespan setting from “Created &amp; Still Living” (the default) to “All Objects Created”:</p> <p><img src="https://i.stack.imgur.com/4SVf2.png" alt="Allocation Lifespan setting"></p> <p>To find objects of a specific class, start by typing the class name into the Search field at the right end of the window toolbar. Then find the class name in the Category column of the list view, mouse over it, and click the arrow that appears next to it. For example, my app has a class named <code>Tile</code>, so I search for that and then click the arrow next to <code>Tile</code> in the list view:</p> <p><img src="https://i.stack.imgur.com/GtLnh.gif" alt="Searching"></p> <p>Now the list view shows every instance of <code>Tile</code>. (Note that you have to enter the actual class of the object, not a superclass. Entering <code>NSObject</code> will only find objects that were created by <code>[NSObject alloc]</code>, not objects that were created by <code>[Tile alloc]</code>.) I can see the history for any particular instance by clicking the arrow next to that instance's address:</p> <p><img src="https://i.stack.imgur.com/53Lou.gif" alt="Getting detail"></p> <p>In the detail view for an object, I can see the <code>malloc</code> and <code>free</code> events and, since I turned on “Record reference counts”, I can also see the <code>retain</code>, <code>release</code>, and <code>autorelease</code> messages and their effect on the object's retain count. If I want to see the call stack for any of those events, I can open the extended detail panel on the right side of the window:</p> <p><img src="https://i.stack.imgur.com/KKrT1.gif" alt="extended detail of call stack"></p>
14,847,457
How do I find the length (or dimensions, size) of a numpy matrix in python?
<p>For a numpy matrix in python</p> <pre><code>from numpy import matrix A = matrix([[1,2],[3,4]]) </code></pre> <p>How can I find the length of a row (or column) of this matrix? Equivalently, how can I know the number of rows or columns?</p> <p>So far, the only solution I've found is:</p> <pre><code>len(A) len(A[:,1]) len(A[1,:]) </code></pre> <p>Which returns 2, 2, and 1, respectively. From this I've gathered that <code>len()</code> will return the number of rows, so I can always us the transpose, <code>len(A.T)</code>, for the number of columns. However, this feels unsatisfying and arbitrary, as when reading the line <code>len(A)</code>, it isn't immediately obvious that this should return the number of rows. It actually works differently than <code>len([1,2])</code> would for a 2D python array, as this would return 2.</p> <p>So, is there a more intuitive way to find the size of a matrix, or is this the best I have?</p>
14,847,459
2
2
null
2013-02-13 06:07:24.577 UTC
28
2014-02-27 00:39:23.473 UTC
2014-02-04 01:45:08.147 UTC
null
1,748,679
null
1,748,679
null
1
163
python|matrix|numpy
609,602
<p><code>shape</code> is a property of both numpy ndarray's and matrices.</p> <pre><code>A.shape </code></pre> <p>will return a tuple (m, n), where m is the number of rows, and n is the number of columns.</p> <p>In fact, the numpy <code>matrix</code> object is built on top of the <code>ndarray</code> object, one of numpy's two fundamental objects (along with a universal function object), so it inherits from <code>ndarray</code></p>