Database Collation in the stored procedure

Question: I have a dump that contains the procedure for creating a stored procedure:
DELIMITER ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`sys`@`%` PROCEDURE `test`(_Test bigint )
BEGIN
    select * from test;
END ;;
DELIMITER ;

But, when I perform:
SHOW PROCEDURE STATUS WHERE Name LIKE '%test%'\G;

I get:
*************************** 1. row ***************************
                  Db: TEST
                Name: test
                Type: PROCEDURE
             Definer: root@%
            Modified: 2018-02-22 23:25:27
             Created: 2018-02-22 23:25:27
       Security_type: DEFINER
             Comment:
character_set_client: utf8
collation_connection: utf8_general_ci
  Database Collation: latin1_swedish_ci

Why is Database Collation meaninglatin1_swedish_ci?
Comment: The error occurs when you run the stored procedure or when restore the backup?
Answer: For Emoji, you need utf8mb4, not utf8 nor latin1.
I think the Database Collation is not the problem.
Answer: In your table test (and all other tables) must change the character set:
alter table test character set utf8mb4;

Also the fields that contains text:
alter table test change varchar_column varchar_column varchar(XX)
                                        character set utf8mb4;


Showing that a certain random variable has variance $1$

Question: I am calculating this example at the moment. Are my calculations right?
The random variable $Y$ has a mean of 15 and a variance of 9. $Z =
1/3 (Y − 15)$. Show that $Z$ has variance $1$.
$Z = \frac13  (Y − 15)$
$, \newcommand{\stdev}{\mathrm{stdev}}\stdev(Y)=3$
$$\stdev(Z)=\frac13 (Y − 15) = \frac13 (Y)$$
$$\stdev(Y)=3$$
$$\stdev(Z)=\frac13 Y = \frac13  3 = 1$$
$$\mathrm{var}(Z) = 1^2 = 1$$
Is my argumentation right?
Answer: You're correct, though I'm not exactly sure why you converted variances to standard deviations and then back, since you can derive your answer from two properties of variance, namely
$$\newcommand{\Var}{\mathrm{Var}} \Var(X-c) = \Var(X)$$
$$ \Var(cX) = c^2 \cdot \Var(X)$$
where $X$ is a random variable and $c$ is a constant.
The first property tells us that $\Var(Y-15) = \Var(Y) = 9$. Using the second, we find that
$$
\begin{aligned}
\Var\bigg(\frac{1}{3}Y\bigg) &=  \bigg(\frac{1}{3}\bigg)^2 \cdot \Var(Y) \\
& = \frac{1}{9}\Var(Y) \\
& = \frac{1}{9}\cdot9 \\
& = 1
\end{aligned}
$$
Combining the two is pretty trivial!
There's a nice intuition behind both of these properties if you think about variance as "spread" or "scatter". Shifting a distribution left or right (i.e., adding or subtracting a constant) has no effect on how spread apart it is. Scaling a distribution with multiplication or division, however, stretches or squishes it (respectively), which changes the spread of the distribution and thus its variance.


Equivalent sets proof

Question: Let $A$ be a set. Show that $\cal P(A)$ - the power set of $A$ - is equivalent (same cardinal) to ${\{0, 1\}}^A$ - the set of all functions from $A$ to $\{0, 1\}$. Suppose $A$ was $\mathbb{N}$; would this hold? How about if $A$ was $\mathbb{N}^\mathbb{N}$ (the set of sequences with values in $\mathbb{N}$)?
My friend gave me the following proof:
It suffices to construct a bijective function.
Suppose that $f: A \rightarrow \{0, 1\}$, and let $A_f$ be the set of elements such that $a\in  A_f \iff f(a)=1$. Define the map $h(f) =A_f$ then we proceed to show injectivity and surjectivity:
Injectivity:
Suppose that for functions $f, g$, we have $f\ne g$. Then there is an $x\in A$ so $f(x)=1$ and $g(x)=0$ or vice versa. Then $A_f\ne A_g$. By the contrapositive argument, $h$ is injective.
Surjectivity:
Let $X\in{\cal P}(A)$ and then define a function $f$ as follows:
$$f(x)=\cases{1, if x\in B\cr 0, if x \notin B }$$
Then $X = h(f)$ and $h$ is surjective.
We have a bijection $h:{\{0, 1\}}^A \rightarrow {\cal P}(A)$ so, we may conclude that the two sets are equivalent.
Is this proof correct? Is there a more formal or more detailed way to express it? In addition, does this proof carry forward to $\mathbb{N}$ and $\mathbb{N}^\mathbb{N}$ defined in the problem above? Any assistance much appreciated.
Comment: I look at my comment .... and I see Symbol Soup.  But if you *get* the concepts they really *are* simple. And the alternative to Symbol Soup is literary "the man who shot the man who got shot by the man who shot him used a gun that shot the man who got shot by the man who shot the man who got shot" block that referrer linguistic quagmire.  And that can be worse.
Comment: This isn't quite how I would write it (for example I would be clearer about what $h$ was a function from and to, which your context makes clear but might not be clear to a random reader of the argument), and I might include more narrative just being explicit about what it means for things to be one-to-one and onto. But the core ideas are clear and correct and that is definitely exactly how I would approach the problem. It isn't immediately clear to me why the specific identity of $A$ would matter.
Comment: The proof holds for $any$ set $A$.
Comment: @leslietownes Would the proof above require any further steps to be recognized as formal or is what is above sufficient?
Comment: Why don't you think it is formal?  Seems formal to me.
Comment: @fleablood The injectivity and surjectivity don't seem to be "enough"...
Comment: Why in blood's name not?  That's the *very* definition of to sets having the same cardinality.  That means that is an injective/surjective function between them.  What "more" could it possibly mean.  And that *very* formall finds the bijection.
Comment: @fleablood No I understand that part. Perhaps I haven't had enough experience with such but his proof of the injectivity and surjectivity seems lacking in explanation. In particular, how can one conclude surjectivity by just defining a function?
Comment: If you want to prove $f:M \to N$ is surjective, all you have to do is show that for *any* $n \in N$ you can find/define/create an element $m\in M$ so that $f(m) = N$.  As the elements if $\{0,1\}^A$ are functions $A\to \{0,1\}$ then *defining* a function is *EXACTLY* the way to find an element....  The element you found *is* that function you just invented.
Comment: This sort of gets at my earlier comment. $h$ as defined is a function from $\{0,1\}^A$ to $\mathcal{P}(A)$. It might not hurt simply to mention that (it's clear from context but often people reading these things like to see the domain and codomain expressly identified when a function is defined). To prove $h$ is surjective one must, as you do, fix $X \in \mathcal{P}(A)$ and produce $f \in \{0,1\}^A$ with $h(f) = X$. So you *do* show that $h$ is surjective by "defining a function" (in a way that works for any $X$ in the codomain of $h$).
Comment: There is considerable variation in how much proofs like this walk you back through the definitions of the things you are proving (e.g. what it means for a function to be injective or surjective, with the ingredients of the proof simply "plugged in" to them before any subsequent analysis or comment is made, e.g. "to show that $h$ is injective, we must show that $h(f) = h(g)$ implies $f=g$."). This is not really being more "formal"; I see it more as a stylistic choice than anything else. But it can help convey to the reader, or yourself, that your argument is in fact doing what it sets out to do
Comment: @leslietownes This makes a lot of sense! In my experience, proofs are often a little complicated to follow when not enough has been explained. Thank you for your response(s)!
Comment: I think the hardest thing for this and proofs like it, is to really *grock* what the terms $\{0,1\}^A$ and $\mathscr P(A)$ *mean* and to picture what a function $\phi:\mathscr P(A) \to \{0,1\}^A$ or $\psi: \{0,1\}^A \to \mathscr P(A)$ would *look* like.  But  once you get if $f:A \to \{0, 1\}$ is a function so that $f(x)=$ either $0$ or $1$ and $E_f \subset A$ based somehow on what the function $f$ does, then $f\in \{0,1\}^A$ and $E_f \in \mathscr P(A)$ and we HAVE "mapped" $f \mapsto E_f$.  So that *is* what is going on. Do that for every element and we have $\psi:\{0,1\}^A\to\mathscr P(A)$.
Comment: @fleablood I think I will use your approach from now on.
Comment: @fleablood Any chance I could get your help with the following: https://math.stackexchange.com/questions/4036232/limit-with-a-set-proof
Answer: I'd be more direct.
Let $f\in \{0,1\}^A$.  Then $f$ is a function $f: A \to \{0,1\}$
Consider $\{a\in A| f(a) = 1\}$.  That's well defined subset of $A$.
And so $\phi:\{0,1\}^A\to \mathscr P(A)$ via $\phi(f) = \{a\in A| f(a) = 1\}$ is a well-defined function.
Now its just a matter of proving it is surjective and injective.

It is surjective.

Let $E\subset A$.  Define $g:A\to \{0,1\}$ via $g(a) =\begin{cases}1&a\in E\\0&a\not \in E\end{cases}$.  $g$ is a well defined function from $A\to \{0,1\}$. so $g \in \{0,1\}^A$.
Because that's what $\{0,1\}^A$ is:  Its the collection of all possible functions for $A\to \{0,1\}$ and $g$ certainly is a function that for every element of $A$ maps distinctly to either $0$ or $1$.
And $\phi(g)=\{a\in A|g(a)=1\} = \{a\in A|a \in E\} =E$.
SO for all $E\in \mathscr P(A)$ there a $g\in \{0,1\}^A$ so that $\phi(g) = E$. So $\phi$ is surjective.

It is injective.

$f, g\in \{0, 1\}^A$ and $\phi(f)=\phi(g)=E$.  Then for every $a \in A$ we have either $a\in E$ in which case $f(a)=g(a) = 1$; or $a \not \in E$ in which case $f(a)=g(a)=0$. In either case $f(a) =g(a)$ for all $a \in A$.
So $f = g$.  For any $f,g \in \{0,1\}$ we have $\phi(f)=\phi(g) \iff f=g$ so $\phi$ is injective.
....
ANd that's that.
....
This will hold of $A = \mathbb N$ or $A =\mathbb N^{\mathbb N}$ or for any set.
$\{0,1\}^{\mathbb N}$ is the set of all functions from $\mathbb N \to \{0,1\}$.  We can find a one-to-correspondence between any subset of the natural numbers to a function (and vice versa) by for each subset considering the function where $f(n)=1$ if $n \in A\subset \mathbb N$ and $f(m) = 0$ if $m\not \in A$.
......
COuld you try harder to put your finger on what in your gut doesn't feel right because this is utterly complete and formal and foolproof so far as I can tell.
Comment: Looks fine to me. I note that it avoids a mild infelicity of notation in the original, where the notations $h(f)$ and $A_f$ are redundant, and perhaps the use of $A$ in $A_f$ arguably invites confusion (in some, but not in me) with the set $A$ that begins the problem.  (If you called it $B_f$ there would be no trouble with just calling the function $B$, skipping $h$ entirely, and describing its action by $f \mapsto B_f$ or $B(f)$. Whereas $A$ cannot double as a function and the name of the original set). It is certainly cleaner with less notation.
Comment: Yes Indeed!  $|\mathscr P(\mathbb N)| = |\{0,1\}^{\mathbb N}| =2^{\mathbb N}=  |\mathbb R| = |$ all countably infinite sequences of $0$ and $1| =|$ all sequences of natural numbers$| = |$ all function of natural numbers to any countable set|--- is one of the *fundamental* and well known results of cardinality.
Comment: Consider this (You might as well see it now... you *will* see it later).  Let $x\in \mathbb R$.  Express $x$ is as a binary decimal.  Let $\mathbb N\supset A = \{n\in \mathbb N|$ the $n$th digit of $x$ as a binary is equal to $1\}$.  That's a 1-1 mapping from  $\mathbb R$ to$\mathscr P(\mathbb N)$ .  ... well actually it's only a mapping from the  real interval $[0, 1]\subset\mathbb R$ to $\mathscr P(\mathbb N)$ but we can make modifications to get it to work from all $\mathbb R$.
Comment: @fleablood Oh my God! Check that, Oh my Blood! This is far more detailed! Thank you for that!
Comment: Also, wouldn't the case that $A = \mathbb{N}$ imply that the cardinality of $\cal P(\mathbb{N})$ is equal to that of $\{0, 1\}^{\mathbb{N}}$? So the power set of naturals has the cardinality $2^{|\mathbb{N}|}$?
Comment: @fleablood Have any recommendations where I can read more about $\cal P(\mathbb{N})$ and $\mathbb{R}$? By the way, with proofs like yours, you should contribute to proof wiki (the proofs there are much too complex) or start a Youtube channel!
Comment: @fleablood Cleaner way to say it: Let $A: [0, 1] \to P(N)$ such that $A(x) = \{n \in N \mid \text{the $n$th binary digit of $x$ is $1$}\}$. Then $A$ is bijective so $[0, 1] \equiv \mathcal{P}(N)$ as sets and hence $\bf{R} \equiv \mathcal{P}(N)$ as sets.
Comment: @Kraftsman Re: book recommendation: Abbott's *Understanding Analysis* is an analysis book that covers all the elementary set theory discussed in this answer and its comments. It's aimed at undergrads taking a first analysis course and has lots of exercises with solutions, which you might find useful for self-study
Comment: @Asker cleaner maybe.  It's  a trade of.  Sometimes thinking *functions* that take *sets* as single elements output (or input), or other functions as input or elements, is an abstract concepts many students have a mental block over.  But sometimes a casual "we have a set of subset here, and real number here, and we can assign a set to be number by so and so" avoids the mental block (even though it the exact same thing!)

Equivalent sets proof


curl within Ruby stripping out paramters

Question: For some reason, whenever i try to invoke a bash curl command within my ruby console, it always strips out all except the first parameter. can anyone please explain why only the first parameter is sent?
for example, if i have something like
`curl -F file=@../cheddar.txt -X POST http://myapp.com/endpoint?key=cheese&action=eat&when=now&id=#{some_id}&version=#{my_version}`

only the key parameter is accepted on the backend. However, the when or version parameter are all null. On my backend, im using Java google appengine, and it's a very standard servlet that has been tested and works with regular curl command. I know that the first parameter is sent because if i dont send the key, then something else will happen on backend (and likewise if i swap something else to the first parameter, that gets sent)
Any ideas what might be happening?
Comment: Try enclosing the url in double quotes. See for example http://stackoverflow.com/questions/20955748/wget-to-download-image-link-get-truncated/20955807
Answer: I think your shell is reading the ampersands as shell commands.  You need to escape strings you send to your shell so that it knows these characters are to be taken literally. Check out this script:
#!/usr/bin/env ruby

require 'shellwords'

url = 'http://myapp.com/endpoint?key=cheese&action=eat'

puts "With unescaped string:"
puts `echo #{url}`  # => "http://myapp.com/endpoint?key=cheese"
puts 'Note the absence of the last parameter action=eat'
puts "\nNow, with escaped string:"
escaped_url = Shellwords.shellescape(url)
puts `echo #{escaped_url}` # => "http://myapp.com/endpoint?key=cheese&action=eat"

Here's what Shellwords.shellescape does:
2.3.0 :014 > Shellwords.shellescape('http://myapp.com/endpoint?key=cheese&action=eat')
 => "http://myapp.com/endpoint\\?key\\=cheese\\&action\\=eat"

Another way to do this is to insert double quotes where appropriate, such as:
command = %q{echo "http://myapp.com/endpoint?key=cheese&action=eat"}
puts `#{command}`

Note that this behavior has nothing to do with curl; curl is just processing whatever it gets from the shell.  So you would need to do this with other shell commands as well.


SQL Left Join via foreign keys, how to avoid duplicate columns?

Question: I have numerous tables I join with a primary key field. I can query with the below to get the results I need.
Select *
from orders
Left Join serviceorders on orders.contractLineID = serviceorders.lineID
Left Join all_orders on orders.OrderNum = all_orders.ordernum
Left Join invoices on orders.OrderNum = invoices.OrderNum
Left Join schedule on orders.OrderNum = schedule.Ordernum;

But when I try to create a view from this, I face duplicate columns, as each table I'm joining has the ordernum in it.
I know I shouldn't use * to select everything, but I don't know the syntax for selecting columns from multiple tables?
Is it just:
SELECT orders.column1, orders.column2 schedule.column1, schedule.column 2, invoice.column1, invoice.column2

FROM orders, schedule, invoice

I've also seen you can use the USING command, but the syntax for that is unclear. I'm not sure if that would be the better option as it's just the one column that's being repeated across all tables.
Comment: If you want specific columns only, do not use `SELECT *` specifiy the columns. This is done by declaring the [tablename].[column] (with comma separation between each)
Answer: Here's the syntax:
SELECT TableA.id AS tableA_id, -- Or anything you want to name it after 'AS'
       TableB.id AS tableB_id
  FROM TableA
 INNER
  JOIN TableB
    ON TableA.key = TableB.key

This is if you need the view to have both ids, with a distinct name. Better yet only select the columns you want.
Answer: First, learn to use aliases.  Second, you should list all the columns:
Select o.col1, o.col2, so.col3,  -- list columns you want explicitly
       ao.col3 as ao_col3        -- if you still have duplicates, assign new names
from orders o left join
     serviceorders so
     on o.contractLineID = so.lineID left join
     all_orders ao
     on o.OrderNum = ao.ordernum left join
     invoices i
     on o.OrderNum = i.OrderNum left join
     schedule s
     on o.OrderNum = s.Ordernum;

Comment: I've managed to get it to work doing this. I don't suppose there's an easy way to select everything but certain columns?
Comment: @PeterCollins . . . Not in MySQL.  Google's BigQuery supports an `EXCEPT` clause which does exactly that.


Jazz flute - correct way to fall-off?

Question: For my A Level Music recital one of my pieces is Fly Me To The Moon, as sung by Frank Sinatra, for jazz flute. There is only one "fall-off" in the piece, on an Ab in the middle register. Regarding the notes that should be played for this and the use of the embouchure to get a "falling" sound, how should this be played?
Here's a picture of the notation where the fall-off is on the last Ab:
Answer: Hold the last Ab until the 'and' of I, then, while quickly reducing the aperture of your embouchure to reduce the volume of the sound produced, press the keys down chromatically.  It must be done very quickly to avoid the audience hearing each separate note of the fall.  This should create a downward glissando effect that fades into nothing (make sure not to land hard at the bottom, just fade away).
Source: Complete Jazz Flute Book by William Bay
Answer: Here's an excerpt taken from Complete Jazz Flute Book by William Bay:

Play the written note for about one-half of its value, then quickly "Slide" down chromatically. The chromatic notes should not sound individually, and there should not be any particular pitch in evidence at the end of the [fall-off]!

So the correct way to play seems to be a chromatic descent with diminuendo to nothing. To get the diminuendo it is necessary to reduce the aperture of the embouchure and perhaps also achieve some pitch bend to emphasise the "falling" sound.

Jazz flute - correct way to fall-off?


In a vector space in finite dimension, all vectors which are not colinear, are orthogonal. True or false?

Question: This is a theorem I learn few month ago, and I found it funny. Well I found on facebook, some groups about mathematics, and just to test people I said :

In a vector space in finite dimension, all vectors which are not co-linear, are orthogonal. True or false ?

And each time it was a fifty fifty between people who agreed and others. Then I think here maths level is higher than in these groups, can you tell me if the demonstration I have is true or false?

I just precise before, than english is not my mother tongue, and I will maybe make some maths vocabulary mistakes (and english too)

Proof :
All free familly of vectors can be completed as a base. All basis $(e_1,...,e_n)$ can be consider as an orthogonal (or orthonormal if base's vectors are unit vectors) base for the choice of one dot product. Then define a different dot product for each bases of the vector space. QED
Obviously the theorem is false in an euclidian space...

So what do you think, are my maths teachers in the truth ? I hope my translation is correct.
Thank you in advance for your answers.
Comment: One should note that the notion of orthogonality requires an inner product space, and that is not part of the premise. - Likewise one might claim that given any finite set (having at least three elements) any two elements of it are inverse to each other and argue that one can definie a suitable group structure on that set
Comment: I don't undersand the "translation request" part of your question, since there is no original language quote.
Comment: My translation request is just because I may did some english mistakes :)
Comment: Since we don' have the original text, you should remove the tag. You can still try to explain more in details your issue (there is a statement, a proof which does not seem to fit...).
Comment: So the two vectors $(1,1)$ and $(1,0)$, not being collinear, are orthogonal?
Comment: Yes if you define a special dot product just for them !
Comment: @JackD'Aurizio Not with the usual dot product.
Comment: The question is reasonable. Your answer is bizarre. If you have $n+1$ mutually non-colinear vectors in an $n$-dimensional space, no matter when you decide to define an inner product, you cannot have them all be orthogonal.
Comment: So if the vector space does not have an inner product, then _no_ vectors are orthogonal, but any two vectors can be _made_ orthogonal by imposing a suitable inner product on the vector space.
Answer: The following sentence is neither true nor false, because it has no meaning:

In a vector space in finite dimension, all vectors which are not collinear, are orthogonal.

Collinearity and orthogonality are not properties of vectors;
it is meaningless to say that a vector $v$ is collinear or that
another vector $u$ is orthogonal.
There is no such thing as "all vectors which are not collinear".
A set of vectors can be said to be collinear or orthogonal.
(I think this would generally be understood to mean
pairwise collinear or pairwise orthogonal.)
So we could decide the truth value of a statement such as this:

In a vector space in finite dimension, all sets of vectors which are not collinear, are orthogonal.

This is false for any dimension greater than $1$;
take any two non-collinear vectors $u$ and $v$ in the vector space, and then
the set $\{u,v,2v\}$ is neither collinear (on account of $u$ and $v$) nor orthogonal (on account of $v$ and $2v$) regardless of the definition
of the inner product.
The following statement is true:

In a vector space in finite dimension, any pair of vectors that are not
  collinear are orthogonal under a suitably chosen inner product.

In other words, given non-collinear vectors $u$ and $v$, there is
some inner product under which those two vectors are orthogonal.
This is what the "proof" in the question actually shows.
But there is no single inner product space in which every pair of
vectors is either collinear or orthogonal.
Given an inner product space and two vectors $u$ and $v$ that are orthogonal
in that vector space, $u+v$ is also a vector and $\{u,u+v\}$ are
neither collinear nor orthogonal.
So this statement is false:

In a vector space in finite dimension with inner product
  $\langle\cdot,\cdot\rangle$,
  any pair of vectors that are not collinear are orthogonal.

The statement about Euclidean space in the question is an example of this.
Comment: Its exactly why I took a translation request, now you have translate me the theorem as I understood it. Its just I don't speak english as well as i want . Thank you !
Answer: The question simply doesn't make sense as stated, which might explain the disagreement on Facebook: One can only speak of orthogonality of vectors in a vector space when the space is endowed with an inner product. The "proof" is anyway an argument for the following:

For any linearly independent set $S$ of vectors in a f.d. vector space $\Bbb V$, there is some inner product on $\Bbb V$ with respect to which the vectors in $S$ are pairwise orthogonal.

Likewise, it doesn't make sense to say that this result fails for Euclidean space, because by definition the term Euclidean entails a fixed inner product. (of course, the statement is true for the vector space $\Bbb R^n$ underlying the Euclidean space $(\Bbb R^n, \langle\,\cdot\, , \,\cdot\,\rangle)$).
Comment: The word "orthogonal" is not defined for vector spaces, so the question uses undefined terminology, and must be modified before it makes sense. Your argument is valid if you replace "all vectors that are not collinear are orthogonal" with "for every pair of vectors that are not collinear, there is an inner product for which they are orthogonal".
Comment: So if I take a vector space with just a,b and c as vectors then I  define threedifferents dot prod in such a way that (a,b)=0 ((a,c))=0 =0 i'm wrong ?
Comment: Wrong about what? Again, the original true-false question doesn't even make sense as written.
Comment: I don't undertand what it doesn't make sense... you take all possible basis of the vector space, and for each of them you use Gram-Schimdt process then you find orthogonal basis. ?
Answer: This is probably a problem of how you make the statement.
If you ask

In a vector space in finite dimension, all vectors which are not linearly dependent, are orthogonal?

it means that you already have an inner product, it doesn't have sense to say 'orthogonal' in other case, so, IMHO this is just a funny puzzle, everyone would answer NO but you have a nice (but incorrect) argument to argue that the answer is YES.
Comment: But if you _already_ have an inner product, then there are pairs of vectors that are neither collinear nor orthogonal. Given an arbitrary pair of non-collinear vectors you can "make" them orthogonal, but first you may have to remove the old inner product and define a new inner product, and after you have done this there still will be other pairs of vectors that are neither collinear nor orthogonal.
Comment: @DavidK So, are you arguing that the process of creating a new inner product such that a *given* set of linearly independent vectors is orthogonal can not be performed?
Comment: Actually I think I'm agreeing with your answer. Of course, given any set of linearly independent vectors you can always define a new inner product that will make them orthogonal, but then simultaneously you make some other sets of linearly independent vectors _not_ orthogonal.
Comment: @DavidK Exactly! So, in conclusion, the proposition is **always** false, in some sense: once you fix an inner product, there will always be non-orthogonal linearly independent sets of vectors (with more than one vector).


Is it possible to include dependency app -from another repository- in a circleci build?

Question: The problem
I have a single repo project which I split it in 2 separate repos.
I split it because it was difficult to manage such a monolithic beast.
In both repos I have implemented circleci tests.
The tests in the first repo are failing because they depend on the existence of a second application which lives in the second repo. The circleci tests in the second repo run successfully.
In general, the first repo is a Flask app with a database and the second repo is an Flask-ElasticSearch-redis app/service.
I experimented with workflows, but I couldn't make it work. When I SSH to the first's repo circleci workspace, I couldn't see any URLs related to the second app (using netstat), which is expected.
Is it possible to build and run the circleci tests of the first repo in a way that the build will include the second (dependency) app?
Answer: git clone from the repo that has the dependency and build both.
Comment: it would be great if it was so simple, git clone isn't enough. The dependency app it's an API, so it need its own stack to work.
Comment: Any idea if the dependency is already built in another repo with an artifact from circleCI?


Duvida Distinct com Doctrine_Query

Question: Tenho uma tabela em mysql e preciso retornar valores únicos desta tabela só que não estou conseguindo criar uma function ou uma consulta que se adapte. A instrução SQL no banco seria assim e funciona certinho, só que em Doctrine não consigo fazer :
SELECT DISTINCT anodecorrente FROM ct_noticias WHERE categoria = 'Infanto' ORDER BY nt_id ASC

Tenho a classe que mapeia a tabela em Doctrine como CtNoticias.
Comment: Ajuda aí pessoal !!!, qualquer ajuda é bem vinda.
Answer: Tete a seguinte DQL:
$this
    ->getEntityManager()
    ->createQuery('
        SELECT DISTINCT(c.anodecorrente)
        FROM CtNoticias c
        WHERE c.categoria = :categoria')
        ORDER BY c.ntId ASC
    ->setParameter('categoria', $categoria)
    ->getResult();

Você pode ter que atualizar os nomes das propriedades para os nomes dos modelos da sua classe CtNoticias.

Duvida Distinct com Doctrine_Query


When are $\mathfrak O_K/\mathfrak p^m$ and $\mathbb Z/p^m\mathbb Z$ isomorphic as $\mathbb Z$ modules?

Question: Given an algebraic field $K$ and denote by $\mathfrak O_K$ its ring of integers. Suppose that $\mathfrak p$ is a prime ideal and $p$ is a prime contained in $\mathfrak p$. Under what conditions of $\mathfrak p$ can $\mathfrak O_K/\mathfrak p^m$ be isomorphic to $\mathbb Z/p^m\mathbb Z$ as $\mathbb Z$-modules?
Note that if they are isomorphic, then the number of elements in $\mathfrak O_K/\mathfrak p^m$ must be $p^m$ and therefore the norm of $\mathfrak p$ must be $p$. Is this condition also sufficient? Or what is the sufficient condition?
Answer: Your condition is not sufficient. Let $e$ and $f$ denote the ramification and inertial degrees of $\mathfrak{p}/p$. The norm homomorphism satisfies $N(\mathfrak{p}) = p^f$, so the condition that $N(\mathfrak{p}) = p$ is equivalent to the condition $f = 1$. This implies that $\mathcal{O}_K/\mathfrak{p}$ and $\mathbb{Z}/p\mathbb{Z}$ are isomorphic as fields (and hence $\mathbb{Z}$-modules), so your condition does work for $m = 1$.
However, for larger $m$, you need to add an addition hypothesis. Indeed, the smallest power of $p$ in $\mathcal{O}_K/\mathfrak{p}^m$ is equal to $p^t$ where $t = \lceil \frac{m}{e} \rceil$. Assuming $f = 1$, we know that $|\mathcal{O}_K/\mathfrak{p}^m| = p^m$, so the $\mathbb{Z}$-module isomorphism $\mathcal{O}_K/\mathfrak{p}^m \equiv \mathbb{Z}/p^m$ holds iff the smallest power of $p$ in $\mathfrak{p}^m$ to be $p^m$. It is easy to check that this is true iff $m = 1$ or $e = 1$.


Conflict between implicit declaration and varargs function

Question: Can anyone confirm what the standard says about the default return type of vararg function. I was compiling the following code:
int main()
{
    maw(32,3,95,38,20,15);
    return 0;
}

int maw(int a,int b,...)
{
    int *p=&b,i=0;
    while(i++<a)
       printf("\t%d",*p++);
    return 0;
}

but it gave error:
foo.c:9: error: conflicting types for 'maw'
foo.c:10: note: a parameter list with an ellipsis can't match an empty parameter name list declaration
foo.c:4: error: previous implicit declaration of 'maw' was here

but if during the definition of maw, if I mention it as void maw(int a, int b, ...) the compilation is quite fine.
I can make out from this that the default return type of vararg function is probably not int.
What does the standard say in this regard? Can anybody confirm it for me?

I know that if I just standardized the code it will run perfectly. I have done it. There is no problem with that.
My point is: what is the problem with this code? It should have run perfectly.
Doesn't a code like this run without any error?
int main()
{

abc();
.....
return 0;
}

abc()
{
.......
}

The problem is coming when a variable argument function is being used.
I know what the standards say for default declration of the function.
Answer: The other answers are correct, about putting the function prototype first.
Additionally, to be portable, do not access the ... arguments by using a direct pointer to the last (non-vararg) argument, because then you have to care about the alignment and stack direction of your target platform. Instead, use <stdarg.h> and the va_* macros for working with varargs.
Comment: +1 for pointing out the problem with direct access to the stack
Comment: + for a nice answer after 4 "place it BEFORE the main" :)
Answer: Declare maw() before main(), or prototype it before main(). Functions return the types that you assign to them, regardless of arguments (variadic or not).
Answer: The problem is that you're calling the function before defining it, and not including a declaration. If you add a line like this:
int maw(int a, int b, ...);

Before your main() function, you'll be fine. The default ("implcit") is to assume a function returns int, and has an empty argument list. It's bad form to rely on the implicit declaration, you should declare all functions explicitly.
Answer: It's nothing to do with the return type - it's the fact that you declared it at all. Put a declaration:
int maw(int a,int b,...);

before your use of the function in main()
Answer: As every answer (so far) has said: to avoid the errors, declare the function before its use, and as Chris Jester-Young points out, use the standard mechanisms for accessing the variadic arguments or suffer the pains of Undefined Behavior.
In this example, it is not that the declaration before use in this case is required because of the function's return type, but rather because it does not match the default signature for an undeclared function: int u(); that is, a function taking unspecified arguments returning an int. Specifically, the actual definition int maw(int,int,...) is inconsistent with different from the assumed declaration int maw() which causes GCC to say "conflicting types for 'maw'".
Your second example
int main() {
  abc(); ..... return 0;
}
abc() { ....... }

works because the later definition of abc doesn't contradict the default signature assumed when its first call was encountered. But just because it works doesn't make it good form because you get almost no type safety from the default signature.
Access to the variadic arguments (the ones matching the ...) really should be done through the standard mechanisms of stdarg.h, unless you are implementing a compiler and are the author of that compiler's stdarg.h. For instance, on some architectures those arguments may not even be passed on the stack, but they can still be located by the macros from stdarg.h.
Edit: I reworded the second paragraph to say what I meant in a different, and I hope clearer, way.
The compiler needs to know that the function is variadic before the first call because on some architectures, it might be required to pass the variadic parameters differently than normal parameters. That is especially true of certain register-window RISK architectures, and those that might pass the first 2 ints and first 2 floats in registers, but must put all variadics on the stack even if there is room in the regsisters.
A similar declare before use situation exists for functions that do not use the cdecl calling convention. You will usually run into this when linking modules written in Pascal or FORTRAN with modules written in C. However, many of the Windows API functions exported by the core DLLs assume a calling convention named stdcall and if the compiler were to use a cdecl style call, the program would crash (and the whole machine on Windows 9x or earlier).
Comment: as you said "Specifically, the actual definition int maw(int,int,...) is inconsistent with the assumed declaration int maw()"
if it is consistent with the assuemed declration then why is it giving the error?can you shade some light on it?
Comment: "inconsistent" == "not consistent". That is, the two declarations are not consistent, which is what the error message is trying to say.
Comment: okay really thanks for reply.
I wholeheartedly accept what you said.
If i define in my 1st exmpl maw as void maw like this

void maw(int a,int b)
{
.......
}
I think it is more confilicting,
but it is not giving any error and compiling quite fine.
is it some undefined behaviour or else.
thanks
Comment: On my Windows box, MinGW's GCC 3.4.5 simply says "error: conflicting types for 'maw'" for both the original variadic example and for void maw(int a, int b){}. Regardless, unless the implicit declaration matches the actual definition, you are invoking undefined behavior.
Answer: Add the declaration
int maw(int a,int b, ...);

before your main() function.
Currently, the call you make within your main() function implicitly defines maw(), that is, the compiler "guesses" what maw()'s return type is based on the information it is given within main(). If you declare maw() before it is called, you will not have this problem.
Answer: Calling an implicitly declared function that actually takes a variable number of arguments has undefined behavior.
I did not see an answer that actually quoted the relevant portions of the standard. For an implicit function definition, this is only allowed in C89 and C90.
From C89, §22.214.171.124, ¶4:

If the expression that precedes the parenthesized argument list in
  a function call consists solely of an identifier, and if no
  declaration is visible for this identifier, the identifier is
  implicitly declared exactly as if, in the innermost block containing
  the function call, the declaration
         extern int  identifier();
  appeared.

In the same section, ¶6, it states that calling an implicitly declared function that is later declared to take a variable number of arguments causes undefined behavior.

If the expression that denotes the called function has a type that
  does not include a prototype, the integral promotions are performed on
  each argument and arguments that have type float are promoted to
  double.  These are called the default argument promotions.  If the
  number of arguments does not agree with the number of parameters, the
  behavior is undefined.  If the function is defined with a type that
  does not include a prototype, and the types of the arguments after
  promotion are not compatible with those of the parameters after
  promotion, the behavior is undefined.  If the function is defined with
  a type that includes a prototype, and the types of the arguments after
  promotion are not compatible with the types of the parameters, or if
  the prototype ends with an ellipsis (", ..."), the behavior is
  undefined.


Vários carrossel diferente com owlCarousel

Question: Em minha página preciso de 3 carrossel:
Um para o banner, outro para régua e mais um para avaliações. Todos vão ser com imagens e precisaria que cada um tivesse seu parâmetro, porém com o OwlCarousel não consegui fazer, já que quando faço a chamada do Own ele não permite modificar os demais carrossel.
$(document).ready(function(){

    $('.owl-carousel').({
    loop:true,
    margin:10,
    nav:true,
    responsive:{
        0:{
            items:1
        },
        600:{
            items:3
        },
        1000:{
            items:5
        }
    }
})

});

Com o script acima ele fica o mesmo para os 3 e preciso dividir para cada um ter sua característica. Obrigado!
Comment: Por quê você não utiliza o `id` de cada carrossel como seletor? `$("#carousel_1").owlCarousel({...})`, `$("#carousel_2").owlCarousel({...})`, `$("#carousel_3").owlCarousel({...})`.
Comment: Eu tentei mas não carregou corretamente
Comment: Consegue colocar na pergunta esse código também?
Answer: Como eu disse nos comentários, basta inserir um id único para cada carrossel e utilizá-lo como seletor. Perceba que o id deve estar no elemento referente ao carrossel, isto é, o mesmo elemento que possui a classe .owl-carousel. Veja um exemplo abaixo:

$(() => {

  $('#carousel1').owlCarousel({
    loop: true,
    margin: 10,
    nav: true,
    responsive: {
      0: {
        items: 1
      },
      600: {
        items: 3
      },
      1000: {
        items: 5
      }
    }
  });

  $('#carousel2').owlCarousel({
    loop: true,
    margin: 10,
    nav: true,
    responsive: {
      0: {
        items: 1
      },
      600: {
        items: 2
      },
      1000: {
        items: 5
      }
    }
  });

  $('#carousel3').owlCarousel({
    loop: true,
    margin: 10,
    nav: true,
    responsive: {
      0: {
        items: 1
      },
      600: {
        items: 1
      },
      1000: {
        items: 5
      }
    }
  });

});
.item {
  height: 60px;
  background: LAVENDER;
}
<link href="https://owlcarousel2.github.io/OwlCarousel2/assets/owlcarousel/assets/owl.carousel.min.css" rel="stylesheet"/>
<link href="https://owlcarousel2.github.io/OwlCarousel2/assets/owlcarousel/assets/owl.theme.default.min.css" rel="stylesheet"/>

1

2

3

4

5

6

7

8

9

10

11

12

Comment: Valeu amigo deu certo!
Comment: Você pode agradecer votando positivamente na resposta e aceitá-la. Para isso, veja a pontuação ao lado esquerdo da resposta. Ao pressionar `^` você estará votando positivamente e pressionando `✓` você estará aceitando-a como solução ao problema.
Answer:

exemplo1

exemplo2

exemplo1

exemplo2

Nesse caso tentei criar outro JS para o comentarios e nao funciona
Answer: Olá, um item importante, você obrigatoriamente deve inserir a classe owl-carousel. Não necessariamente precisa trabalhar com ids, pode ser com classes também, mas, cada classe terá sua configuração.
Abaixo, segue o código para três slides.

$(function() {
  $('.style1').owlCarousel({
    loop: true,
    items: 1
  });

  $('.style2').owlCarousel({
    loop: true,
    items: 2
  });

  $('.style3').owlCarousel({
    loop: true,
    items: 3
  });

});

<link href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.2.1/assets/owl.carousel.min.css" rel="stylesheet" />


NSMutableURLRequest timing out after approx 15 seconds. Timeout is set at 240 seconds

Question: I'm working on an iOS app that uses a NSMutableURLRequest and a NSURLConnection to send data to my server. I need to display the error message when it fails. My code for sending the request is shown below
const int TIMEOUT = 120;

-(void)send:(id<NSURLConnectionDelegate>)delegate
{
    bodyContents = [bodyContents stringByAppendingFormat:@"--%@--",boundry];
    NSData *data = [bodyContents dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [request setValue:[NSString stringWithFormat:@"%i",[data length]+4] forHTTPHeaderField:@"Content-Length"];
    NSLog(@"Timeout before setting custom is %f",request.timeoutInterval);
    [request setTimeoutInterval:TIMEOUT];
    NSLog(@"Timeout after setting custom is %f",request.timeoutInterval);
    NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:delegate];
    if(connection)
        NSLog(@"Connection good");
    else
        NSLog(@"Connection not so good");
}

//in the delegate class
-(void)connectionDidFinishLoading:(NSURLConnection*)connection
{
    NSLog(@"connectionDidFinishLoading");
}

-(void)connection:(NSURLConnection*)connection didFailWithError:(NSError *)error
{
    NSLog(@"Failed with error %@",error);
    btnCancel.title = @"Retry";
    self.navigationItem.hidesBackButton = NO;
    [self showAlertDialog:[NSString stringWithFormat:@"%@",[error localizedDescription]] :@"Error"];
}

I would expect the didFailWithError message to be called after 2 minutes of no response. Instead it's called after about 15 seconds of no response which doesn't make any sense. I looked at the documentation to check if I was setting the timeout incorrectly, the only thing I could find is that the minimum timeout for a post with a body is 240 seconds which I have come to begrudgingly accept.
The output from running the app looks like this:

2012-06-22 16:49:12.393 Media Upload[672:707] Timeout before setting custom is 240.000000
2012-06-22 16:49:12.394 Media Upload[672:707] Timeout after setting custom is 240.000000
2012-06-22 16:49:12.395 Media Upload[672:707] Connection good
2012-06-22 16:49:29.174 Media Upload[672:707] Failed with error Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." etc

I'm more than a little confused as to why it's timing out so quickly. The server is not up when the connection is created so I'm not even sure why it says Connection good instead of connection not so good, but that's a different problem (I hope) Any suggestions?
Answer: So, I suspect that the answer is all in the semantics.
As for the "Connection good" logging instead of "Connection not so good", this is because init'ing a connection does not wait for it to do anything on the network. It does cause it to start right away, but not before it returns from the init method.
The more interesting (read:misleading) issue is with the timeout. I suspect that what the timeout setting really means is, "If I have established a connection, but the server just hasn't given me response bytes yet". Which is distinct from "I have been trying, but cannot connect". It makes a certain amount of sense when you think of it this way; One timeout value just for all the 'network' stuff (routing and handshakes) and another for the actual payload to be processed.
Comment: So just to be sure I understand, essentially the 15ish second timeout is because it can't find the server initially while the 240 second timeout is for "if I've contacted the server and sent my packet but it doesn't respond for 240 seconds then timeout." Is that right?
Comment: That's my understanding, yes. The 240 seconds is the 'connection' timeout, which applies once you have a 'connection'.


About The Sum of Positive Divisors of $n$

Question: The question says:

Find the smallest positive integer $n$ so that $\sigma(x)=n$ has no solution, exactly two solutions, exactly three solutions.

I could not come up with a good way to solve this question other that trial and error. But I am questioning this method. Is there any better ideas?
Comment: I think brute search is optimal, if a bit tedious.  You'll find the answer fairly quickly.
Comment: Absolutely, yes.  And you are  correct about $2,12$.  The third part won't take you as long as you fear.  Keep in mind $\sigma_1(n)≥n+1$ with equality only for primes.  That makes it easy to truncate your search.
Comment: Correct again. $\,$
Comment: (+1) for the posted solution, good work.
Comment: Oh, thanks, my method sounds good though.
Comment: found it to be 24?
Comment: Thanks for your help @lulu
Comment: If you are so inclined, you might want to post your calculations as a solution.  Keeps the question from being listed as unanswered.
Comment: @lulu, just done so and edited the question details to be convenient.
Comment: Thanks,, I really appreciate  :)
Answer: By trial and error, I have found that the solutions are:

$\sigma(x) = 2$   has no solution.
$\sigma(x) = 12$  has exactly two solutions that are $6$ and $11$.
$\sigma(x) = 24$  has exactly three solutions that are $14,15$ and $23$.
Answer: The number of divisors of a natural number $n$ is given by $\sigma(n) = \sum_{k=1}^{\infty}\left ( \left \lfloor \frac{n}{k} \right \rfloor-\left \lfloor \frac{n-1}{k} \right \rfloor \right )$.
This may be useful when expanding the summation.
Note that, when $n$ is a prime number, $\sum_{k=1}^{\infty}\left ( \left \lfloor \frac{n}{k} \right \rfloor-\left \lfloor \frac{n-1}{k} \right \rfloor \right )=2$
Comment: how did you come up with this formula?
Comment: $\sigma(n)$ is not the number of divisors function.


Basic C++: convert from char to string

Question: I'm a little confused by the class code.  Here's what I'm trying to do:
//Program takes "string text" and compares it to "string remove".  Any letters in
//common between the two get deleted and the remaining string gets returned.
#include <string>
#include "genlib.h"

string CensorString1(string text, string remove);

int main() {
    CensorString1("abcdef", "abc");
    return 0;
}

string CensorString1(string text, string remove) {
    for (int i = 0; text[i]; i++){
        for (int n = 0; remove[n]; n++){
            if (i != n){
                string outputString = ' '; //to store non repeated chars in,
                                           //forming my return string
                outputString += i;
                }
            }
        }
        return outputString;
}

I'm getting an error on the "outputString += 1" saying: "cannot convert from "char" to
std::basic_string
I'm also getting an error on the "return outputString" saying: undeclared identifier
???????

I get that I'm putting a "char" on a "string" variable but what if shortly that "char" will soon be a string?  Is there a way to pass this?
I'm always forgetting libraries.  Can someone recommend a couple of standard/basic libraries I should always think about?  Right now I'm thinking , "genlib.h" (from class).
C++ is kicking my ass.  I can't get around constant little errors.  Tell me it's going to get better.
Comment: I hope you didn't really put `using namespace std;` in a header, did you? What are you trying to achieve by `outputString += i`?
Comment: If this is homework, please tag.
Comment: *C++ is kicking my ass. I can't get around constant little errors. Tell me it's going to get better.* It has, it's called Java or C#, with C++ you will forever be stuck with libraries that use different kind of character strings and unsafe conversions. Of course, having these libraries and access to OS functionality is a major reason to go with C++ in the first place.
Answer: There are many errors in your code:

Your outputString needs to be in the outer scope (syntax)
You compare i to n instead of text[i] to remove[n] (semantic)
You are adding i to the output instead of text[i] (semantic)
You ignore the return of CensorString1 (semantic)

Here is your modified code:
string CensorString1(string text, string remove) {
    string outputString;
    for (int i = 0; text[i] ; i++){
        for (int n = 0; remove[n] ; n++){
            if (text[i] != remove[n]){
                outputString += text[i];
            }
        }
    }
    return outputString;
}

This has some remaining issues. For example, using text[i] and remove[n] for termination conditions. It is also very inefficient, but it should be a decent start.
Answer: At any rate, strings are always double-quoted in C and C++. Single-quoted constants are char constants. Fix that and you should probably be all right.
Also, look at this SO question: How do you append an int to a string in C++?
Good luck at Stanford!
Comment: Thanks WN.  That was helpful.  The little things...  Now I just need to understand why I get the Error "undeclared identifier" for "return outputString".  didn't I identify it above?
Comment: @MCP because you're declaring 'outputString' in the scope of if statement. It gets destroyed when that scope ends. It needs to be at the function scope, so declare it at the start of the function.
Answer: There are some problems there:
string outputString = ' '; will try to construct a string from a char, which you can't do. You can assign  a char to a string though, so this should be valid:
string outputString;
outputString = ' ';

Then, outputString is only visible within your if, so it won't act as an accumulator but rather be created and destroyed.
You're also trying to add character indices to the string, instead of characters, which is not what I think you want to be doing. It seems like you're mixing up C and C++.
For example, if you want to print the characters of a string, you could do something like:
string s("Test");
for (int i=0;i<s.length();i++)
    cout << s[i];

Finally, I'd say that if you want to remove characters in text that also appear in remove, you'd need to make sure that none of the characters in remove match your current character, before you add it to the output string.
Answer: This is an implementation of what I think you want, your code has multiple problems which just showed up described in multiple other answers.
std::string CensorString1(std::string text, std::string remove) {
    std::string result;
    for (int i = 0; i<text.length(); i++) {
        const char ch = text[i];
        if(remove.find(ch) == -1)
                result.append(1,ch);
    }
    return result;
}

Comment: That is actually pretty clean.  I'm assuing that implementation will be a lot less inefficient than my code?  I've got to get used to seeking member functions to complete a task...  Thanks JI.
Comment: When you're getting into it a bit more, you'll like iterators instead of the for loop above. Iterators are a bit harder to grasp, so I left them out of this simple implementation. When you feel more comfortable, look them up though :)

Basic C++: convert from char to string


vb.net Keydown event on whole form

Question: I have a form with several controls. I want to run a specific sub on keydown event regardless any controls event.
I mean if user press Ctrl+S anywhere on form it execute a subroutine.
Answer: You should set the KeyPreview property on the form to True and handle the keydown event there

When this property is set to true, the form will receive all KeyPress,
  KeyDown, and KeyUp events. After the form's event handlers have
  completed processing the keystroke, the keystroke is then assigned to
  the control with focus. .......... To handle keyboard
  events only at the form level and not allow controls to receive
  keyboard events, set the KeyPressEventArgs.Handled property in your
  form's KeyPress event handler to true.

So, for example, to handle the Control+S key combination you could write this event handler for the form KeyDown event.
Private Sub Form1_KeyDown(ByVal sender As Object, ByVal e As KeyEventArgs) Handles MyBase.KeyDown
    If  e.Control AndAlso e.KeyCode = Keys.S then
        ' Call your sub method here  .....
        YourSubToCall()

        ' then prevent the key to reach the current control
        e.Handled = False
    End If
End Sub

Comment: Thanks Steve... its very helpful
Answer: I've used this code in my forms before and it seems to work pretty good.
Protected Overrides Function ProcessKeyPreview(ByRef m As System.Windows.Forms.Message) As Boolean
    If m.Msg = &H100 Then  'WM_KEYDOWN
        Dim key As Keys = m.WParam
        If key = Keys.S And My.Computer.Keyboard.CtrlKeyDown Then
             'DO stuff
             Return True
        End If
    End If

    Return MyBase.ProcessKeyPreview(m)
 End Function

vb.net Keydown event on whole form


Return from function upon condition met in map

Question: Is there a way I can use map such that if a certain condition is met I can return an error? The reason is that i'm trying to implement the trait FromStr for my struct BigNum:
impl FromStr for BigNum {
    fn from_str(s: &str) -> Result<BigNum, BigNum::Err> {
        let filter_vec = t_num.chars().
            map(|a| match a.to_digit(10) {
                Some(x) => { x },
                None    => { /* return from function with Err */ }
            });
    }
}

Is this possible to do? Or should I simply iterate over the chars() myself and return an error upon reaching a None? Just wondering if there's an easy way to break out of map and return from the function
Comment: Did you try `return Err(..whatever..)`?
Answer: Two key pieces of information will be useful here:

Iterators operate one item at a time, so iterator adaptors will only be executed while something is consuming the iterator.
FromIterator (which powers Iterator::collect) is implemented for Result as well.

Since you didn't provide a MCVE, I made up sample code that can actually compile:
fn foo(input: &[u8]) -> Result<Vec<u8>, ()> {
    input.iter().map(|&i| {
        if i > 127 {
            Err(())
        } else {
            Ok(i + 1)
        }
    }).collect()
}

fn main() {
    let a = foo(&[1,2,3,4]);
    let b = foo(&[200,1,2,3]);
    println!("{:?}", a);
    println!("{:?}", b);
}

If you stick a println! in the map body, you can see that no numbers are processed after the 200.


Can't use map() method on an array nested in a cloned object (fetch API) - React Hooks

Question: I want to use the map() method on the cloned object but it keeps saying "Cannot read property 'map' of undefined" but I can use it to output the servings number ({copyRecipe.servings}). And I dont understand why console.log(copyRecipe) was shown 5 times with the first 4 empty (image below). Any helps would be appreciated. Thanks in advance!

const Parent = () =>{

  //I fetch data from my custom hook
  const {data: recipe, error, isLoading} = useFetch(url)

  return(
    <Child recipe={recipe}/>
  )
}

const Child = ({recipe}) =>{
  //I cloned the recipe from parent component
   const [copyRecipe, setCopyRecipe] = useState({});
   let duplicate = { ...copyRecipe };

   useEffect(() => {
   setCopyRecipe({...recipe});
   }, [recipe]);

   //this is to increase the number of servings when clicking the Increment component
   const incrementHandle = () => {
    duplicate.servings = `${parseInt(duplicate.servings) + 1}`;
    setCopyRecipe(duplicate);
  };
  console.log(copyRecipe);
   return(
   //I CAN USE THE CLONED OBJECT HERE!
   {copyRecipe &&
{copyRecipe.servings}
}
    <Increment onClick={incrementHandle}/>

     //I CAN'T USE THE CLONED OBJECT HERE!!!
   {copyRecipe && (

        {copyRecipe.ingredients.map((item,index) => {
          //do something
        })}

   )}
   )

}
Comment: [map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) is an array method. You can't use it on an object, cloned or not.
Comment: Your code is outside of the return statement of the component
Comment: @BrianThompson {copyRecipe.ingredients} is an array
Comment: @DanielDuong it was just typos, I corrected it. I didn't make that mistake in the real project
Comment: "Cannot read property 'map' of undefined" is about `copyRecipe.ingredients.map`? Try this: `copyRecipe?.ingredients.map`.
Comment: @CarloSchneider I tried it but it didn't work. I think it's the copyRecipe  object wasn't  available when the map method was used
Answer: So the console.log(copyRecipe) is firing every time the useEffect is being triggered.
Using Array.prototype.map is returning undefined, because it is undefined. You're trying to deconstruct from an api call which is going to be asynchronous.
Everything else, the useEffect of the child, the deconstruction and declaration of the variables of the parent are happening synchronously, and on mount, they aren't defined because the fetch hasn't evaluated yet.
Ok so you are using useEffect in the custom hook...
Now I think the problem is you're still trying to render the components based on an empty object.
Empty objects evaluate to truthy
I would recommend Object.entries(copyRecipe).length > 0 instead of copyRecipe as your conditional for rendering in the child component's return statement.
Comment: @Simon can we see a full print out of the copy recipe object? Also i think just checking if the object copyRecipe is truthy is always going to give you true. Maybe check Object.entries(copyRecipe).length > 0
Comment: Inside the parent component, I actually use the fetched data to render some components so I thought the data is also available to be passed to its child component. Speaking of your suggestions, I actually used useEffect in the custom Hook. Here is the link to it: https://www.dropbox.com/s/kxxfv0y0chk9hav/useFetch.png?dl=0
Comment: Is there a reason why the dependency array for the child useEffect has recipe and not copyRecipe
Comment: So I'm not sure if I have to change any parts of it. I'm pretty new to react and it would be great if you can show me exactly what I should change in the custom Hook. Thank you  :)
Comment: Speaking of the dependency, I actually  posted a question about cloning an object and got that answer. From my understanding, every time the recipe changes the setCopyRecipe will be called
Comment: I actually think the custom hook is fine. I'm looking back through the code now.
Comment: Are you only rendering one parent and one child?
Comment: There are actually 3 children, the one I've been asking about is the second one. The first and second child share the same api data. Here is the link to it: https://www.dropbox.com/s/8i7zjqzv6rh6t0x/children.png?dl=0
Comment: I changed the code like this: https://www.dropbox.com/s/hqotekmuwh7wp1x/object.entries.png?dl=0


Access HttpContextBase object from static class

Question: ASP.NET 4.6.1 using MVC 5.
I have a class with the following constructor and I'm setting a session variable:
public class MyClass()
{
    private HttpContextBase Context { get; set; }

    public MyClass(HttpContextBase context)
    {
        Context = context;
    }

    public bool CheckForAccess()
    {
        Context.Session["MyVariable"] = "Hello";
        return true;
    }
}

I can access the session and pass it to my object from my controller like so:
public ActionResult Index()
{
    var myclass= new MyClass(HttpContext);
    var excluded = myclass.CheckForAccess();
}

This is working fine. Now i have a static class and i need to call the same function in MyClass:
public static class MyClassExtension
{
    public static bool Check()
    {
   //here's where i'm stuck
    var myclass = new MyClass(I_need_to_pass_the_HttpContextBase_from_here);
        return myclass.CheckForAccess();
    }
}

This is where i'm stuck. I'm clearly trying to access the current session of the logged in user and pass it around when i have to. What do i pass from my static class to the constructor of with an HttpContextBase parameter so it can be used in the MyClass object? Thanks
Comment: what is the error?
Comment: I do not know what to send in my static class to the constructor when I instantiate the non static object. The comment //heres the problem is where im stuck
Comment: Add the context as a parameter to your static function and pass that in...
Comment: from your page, you can call MyCallExtension.Check(HttpContext) and your code should work!! not sure where you are really struck
Comment: Thats not what i'm doing..I'm making the call to my non static method from my static class. I need to access the HttpContextBase from my static class and pass it to my non static class.
Comment: @JeffMercado - thats what im trying to do. Show me how in code
Comment: @BoundForGlory - Are you asking to access HttpContextBase directly without being that parameter passed to your static method? I'm sure that's not the way you should look into.  I'm actually not sure what you are trying to do but it looks like your logic needs a second-thought
Comment: @techspider - check out the answer. you were making this to be something it wasnt
Comment: @BoundForGlory, I would not prefer that solution; you can also see Brian's suggestions; there are always two things - getting things done and getting things done in the right way :)
Comment: @techspider - i agree with you 100%. I have checks for error in my application. You are seeing a very small part of my entire app. Thanks for your input
Answer: You can use HttpContext.Current, but beware: if the static is called outside of the ASP.NET request, HttpContext.Current will be null (or may be null in certain situations depending on how you are using this):
public static bool Check()
{
    var myclass = new MyClass(new HttpContextWrapper(HttpContext.Current));
    return myclass.CheckForAccess();
}

HttpCOntextWrapper exists to wrap the old HttpContext sealed class and support the HttpContextBase base class.


R: Fill empty cell with value of last non-empty cell

Question: In Excel, it is easy to grab a cell within a column and drag the cursor downward to replace many cells below so that each cell becomes the same value as the original.
This function can be performed in R using a for loop. I spent some time trying to figure it out today, and thought I'd share for the benefit of the next person in my shoes:
for (row in 2:length(data$column)){ # 2 so you don't affect column names
    if(data$column[row] == "") {    # if its empty...
        data$column[row] = data$column[row-1] # ...replace with previous row's value
    }
}

This worked for me, although it took a long time (5-10 mins) to run with a huge data file. Perhaps there is a more efficient way of achieving this function, and I encourage anyone to say how that could be done.
Thanks and good luck.
Comment: `library(zoo)` `na.locf()` is faster I believe.
Comment: Not a question, so does it belong as one?
Answer: df <- data.frame(a = c(1:5, "", 3, "", "", "", 4), stringsAsFactors = FALSE)

> df
   a
1  1
2  2
3  3
4  4
5  5
6
7  3
8
9
10
11 4

while(length(ind <- which(df$a == "")) > 0){
  df$a[ind] <- df$a[ind -1]
}

> df
   a
1  1
2  2
3  3
4  4
5  5
6  5
7  3
8  3
9  3
10 3
11 4

EDIT: added time profile
set.seed(1)
N = 1e6
df <- data.frame(a = sample(c("",1,2),size=N,replace=TRUE),
                 stringsAsFactors = FALSE)

if(df$a[1] == "") {df$a[1] <- NA}

system.time(
  while(length(ind <- which(df$a == "")) > 0){
    df$a[ind] <- df$a[ind - 1]
  }, gcFirst = TRUE)

user  system elapsed
0.89    0.00    0.88

Comment: Your while loop is a truly beautiful solution in the way it takes advantage of R's vectorization.
Answer: Here  fast solution using na.locf from the zoo package applied within data.table. I created a new column y in the result to better visualize the effect of replacing missing values( easy to repalce x column here). Since na.locf replaced missing values , an extra step was needed to replace all zero length values by NA. The solution is very fast and takes less than half second in my machine for 1e6 rows.
library(data.table)
library(zoo)
N=1e6  ##  number of rows
DT <- data.table(x=sample(c("",1,2),size=N,replace=TRUE))
system.time(DT[!nzchar(x),x:=NA][,y:=na.locf(x)])
## user  system elapsed
## 0.59    0.30    1.78
# x y
# 1:  2 2
# 2: NA 2
# 3: NA 2
# 4:  1 1
# 5:  1 1
# ---
#   999996:  1 1
# 999997:  2 2
# 999998:  2 2
# 999999: NA 2
# 1000000: NA 2

Comment: A minor issue. If there are actual `NA` values in the data, this will replace them as well. As per `dt <- data.table(x=c(1,NA,2,"",""))` for instance.
Comment: @thelatemail good catch even if `NA` and `""` are in the same spirit of missing values! I wait for the user example and expected result before going further with this answer.
Answer: Borrowing agstudy's MWE:
library(dplyr)
library(zoo)

N = 1e6
df <- data.frame(x = sample(c(NA,"A","B"), size=N, replace=TRUE))

system.time(test <- df %>% dplyr::do(zoo::na.locf(.)))

   user  system elapsed
  0.082   0.000   0.130

Answer: just to provide a more recent update;
tidyr::fill() is faster than lightning
library(dplyr)
library(tidyr)

N = 1e6
df <- data.frame(x = sample(c(NA,"A","B"), size=N, replace=TRUE))

system.time(test <- df %>% tidyr::fill(x))

   user  system elapsed
   0.01    0.00    0.02


How to switch the position or exchange the content of two JComboBox?

Question: I am new to JAVA GUI and faced a problem. The following picture shows the part of GUI where my problem lies.

I want to achieve that when I click the "click to switch" button, the content of the comboBox will be exchanged. I tried different ways to either exchange the position of the two comboBox or exchange the content of the two ComboBox, but neither worked out.
Following is the part of my code related to this problem.
Class1:
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JPanel;

public class FilePathComboBox implements ActionListener {
    List<String> strings;
    BufferedReader input;
    JComboBox comboBox;
    JPanel jpFilePath;
    JButton testJB;

    public FilePathComboBox(String filePathOfSyncTool) {
        strings = new ArrayList<String>();
        FileReader fr;

        try {
            fr = new FileReader(filePathOfSyncTool);
        } catch (FileNotFoundException e1) {
            fr = null;
            e1.printStackTrace();
        }

        input = new BufferedReader(fr);
        try {
            String line = null;
            while ((line = input.readLine()) != null) {
                strings.add(line);
            }
        } catch (FileNotFoundException e) {
            System.err.println("Error, file " + filePathOfSyncTool +
            "didn't exist.");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        String[] lineArray = strings.toArray(new String[] {});

        comboBox = new JComboBox(lineArray);
        testJB = new JButton("click to add item");
        testJB.addActionListener(this);
        jpFilePath = new JPanel();
        jpFilePath.add(comboBox);
        jpFilePath.add(testJB);

    }

    public JComboBox getJComboBox(){
        return this.comboBox;
    }

    public void setJComboBox(JComboBox jcb){
        this.comboBox = jcb;
    }

    public JPanel getjpFilePath(){
        return jpFilePath;
    }

    @Override
    public void actionPerformed(ActionEvent arg0) {
        String s1 = "E:\\home\\joe\\foo";
        comboBox.insertItemAt(s1, 0);
        comboBox.setSelectedIndex(0);

    }
}

class2:
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JPanel;

public class SwitchComboBox implements ActionListener {
    JPanel switchOverall;
    JButton switchButton;
    FilePathComboBox fpcb;
    FilePathComboBox fpcb2;
    public SwitchComboBox(){
        fpcb = new FilePathComboBox("E:\\pathRecord.txt");
        fpcb2 = new FilePathComboBox("E:\\pathRecord2.txt");
        switchButton = new JButton("click to switch");
        switchOverall = new JPanel();
        switchButton.addActionListener(this);
        switchOverall.add(fpcb.getjpFilePath());
        switchOverall.add(fpcb2.getjpFilePath());
        switchOverall.add(switchButton);
    }

    public JPanel getSwitchOverall(){
        return this.switchOverall;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        //Here should be the code to switch the content
        //or position of the two comboBox
        Component[] stringArray = fpcb.getJComboBox().getComponents();
        Component[] stringArray2 = fpcb2.getJComboBox().getComponents();
        fpcb.setJComboBox(new JComboBox());
        for(int i =0; i < stringArray2.length; i++){
            fpcb.getJComboBox().add(stringArray2[i]);
        }
        fpcb2.setJComboBox(new JComboBox());
        for(int i =0; i < stringArray.length; i++){
            fpcb2.getJComboBox().add(stringArray[i]);
        }
    }
}

Hope someone can kindly help me with this. Thanks!
Comment: What do you mean by "contents will exchange"? Do you mean that the data held within the comboboxes will swap? If so, simply swap models.
Comment: @ Hovercraft Full Of Eels  Yes, I want the data held within the comboBoxes to be swapped. I am not very familiar with models. Could you give me more details about how to swap models?
Answer: Do you mean that the data held within the comboboxes will swap? If so, simply swap models:
ComboBoxModel model1 = fpcb.getJComboBox().getModel();
ComboBoxModel model2 = fpcb2.getJComboBox().getModel();

fpcb.getJComboBox().setModel(model2);
fpcb2.getJComboBox().setModel(model1);


Safari and Google Chrome orientation scale

Question: one of my friends create a web mobile and it shows me some problem when orientate mobile. It looks great but it shows me a problem when user change orientation. Website is http://www.tivag.ch/app. When page is loading it works fine in portrait mode, when i change in landscape mode also works perfect, but when i return back in portrait mode it shows me a problem it shows me a blank white space in right. When page is return in portrait mode document.width keeps the width of the landscape mode, it does not change the value. Scale doesn't work :)
Answer: Use overflow:hidden; for .content elememt.
.content {
width: 100%;
overflow:hidden; /*Important*/
height: auto;
float: left;
padding-bottom: 15px;
background: url(../img/bg_content.jpg) no-repeat center top;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}

As well as for further consistent results Add it to your head section. And don't use minimum-scale="1"
<meta name="viewport" content="initial-scale = 1,user-scalable=no,maximum-scale=1.0">


Sum a list of BigIntegers

Question: I've looked all over but can't figure this out. How do you sum a list of BigIntegers?
Using System.Numerics;
Using System.Linq;

List<BigInteger> bigInts = new List<BigInteger>();
BigInteger sum = bigInts.Sum();             // doesn't work
BigInteger sum = bigInts.Sum<BigInteger>(); // doesn't work
BigInteger sum = bigInts.Sum(x => x);       // doesn't work

Do you have to do this?
BigInteger sum = new BigInteger(0);
foreach(BigInteger bigint in bigInts)
    sum += bigint;

Answer: var sum = bigInts.Aggregate(BigInteger.Add);

Aggregate gets a delegate to a method which gets two BigIntegers and return a BigInteger. It uses a default BigInteger as initial value (0), and goes over each BigInteger, invoking BigInteger.Add with the previous result (0 would be previous result in the first time - also called 'seed') and the current element.
Comment: @jb. Friend request sent. Lets not spam SO with small talk. :)
Comment: Lol. Likewise! What question are you on now? ;P
Comment: The initial value is not really necessary when dealing with `Add`.
Comment: @leppie Thanks for the note. Fixed.
Comment: @jb. Very nice. Are you doing them by order?
Comment: @YoryeNathan: Your explanation is incorrect. There must be at least 1 value in the list. In that case, only that value is returned, else `Add` will be applied.
Answer: Aggregate function is more general version of Sum:
var bigInts = new List<System.Numerics.BigInteger>();
bigInts.Add(new System.Numerics.BigInteger(1));

var result = bigInts.Aggregate((currentSum, item)=> currentSum + item));

Comment: Or just `bigInts.Aggregate(BigInteger.Add)` :)
Comment: Alexei, This is exactly what I used as soon as you put your answer, I looked up how to use Aggregate. @leppie, could you add some explanation how your magic works?
Comment: @jb.: It is just a delegate, referencing the `BigInteger.Add` method.
Answer: You can also use the ForEach() method on generic lists to do the addition:
var bigInts = new List<BigInteger>();

BigInteger sum = 0;
bigInts.ForEach(x => sum += x);

Comment: I thought of this, but it still requires an extra BigInteger. And I'd have to do `.ToList()` if I'm in an `IEnumerable`. (Which I am, but forgot to mention)
Comment: Ah, well then, that makes a slight difference. (-:
Answer: As Alexei said Aggregate is the more general from of sum.
Presented below is an extension method.
public BigInteger static Sum(IEnumerable<BigInteger> this lst)
{
    return lst.Aggregate(BigInteger.Zero, (acc, next)=> acc.Add(next));
}

I haven't tested this, and my C# might be getting a little rusty.
but the idea should be sound:
see http://msdn.microsoft.com/en-us/library/bb549218.aspx#Y0
Comment: You might want to have a return type and return something.
Comment: @Oxinabox you know you're rusty when you can't even spell "C#" right. haha :)
Comment: Oh i see while i was typing this @Alexei Levenkov, updated his answer to incude an example.
great minds think alike
Comment: leppie, Ah yes. Too much using F# for me. forgot about those. Fixed now
Comment: Don't you have to do `this.Aggregate(...)` ?
Comment: @jb.: I fixed the syntax. `lst.Aggregate(BigInteger.Add)` will also work.
Comment: Apparently my C@ was rustier than i thought.

Sum a list of BigIntegers


If $\sin q\ne \cos q$ and $x,y,z$ satisfy the equations $x\cos p-y \sin p+z=\cos q+1$, $x\sin p+y\cos p+z=1-\sin q$, $x\cos(p+q)-y\sin(p+q)+z=2$

Question: If $\sin q\ne \cos q$ and $x,y,z$ satisfy the equations
$$
x\cos p-y \sin p+z=\cos q+1\\
x\sin p+y\cos p+z=1-\sin q\\
x\cos(p+q)-y\sin(p+q)+z=2
$$
then find the value of $x^2+y^2+z^2$

I multiplied the first equation by $\cos p$ and the second equation by $\sin p$ and added to get $x+z(\cos p+\sin p)=\cos p\cos q+\cos p+\sin p-\sin p\sin q$ and then I multiplied the first equation by $\sin p$ and the second equation by $\cos p$ and subtracted to get $y+z(\cos p-\sin p)=\cos p-\cos p\sin q-\sin p\cos q-\sin p$  Now i am stuck.I dont know how to solve further.
Answer: Your equations are linear in all variables, solve the first equation for $z$ and plug this in equation two and three, solve one of this equations for $y$ and you will get an equation only in $x$.
By this method i got
$$x={\frac { \left( -\cos \left( q \right) -\sin \left( q \right)
 \right) \sin \left( p+q \right) + \left( -\cos \left( q \right) +1
 \right) \cos \left( p \right) +\sin \left( p \right)  \left( \sin
 \left( q \right) +1 \right) }{ \left( \sin \left( p \right) -\cos
 \left( p \right)  \right) \sin \left( p+q \right) -1+ \left( \cos
 \left( p \right) +\sin \left( p \right)  \right) \cos \left( p+q
 \right) }}
$$
Answer: From the first two equations, put z on the right-hand side.
1. square and sum to get an expression for $x^2+y^2$ in terms of $q$ and $z$.
2. Combine the two to find another expression for $x\cos(p+q)-y\sin(p+q)$
Answer: Rather, multiply the first equation by $\cos q$ and the second by $-\sin q$ and add these scaled equations to obtain $$x\cos(p+q)-y\sin(p+q)+z(\cos q -\sin q)=\cos q -\sin q+1.$$ Since from the last of the original triple we know that $x\cos(p+q)-y\sin(p+q)=2-z,$ we can substitute in the above sum and letting $K=\cos q -\sin q,$ we obtain $$2-z+Kz=K+1,$$ which you may now substitute in any pair of the original system to eliminate $z,$ so that you now have a pair in $x$ and $y$ alone. I believe you can find the way from there.


How can I override or disable a parent theme's CSS file?

Question: I am trying to override the menu.css file in the default Classy theme through my library file. I have read through the documentation, but anything I tried doesn't work.
What would be the correct markup to override or disable this file?
Comment: Have you link to CLassy template?
Comment: I have a subtheme in which I have my own menu.css. This is a subtheme from Classy.
Answer: Add this to your theme's .info.yml to override it with css/my-menu.css from your theme:
libraries-override:
  classy/base:
    css:
      component:
        css/components/menu.css: css/my-menu.css

To disable it (don't load it when loading the classy/base library):
libraries-override:
  classy/base:
    css:
      component:
        css/components/menu.css: false

To get the classy/base key you need for the override, find the *.libraries.yml file where the CSS is declared. The part before the slash is the * in that file (e.g. classy.libraries.yml), and the part after is the top-level key in that file under which the CSS is declared.
In most cases I find it easiest to actually copy the library declaration from the libraries file that declares the asset to maintain the 'css', 'component', keys and indentation.
Note that you can do the same thing for JavaScript assets as well.
See https://www.drupal.org/node/2216195#override-extend for more information.
Comment: From that error it sounds like you're working in *.libraries.yml, only library definitions go in there. Overrides, extends, etc. happen in your theme's *.info.yml file.
Comment: Thanks, you were right. I couldn't find anything that would suggest it had to be placed inside the *.info.yml file. It works now so thank you for your answer. Will definitely be using this in future.
Comment: Thanks for the explanation. I now get where you get the key from. I tried both of them but they give me the same error:
>Incomplete library definition for definition 'libraries-override' in extension 'My-theme' in.
Any idea what could be the problem?
Comment: One way to maybe remember it is that both modules and themes can have *.libraries.yml but only themes can globally add libraries and manipulate libraries via their *.info.yml file. Themes have more power with respect to libraries :)
Comment: Ah yes, because you have to interact with an asset from a different theme(In this case a parent-theme), you have to touch It's library first. And you can't edit a library through a library. Makes sense.
Comment: Is there anyway to override a base theme setting in my child theme? Bootstrap has the following line `css/components/ajax-progress.module.css: false` in it's libraries-override in it's info.yml. But when I set this to true in my child theme. It doesn't load the css. Anyone have any solution?
Answer: just gonna drop this update here for anyone else landing on this answer: Apparently the names have changed, but this works for me on D9.2.0:
libraries-override:
  bartik/global-styling:
    css:
      component:
        css/components/menu.css: false
        css/classy/components/menu.css: false
  bartik/classy.base:
    css:
      component:
        css/classy/components/menu.css: false


SQL: Select Between Nth Occurrences of Same Character

Question: I have a string
"https://www.facebook.com/9876543219876/posts/123456789123456/"
and am looking for the following:
1. Select only 123456789123456 (between 5th and 6th occurrence of '/'
2. Select only 9876543219876 (between 3rd and 4th occurrence of '/'
I tried using combinations of right, charindex and reverse but I could not get the query to return between the multiple occurrence of the characters.
For example I tried
right("String",charindex('/',reverse("String"))- 1)
but could only get after the first occurrence from the right.
Thank you in advance!!
Comment: What RDBMS?  Please show your current attempts.
Comment: The Oracle INSTR function allows you to chose which occurrence of a string it returns
Answer: regex_substr is what you need.
select regexp_substr(<col>, '[^/]+', 1, 1) as val1,
       regexp_substr(<col>, '[^/]+', 1, 2) as val2,
       regexp_substr(<col>, '[^/]+', 1, 3) as val3,
       regexp_substr(<col>, '[^/]+', 1, 4) as val4,
       regexp_substr(<col>, '[^/]+', 1, 5) as val5
from
<your table>

Fiddle


Inequality: $\tan(x) > 1$

Question: So far, I've not come very... far. It ends up with me trying to solve it more intuitively than mathematically.
I figured, first I'll find the place of equality, which is at $x = \arctan 1 = \frac{\pi}{4} + \pi n$.
Then, it will be larger than 1 until either sin(x) or cos(x) changes sign, but I can't find a way to express this consistently over a larger interval.
Answer: The principal domain of $y = \tan x$ is $(-\pi/2,\pi/2)$. Since $\tan (\pi/4) = 1$ and $y = \tan x$ is increasing, the solution to $\tan x > 1$ in this interval is $(\pi/4,\pi/2)$.
Since the tangent function is periodic with period $\pi$, the solution set in a different period has the form $(\pi/4+k\pi,\pi/2+k\pi)$. Thus $$ \{x : \tan x > 1\} = \bigcup_{k \in \mathbb Z} \left( \frac{\pi}{4} + k\pi, \frac{\pi}{2} + k\pi \right).$$
Answer: Let us look in the interval $(-\pi/2,\pi/2)$, since $\tan$ is $\pi$-periodic. In this interval, if we want $\tan(x) > 1$, then
$$x \in (\pi/4,\pi/2)$$
Hence, the desired intervals are
$$n \pi + (\pi/4,\pi/2)$$
Answer: $\tan x$ is increasing in $[0,\pi/2)$ and principal solution of $\tan x>1$ is $[pi/4,pi/2)$ and we know the graph of $\tan x$ is repeated after every $\pi$ unit so final solution is $[n\pi+\pi/4,n\pi+\pi/2)$

Inequality: $\tan(x) > 1$


If a class overlay is too high for one to another, is it possible to do classification?

Question: This is a figure of PCA Map of several class data that i am trying to classify:

By looking at it, I wanted to be sure if this is not really applicable to be classified? (since it has a high overlap rate) or is there anyway I can do to somehow separate the class (so it minimize the class overlay) and make it more favorable to be classified?
PC Information:

Edit: Figure of ICA Map (alternatives)
Comment: What if you use multiple PCs in your model, not just two?
Comment: PCA for dimension reduction can harm the predictive power of your model. See: https://stats.stackexchange.com/questions/448200/is-pca-always-recommended/448203#448203
Comment: @Dave I have 8PCs in total for this.. I mapped the first two..
Comment: @Sycorax Thanks for this, so maybe try to use another dimension reduction tools instead of PCA?
Comment: Why use dimension reduction at all? What problem are you trying to solve, and how does dimension reduction help to solve it?
Comment: @Sycorax I am actually trying to visualize the data i am trying to classify. recently i directly build models like decision trees, bagged tree, random forest, but the prediction tends to overfit the result.. i wonder if these overlaps in dimension reduction has any relation to do with the overfitting
Answer: (This answer will set aside the issues related to PCA or other dimension-reduction techniques.)
It is possible that your classes simply are not separable on your features. For instance, if category $1$ has a bivariate distribution of $N\left(\begin{pmatrix}0\\0\end{pmatrix},\begin{pmatrix}1&0\\0&1\end{pmatrix}\right)$ and category $2$ has a distribution of $N\left(
\begin{pmatrix}0\\0\end{pmatrix},\begin{pmatrix}
1&0\\
0&2
\end{pmatrix}
\right)$, but the only feature you observe is the first one where both categories have standard normal distributions, then you cannot reliably distinguish between the classes. In more formal language, the posterior probability of either category, given an observation of that first feature, is equal to the prior probability of that category: $P(\text{category c}\vert\text{feature 1})=P(\text{category c})$.
In a more realistic scenario where the feature distributions of the two categories are not exactly the same, they might be different but only slightly. In such a scenario, there is slight ability to distinguish between the two classes but only slight.
If your classes have considerable overlap that precludes strong performance, yet you force a model to separate them by fitting to coincidences in the training data, then that absolutely could result in overfitting and having terrible out-of-sample performance. A picture on the Wikipedia article on overfitting shows this to some extent.

Imagine if the red and blue dots overlapped considerably. Yes, it would be possible to snake around and get most of the points on the correct side of some kind of decision boundary (you could get everything right if you drop the requirement for the decision boundary to be continuous), but that likely would have overfit to coincidences in the data rather than the real trend.


Using AddEncoding x-gzip .gz without actual files

Question: With Apache (2.2 and later) how can I achieve the following. I want to transparently compress using GZip encoding (not plain Deflate) the output when a certain file is queried with its name plus the extension .gz, where the .gz version doesn't physically exist on disk.
So let's say I have a file named /path/foo.bar and no file foo.bar.gz in the folder to which the URI /path maps, how can I get Apache to serve the contents of /path/foo.bar but with AddEncoding x-gzip ... applied to the (non-existing) file?
The rewrite part appears to be easy, but the problem is how to apply the encoding to a non-existent item. The other way around also seems to be simple as long as the client supports the encoding.
Is the only solution really a script that does this on the fly?

I'm aware of mod_deflate and mod_gzip and it is not what I'm looking for - at least not alone. In particular I need an actual GZIP file and not just a deflated stream.
Now I was thinking of using mod_ext_filter, but couldn't bridge the gap between rewriting the name of the (non-existent) file.gz to file on one side and the LocationMatch on the other. Here's what I have.
RewriteRule ^(.*?\.ext)\.gz$ $1 [L]
ExtFilterDefine gzip mode=output cmd="/bin/gzip"
<LocationMatch "/my-files/special-path/.*?\.ext\.gz">
    AddType application/octet-stream .ext.gz
    SetOutputFilter gzip
    Header set Content-Encoding gzip
</LocationMatch>

Note that the header for Content-Encoding isn't really needed by the clients in this case. They expect to see actual GZIP files, but I want to do this on-the-fly without caching (this is a test scenario).
Answer: Alright, sorry for answering my own answer so shortly after offering the bounty, but I finally found out how to accomplish what I want. My last edit to my question was close, but not close enough.
It turned out I could abuse the fact that mod_rewrite lets me set the MIME-type of a rewritten path (T=) in order to apply my filter (using mod_ext_filter) using the AddOutputFilterByType directive like this:
RewriteRule ^(.*?\.ext)\.gz$ $1 [L,T=application/my-file-type]
ExtFilterDefine gzip mode=output cmd="/bin/gzip"
<Location "/my-files">
    AddOutputFilterByType gzip application/my-file-type
</Location>

So this way the actual file (e.g. somename.ext.gz) does not exist, but somename.ext does exist and mod_rewrite takes care to apply the filter conditionally only when the request comes in with the .ext.gz extension, but never if the request comes in under the (existing) name.
All I did there was to invent my own MIME-type.

As 200_success suggested in his/her comment, I adjusted this once again to be more readable and relying on an environment variable (conditionally set through mod_rewrite):
RewriteRule ^(.*?\.ext)\.gz$ $1 [L,E=NEEDGZIP:1]
ExtFilterDefine gzip mode=output cmd="/bin/gzip" enableenv=NEEDGZIP
<Location "/my-files">
    SetOutputFilter gzip
</Location>

Comment: According to the documentation for ExtFilterDefine, you should be able to activate the filter using the environment variable, without using SetOutputFilter.  That was the point of setting the environment variable NEEDGZIP=1 in RewriteRule.
Comment: @200_success: you're right, forgot the `enableenv`, have this in my config, of course. So you mean the `Location` could also be left out? ... meaning that the `RewriteRule` should actually be narrow enough to not match on other stuff.
Comment: Instead of inventing a MIME type, it would be cleaner to have RewriteRule [E=GZIPFILTER:1] set an environment variable, to trigger ExtFilterDefine enable=GZIPFILTER .
Comment: @200_success: thanks, this worked fine. I amended my answer to reflect the change.
Answer: mod_gzip should be able to help you
http://sourceforge.net/projects/mod-gzip/
Here are some sample configs
http://schroepl.net/projekte/mod_gzip/config.htm
Comment: Thanks. I'm sorry, how does this apply to my case? Could you give me an example. Because from reading through the (second) page I take it that it still requires the `.gz` file to be stored in the same folder although internally. I'll start trying but would appreciate some clues which of the many directives you had in mind. Thanks again.


probability without replacement and unknown number in urn

Question: An urn contains N red chips, N blue chips, and N white chips all numbered 1 through N. Two chips are drawn at random and without replacement. Let A be the event that the two chips drawn are the same color; and let B be the event that they have the same number.
a) Find $P(A)$
b) Find $P(B)$
C) Find the probability that the two chips drawn are either the same color or the same number.
Here is what I have so far, but I am not sure as to whether or not it is correct.
ANSWER:
a) $P(A)= \binom{R}{2} + \binom{B}{2} \binom{W}{2}$
b) $P(B)= \frac{3}{R+B+W} \times \frac{2}{R+B+W-1}$
c) $P(\text{same color or same number})= P(A)+P(B)$
Any help that can be offered with a detailed explanation as to how I would be able to relate it to future problems would be amazing!
Comment: For the first question, you presumably do not believe the answer given is a probability. If we do it in your style, we get $\frac{\binom{N}{2}+\binom{N}{2}+\binom{N}{2}}{\binom{3N}{2}}$. Simplify. Or else whatever we get on the first draw, the probability the next one is a colour match is $\frac{N-1}{3N-1}$. This quick way only works because we have the same number of each colour.
Answer: For the first problem we now that there $\binom{N}{2}$ to choose a pair of red chips, also this holds for the the blue chips and white chips. Also there are $\binom{3N}{2}$ to ways to draw two chips, because there are $3N$ chips in the urn. So the probability is:
$$P(A) = \frac{3\binom{N}{2}}{\binom{3N}{2}} = \frac{\frac{3N(N-1)}{2}}{\frac{3N(3N-1)}{2}} = \frac{N-1}{3N-1}$$
For the second case there are 3 balls with same number at the beginning, while for the second draw there are 2 balls with the same number as the one we draw earlier. Note that the first draw doesn't matter, because we only need to draw the same numbered ball as the one we draw earlier. So the probability is:
$$P(B) = N \times \frac{3}{N+N+N} \times \frac{2}{N+N+N-1}$$
$$P(B) = \frac{2}{3N-1}$$
And for the third case we need to check when exactly one of the conditions is fulfiled, we are using the exclusive OR. So using inclusion-exclusion we have:
$$P(A \oplus B) = P(A) + P(B) - P(A \cup B)$$
But note that the event $A$ and event $B$ never intersect, because it's impossible to draw two balls from the same colour and with same number same number, so we have:
$$P(A \oplus B) = P(A) + P(B) - P(A \cup B)$$
$$P(A \oplus B) = \frac{N-1}{3N-1} + \frac{2}{3N - 1}$$
$$P(A \oplus B) = \frac{N+1}{3N-1}$$
Comment: Can you explain where the 3N(N-1) and the 3N(3N-1) is derived for P(A)?
Comment: It follows from the binomial coefficient. We have:

$$\binom{n}{k} = \frac{n!}{k!(n-k)!} = \frac{n(n-1)(n-2)...(n-k+1)}{k!}$$

So for this case where $k=2$ we have:

$$\frac{N!}{2!(N-2)!} = \frac{N(N-1)(N-2)!}{2!(N-2)!} = \frac{N(N-1)}{2}$$
Answer: Hint: For $P(A \cup B)$, use inclusion-exclusion principle, noting that if the two chosen chips have the same number and the same color then they are the same chip. So you will have $P(A \cup B) = P(A) + P(B) - P(A \cap B)$, where $P(A)$ is the probability they have the same number, $P(B)$ is the probability they have the same color, and $P(A \cap B)$ is the probability that the two chosen chips are the same.


What exactly is the value of a boost::scoped_ptr pointer?

Question: I am trying to understand the syntaxis of boost::scoped_ptr. Let's define and write to standard output a scoped_ptr pointer as well as the value it points at:
#include <boost/scoped_ptr.hpp>
#include <iostream>

int main()
{
  boost::scoped_ptr<int> p{new int{1}};

  std::cout << p.get() << '\n'; // ok
  std::cout << p << '\n';       // error

  std::cout << *p.get() << '\n'; // ok
  std::cout << *p << '\n';       // ok. *p==*p.get()
}

Question. Why is *p.get()==*p and yet std::cout << p << '\n'; won't compile?
I'm working on g++ -std=c++11 -O2 -Wall -pedantic.
Comment: Question 1 is like having: `int* p;` and asking why `p` isn't equal to `&p`. Why would the address of the pointer be equal to the address stored in it?
Comment: If you have C++11, prefer `std::unique_ptr` to `boost::scoped_ptr`.
Answer:
Why do &p and p.get() produce different results?

&p is the address of the scoped_ptr object. p.get() is the address of  the int object it points to.

Why is *p.get()==*p and yet std::cout << p << '\n'; won't compile?

The two are unrelated.
*p is defined to be the same as *p.get(): dereferencing a scoped pointer accesses the object it points to, and so does dereferencing a raw pointer to the same object.
cout << p doesn't compile because there's no overload of << for streaming scoped pointers.

I'm working on g++ -std=c++11 -O2 -Wall -pedantic

Then consider std::unique_ptr (introduced in C++11) rather than boost::scoped_ptr. It's more standard, and also movable.
Answer: scoped_ptr or any other "smart pointers" are something "pointer like objects" instead of real pointers.
These smart pointers are actually objects, of course &p, which obtains a pointer to this "smart pointer object", is different from p.get(), which is a method returns the pointer that the "smart pointer object" holds.
*p.get() is equivalent to *(p.get()), where p.get() returns the pointer that p holds, and *p is equivalent to "p.operator*()", which is an overloaded operator, also returns the pointer that p holds, that's why *p.get()==*p.
cout << p doesn't compile as there is no overloaded operator that outputs p to a stream.
Answer: scoped_ptr< T > is a template class mimicking a pointer. Instantiation of this class will create an object which has similar behaviors as pointers.

p.get returns the address of the associated value of type T*: so it returns the address returned by new int{1}, that is the value in its member which points to the associated pointer.
&p return the address of object p (that is, where p resides). p is a container which has a true pointer member which points on the address of the associated value of type T.
p cannot return anything good because scoped_ptr< T > has no cast operator to convert itself into T* by design choice. You must use get for this purpose. But it should give a bool-like answer in a conditional expression equivalent to p.get() != 0.
cout << p fails because there is no stream operators defined for scoped_ptr< T >.
*p exists because there is a defined unary operator* which gives the same result as *(p.get())