Can't connect components with mapDispatchToProps

Question: I have React Native project with Redux and I'm trying to connect the actions to the components.
I have App.js file without index.js file.
This is how I implement Redux:
App.js:
import React from 'react';
import { Platform, StatusBar, StyleSheet, View } from 'react-native';
import { Provider } from 'react-redux';

import store from './src/store/Store.js';
import AppNavigator from './src/navigation/AppNavigator';

export default function App(props) {
  return (
    <Provider store = { store }>
      <View style={styles.container}>
        {Platform.OS === 'ios' && <StatusBar barStyle="default" />}
        <AppNavigator />
      </View>
    </Provider>
  );
}

AppNavigator.js:
import React from 'react';
import { createAppContainer, createSwitchNavigator } from 'react-navigation';
import MainTabNavigator from './MainTabNavigator';

export default createAppContainer(
  createSwitchNavigator({
    Main: MainTabNavigator
  })
);

MainTabNavigator.js: (Only the relevant part)
import React from 'react'
import {connect} from 'react-redux';
import { createStackNavigator, createBottomTabNavigator } from 'react-navigation';
import {HomeScreen} from '../screens/HomeScreen';
import * as CounterActions from '../store/actions/CounterActions';

let HomePage = connect(state => mapStateToProps)(HomeScreen);

const HomeStack = createStackNavigator(
    {
        Home: HomePage,
    },
    config
);

const tabNavigator = createBottomTabNavigator({
  HomeStack,
  SettingsStack,
});

const mapStateToProps = (state) => {
    return {
        count: state.counter.count
    }
};

const mapDispatchToProps = {
    ...CounterActions
};

export default tabNavigator;

CounterActions.js:
export const increment = (number) => {
    return (dispatch) => {
        dispatch({ type: 'INCREMENT', number })
    }
};

export const decrement = (number) => {
    return (dispatch) => {
        dispatch({ type: 'DECREMENT', number })
    }
};

The following line in MainTabNavigator.js connects the state to props of the HomeScreen component:
let HomePage = connect(state => mapStateToProps)(HomeScreen);
HomeScreen.js:
import React from 'react';
import { Platform, StyleSheet, Text, View } from 'react-native';

export const HomeScreen = (props) => {
  alert(JSON.stringify(props));
  return (
    <View style={styles.container}>
      <Text>COUNT FROM STORE: {props.count}</Text>
    </View>
  );
};

HomeScreen components gets the state correctly and render 'count', but How do I connect the actions?
I want HomeScreen to dispatch like this:
props.increment(1);

Thanks!
Answer: The mapDispatchToProps is the second argument of the connect function from the react-redux.
I also think that you pass wrong the first argument to the connect.
Try this:
let HomePage = connect(mapStateToProps, mapDispatchToProps)(HomeScreen);

Comment: Thank you for the answer! I've already tried this but it doesn't work...
Comment: And what was the problem? `props.increment` was undefined? Was there any error in console?
Answer: Finally solved it by the following way:
MainTabNavigator.js:
import React from 'react'
import {connect} from 'react-redux';
import { createStackNavigator, createBottomTabNavigator } from 'react-navigation';
import {HomeScreen} from '../screens/HomeScreen';
import {increment, decrement} from '../store/actions/CounterActions';

let HomePage = connect(state => mapStateToProps, dispatch => mapDispatchToProps(dispatch))(HomeScreen);

const HomeStack = createStackNavigator(
    {
        Home: HomePage,
    },
    config
);

const tabNavigator = createBottomTabNavigator({
  HomeStack,
  SettingsStack,
});

const mapStateToProps = (state) => {
    return {
        count: state.counter.count
    }
};

const mapDispatchToProps = (dispatch) => {
    return {
        increment: (number) => dispatch(increment(number)),
        decrement: (number) => dispatch(decrement(number))
    }
};

export default tabNavigator;

Comment: As I stated in my answer above, you are adding another functions which are not necessary. This is enough `let HomePage = connect(mapStateToProps, mapDispatchToProps)(HomeScreen);`. Moreover `mapStateToProps` can take multiple arguments, so when you will need it in future and do it your way, you will need to add these arguments also to your function which is first argument of `connect` in your implementation. If it is not working the way I suggest, the problem is somewhere else, not here.
Answer: Follow along, we will make some modifications to your files:
First lets modify your MainTabNavigator.js since you only posted the relevant part, make sure to implement this for the rest as well.
import React from 'react'
import { createStackNavigator, createBottomTabNavigator } from 'react-navigation';
import {HomeScreen} from '../screens/HomeScreen';

let HomePage = connect(state => mapStateToProps)(HomeScreen); // <===== Remove this

const HomeStack = createStackNavigator(
    {
        Home: HomePage, // <===== Make this HomeScreen instead of HomePage
    },
    config
);

const tabNavigator = createBottomTabNavigator({
  HomeStack,
  SettingsStack,
});

const mapStateToProps = (state) => {
    return {
        count: state.counter.count
    }
};

const mapDispatchToProps = {
    ...CounterActions
};

export default tabNavigator;

What we want is to have the mapping of state and props on the Home Screen itself (or any other screen)
Now lets move on to your HomeScreen.js:
import React from 'react';
import { connect } from 'react-redux';
import { Platform, StyleSheet, Text, View } from 'react-native';

import { increment, decrement } from '../store/actions/CounterActions';  // <===== import your actions here, preferably like this

/** add the following: */

const mapStateToProps = (state, ownProps) => ({
    // ... computed data from state and optionally ownProps
});

const mapDispatchToProps = {
    // ... normally is an object full of action creators
    increment,    // <===== Map your dispatch here to props
    decrement     // <===== Mapping the second dispatch
};

const HomeScreen = (props) => {
  alert(JSON.stringify(props));
  return (
    <View style={styles.container}>
      <Text>COUNT FROM STORE: {props.count}</Text>
    </View>
  );
};

/** Export your component like this */

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(HomeScreen)

Now anywhere on your HomeScreen.js you can call this.props.increment(yourNumber) or this.props.decrement(yourNumber) and you should be good to go
Hope this Helps!
Comment: I did that but it still not working. I can't export default `HomeScreen` with the `connect`. Thanks a lot anyway!!
Comment: You are most welcome. but just for clarification, once you follow this you dont need to `export default HomeScreen` anymore instead you export the connect. look at the edited answer


How can I order by date?

Question: I have a problem with a query (mysql).
I have to order by date ASC tha problem is that I also have empty date in the table. Mysql set them to 0000-00-00, so when I order by date those dates are shown first, but i need to put the "empty dates" at the end, how can I do?
Example:
0000-00-00
2011-01-01
2010-12-12

Query: .... ORDER BY date ASC
Results should be:
2010-12-12
2011-01-01
0000-00-00

Thanks
Answer: ORDER BY IF(date = '0000-00-00', 1, 0) ASC, date ASC

Comment: @Marco Yep, real dates first, so shouldn't real dates be 0 when order by asc? :) think again?
Comment: @SalmanA: yes, correct, my fault. +1 for xdazz!! Maybe sleeping a little more helps me ;)
Answer: Assuming you're doing:
SELECT *
FROM table
ORDER BY date ASC

you could do
SELECT *, IF(date > 0, 1, 0) AS has_date
FROM table
ORDER BY has_date ASC, date ASC

I believe that would do it for you.

How can I order by date?


How to print a view in node.tpl.php only if it's not empty

Question: Views can be printed in tpl.php files with this code:
<?php print views_embed_view('myview','block_1'); ?>

However, if that view is empty, the view block code will be printed anyway:

Is it possible to check if the view has any results first and then print it if it does? E. g.:
<?php if ($view_myview,block_1): ?>
<?php print views_embed_view('myview','block_1'); ?>
<?php endif; ?>

Answer: You can check it using the below code
<?php
$viewName = 'myview';
$displayid = 'block_1';

$view = views_get_view($viewName,$displayid);
$view->execute();
$reviewCount = count($view->result); //It will return number of results
if($reviewCount>0){
print views_embed_view($viewName,$displayid);
}
?>

Hope it will help.
Comment: It works, thank you. What about performance - does this `count` slow down the query a lot?
Comment: Not that much. But its fine as long as it is working because it is the easiest way to do it.


Finding interior angle of two lines and describing its relationship with distance

Question: Our team has been on this question for a good few days, but unfortunately, we are far from being mathematicians and need a little guidance! We are trying to find $\phi$ using two points and two angles drawn in the picture. For extra brownie points,  explain what relationship the distance $l$ and $\phi$ have in common.

This question is a small (but important) obstacle in our way of optimizing a search method we need for our project. Therefore any information to the solution will be greatly appreciated!
Comment: If you know $\theta_1$ and $\theta_2$ then $\phi= \theta_1-\theta_2$.
Answer: Call the points $A$ and $B$, and the third point $C$ --- the one you're looking for. Let $v$ and $w$ be unit vectors in the direction from $A$ to $C$ and from $B$ to $C$ respectively, i.e.,
$$
v = (\sin \theta_1, \cos \theta_1)\\
w = (\sin \theta_2, \cos \theta_2)
$$
Then we have
$$
C = A + tv \\
C = B + sw
$$
for some numbers $t$ and $s$, hence
$$
A + tv = B + sw
$$
Taking a dot product with the vector $v' = (-\cos \theta_1, \sin \theta_1)$, which is $v$ rotated 90 degrees counterclockwise, we get
$$
A\cdot v' + t v \cdot v' = B\cdot v' + s w \cdot v'
$$
Since $v \cdot v' = 0$, we get
$$
\frac{(A-B) \cdot v'}{w \cdot v'} = s
$$
and from this, you can determine $C$.
..and now I realize that all you wanted was $\phi$, which is $\theta_1 - \theta_2$, as @EmilioNovati observed in the comments. But since you'll probably want to work out some more details as well, I'm keeping what follows:
Unwinding all that,
\begin{align}
C
&= B + sw \\
&= (x_2, y_2) + \frac{(A-B) \cdot v'}{w \cdot v'} w\\
&= (x_2, y_2) + \frac{(x_1 - x_2, y_1 - y_2) \cdot (-\cos \theta_1, \sin \theta_1)}{w \cdot v'} w\\
&= (x_2, y_2) + \frac{(-\cos \theta_1)(x_1 - x_2) + (\sin \theta_1)( y_1 - y_2)}{w \cdot v'} w\\
&= (x_2, y_2) + \frac{(-\cos \theta_1)(x_1 - x_2) + (\sin \theta_1)( y_1 - y_2)}{(\sin \theta_2)(-\cos \theta_1) + (\cos \theta_2)(\sin \theta_1)} w\\
&= (x_2, y_2) + \frac{(-\cos \theta_1)(x_1 - x_2) + (\sin \theta_1)( y_1 - y_2)}{(\sin \theta_2)(-\cos \theta_1) + (\cos \theta_2)(\sin \theta_1)}  (\sin \theta_2, \cos \theta_2)\\
&= (x_2, y_2) + \frac{(-\cos \theta_1)(x_1 - x_2) + (\sin \theta_1)( y_1 - y_2)}{\sin (\theta_1 - \theta_2)}  (\sin \theta_2, \cos \theta_2)
\end{align}
The relationship between $\phi$ and $\ell$ is that if $\theta_1$ and $\theta_2$ are held constant, and so is the direction from $A$ to $B$ (i.e., the direction of the dotted line), then $\phi$ remains constant even though $\ell$ changes. I'm not sure if this is what you meant, but it's the only relation I can think of.
Comment: THANK YOU! The explanation was clear and really helped. You went above and beyond.


Sets and ordinals - homework questions

Question: I have two questions which I don't even know how to start. I would like you to give some hints. I know it would be better that I show some work, but I really don't know where to begin...
The question goes like that:

Find whether the sets are isomorphic and whether the order types are equal.

$\omega\cdot{\omega}$ and $\omega+\omega$ where $\omega$ is the first infinite ordinal.
$q+1+q$ and $q\cdot{q}$ where q is the order type of $(\mathbb{Q},\leq)$.

Please help, thank you!
Answer: HINTS:

Note that there is just one limit ordinal smaller than $\omega+\omega$.
Only one of these orders is dense. Two countable dense orders with the same endpoints are isomorphic. (Thank you bof for the correction.)
Comment: @Galc127: I mean the same configuration of existence of minimum and maximum. Dense just means that between two points there is a third.
Comment: D'oh, it's strange how immediately I see this after a sleepless night, whereas 10 hours ago I was relatively fresh as a morning dew. I'll fix this soon.
Comment: Thanks, Asaf, your hint for 1 is helpful, I still don't know how to answer two - What is the meaning of "dense with same endpoints"?
Comment: That make sense. Thank you for your helpful answers.
Comment: @AsafKaragila how can we approach this without mentioning that it's dense. (Because our professor said we won't cover dense).
Comment: @GinKin: I don't think that I know any reasonable isomorphisms between the two sets; once you know that all dense countable sets without endpoints are isomorphic there's little point in working any harder. It's not hard to show that the first one is isomorphic to $\Bbb Q$ (by mapping the first $q$ to the negative rationals; the $1$ to $0$ and the second $q$ to the positive rationals). But I can't think of anything simple enough for the second one.
Comment: Isn't mapping $(a,b)\in\mathbb Q\times\mathbb Q \to \frac ab\in \mathbb Q$ a good enough function ?
Comment: @GinKin: It's not injective, nor it is order preserving.

Sets and ordinals - homework questions


Probability that a player is dealt aces once in the next five deals ? Does it matter if they have aces now?

Question: Someone asked me this today and I am stumped . A player has been dealt aces of any suit combination in a 2 card holdem hand. He/She is holding Aces in their hand. What are the chances the player will be dealt aces of any combination in the immediate next five deals. Cards are being randomly shuffled after each deal.
Comment: Not following.  if the cards are put back in the deck, which is then properly shuffled, then past hands have nothing to do with the probabilities going forward.  Is that what you are asking?
Comment: Are you keeping those two aces and getting 5 new cards on top of them dealt to you to make a hand of 7 cards?
Answer: The chance of getting two aces on a given hand is $\frac 4{52} \cdot \frac 3{51}=\frac 1{221}=p$ and the chance of not getting aces on a given hand is $1-p$.  The chance you don't get two aces on any of the next five hands is then $(1-p)^5$ and the chance you get them at least once is $1-(1-p)^5$.  How can this hand affect any of the next five if the deck is shuffled?
Comment: I realize that if the deck is shuffled that  each is an independent event. If I am following  the answers  correctly this makes this problem more straightforward ? You  should decrease or multiply the probability of a single occurrence by the power of (# of recurrences) after the first one  ?
Comment: Yes.  If you have independent events, the probability that something happens in each of them is multiplied.  The probability of flipping $n$ heads in a row is $\frac 1{2^n}$
Answer: Prior hand does not effect next 5
Chance of AA is 4 / 52 * 3 / 51 = 1/221
Any of the next 5 is same as 1 - none of the next 5 = 1 - (1 - 1/221) ^ 5 = 2.242%  = 1 / 44
Exactly 1 in the next 5 I don't know how to do that


Why has $p(\lambda)$ exactly one positive zero?

Question: Let $p(\lambda ) = {a_m}{\lambda ^m} + {a_{m - 1}}{\lambda ^{m - 1}} +  \cdots  + {a_1}\lambda  - {a_0}$ and ${a_0} > 0,{a_1},{a_2}, \ldots ,{a_m} \ge 0$, and at least one of the coefficients ${a_1},{a_2}, \ldots ,{a_m}$ positive.
Why has $p(\lambda)$ exactly one positive zero?
Answer: $p^{'} (\lambda )$ for $\lambda>0$ is positive since you've lost the $a_0$. It's value at $\lambda=0$ is $-a_0$ which is negative. It can only go up from there.
Answer: Equation
$$p(\lambda ) = {a_m}{\lambda ^m} + {a_{m - 1}}{\lambda ^{m - 1}} +  \cdots  + {a_1}\lambda  - {a_0}=0$$
can be considered as the equation verified by the abscissas of the intersection points of
$$\begin{cases}y&=&f(\lambda)\\
y&=&a_0\end{cases} \ \ \text{with} \ \ f(\lambda):={a_m}{\lambda ^m} + {a_{m - 1}}{\lambda ^{m - 1}} +  \cdots  + {a_1}\lambda$$
The first equation is that of a curve passing through the origin $f(0)=0$ and such that $lim_{\lambda \rightarrow \infty}(f(\lambda))=+\infty$. This curve intersects necessarily at least once the horizontal line with equation $y=a_0$.


How to resolve notice : Undefined offset: 3 in user_node_load()

Question: I have moved my entire site and got this when I want to add content:
Notice: Undefined offset: 3 in user_node_load() (line 3604 of /storage/content/39/170239/<mysite>.se/public_html/modules/user/user.module).

Can it have to do with the fact that I have different users now on my site and that some nodes is connected to users that may not exists?
If that is the case, can I resolve this by editing my DB?
Answer: I'd guess you might be right. I think I have a different version of the user module from you (different line numbers), but user_node_load() adds stuff back in from the users table.
If you are missing a user with uid 3, you will get this error.
You probably need to update all of the nodes authored by user 3 to another user, the following SQL should do the trick (replace {new_user_uid} by the uid of the user you want to move the nodes to):
UPDATE node SET uid = {new_user_uid} WHERE uid = 3;


The obstruction cochain is zero iff a map has an extension.

Question: On page 142 of this book, we define

Definition. Fix $n\geq 1$. A connected space $X$ is said to be $n$-simple if $\pi_1(X)$ is Abelian and acts on the homotopy groups $\pi_q(X)$ for $q\leq n$.

Definition. Let $(X,A)$ be a relative CW complex with relative skeleta $X^n$ and let $Y$ be an $n$-simple space. Given a continuous map $f:X^n\rightarrow Y$, we define the obstruction cocycle $c_f\in C^{n+1}(X,A;\pi_n(Y))$ to be $c_f(j)=[f\circ j]$ for an attaching map $j:S^n\rightarrow X^n$ of each $(n+1)$-cell of $(X,A)$.

Here we use the notation:

For a relative CW complex $(X,A)$, let $C_n(X, A)$ denote the free group generated by the set of all attaching maps of relative $n$-cells of $(X,A)$. Then the cellular chain complex $C_*(X,A)$ gives the cellular cochain with coefficients in an Abelian group $\pi$ as $C^*(X,A;\pi)=Hom(C_*(X,A),\pi)$. Moreover, we may then define the cellular cohomology groups to be $H^*(X,A;\pi)=H^*(C^*(X,A;\pi))$.

My question. I try to prove the statement:

Theorem. The restriction of $f$ to $X^{n-1}$ extends to a map $X^{n+1}\rightarrow Y$ if and only if $[c_f]=0$ in $H^{n+1}(X,A;\pi_n(Y))$.

In this proof on page 142, it says that it is clear that $f$ extends to $X^{n+1}$ if and only if $c_f=0$. But I cannot think so. In addition, I cannot find where he applies the hypothesis concerning $Y$.
Moreover, in the last theorem on page 142, I have a similar question as this.
Could you give me advice? Thanks in advance.
Comment: You might want to proofread your post more carefully. For instance, the very first definition looks like it might be missing some words, because $\pi_1(X)$ **always** acts on $\pi_q(X)$, for all $X$ and all $q$.
Answer: For the very first part, assume for simplicity that $X^{n+1}=X^{n} \cup e^{n+1}$, and that $A=\emptyset$. To handle the case where there are more cells, you can argue by formally extending linearly in $C_{n+1}(X)$ which is freely generated by the (n+1) cells in $X$. For the case where $A \neq \emptyset$ you make everything relative.
Let $\varphi:S^{n} \to X^{n}$ be the attaching map for $e^{n+1}$. Then $f$ induces a homomorphism $C_{n+1} \to \pi_n(Y)$ by sending $e^{n+1}$ to $f \circ \varphi$.(**) The result is that this term is zero if and only if $f \circ \varphi$ is nullhomotopic. Then you conclude by noting that a map $S^n \to Y$ is nullhomotopic if and only if it has an extension to a disk, i.e: the cell $e^{n+1}$.
(**) The hypothesis involving $Y$ is used to ensure that the action of $\pi_1$ is trivial on all homotopy groups. This is used to force the relation that $[S^n,Y]=[S^n,Y]_*=\pi_n(Y)$.Without this, there is an ambiguity about basepoints. Basically for this to be a homomorphism actually landing in $\pi_n(Y)$ we need to choose a path from $f(x_0)$ to $y_0$ etc. but all of this is unambiguous when $Y$ is simple.
You may circumvent this issue by using local coefficients, i.e: passing to the universal cover of $Y$ and using the fact that $\pi_n(Y)=\pi_n(\tilde{Y})$, but now instead this is a $\mathbb Z[\pi_1(X)]$-module via $f$.
Comment: This proof is actually pretty tricky and usually glossed over. Let me know if you need more details :). I LOVE obstruction theory and I'm happy to see other people reading about it
Comment: Thank you for your answer.


PROBLEMA DE INSTALAÇÃO WAMPSERVER

Question:
Olá, estou querendo instalar o wampserver, porém sempre aparece este erro. Alguém conhece? Podem me ajudar?
Comment: Aperta em < Back e mostre a tela em que você digitou o bendito caminho.
Answer: No caso, é por que você está instalando uma extensão do Wamp, no caso do MariaDB, (pode verificar no titulo do Form aberto). https://stackoverflow.com/questions/40580223/error-when-installing-wampserver, o mesmo erro, porém o usuário estava instalando a extensão do PHP. Baixe a partir desse site: http://www.wampserver.com/en/, na parte de baixo da página, tem o botão de download.
Comment: Embora este link possa responder à pergunta, é melhor incluir as partes essenciais da resposta aqui e fornecer o link para referência.  As respostas apenas por link podem ser invalidadas se a página com o link for alterada. - [Da Revisão](/review/low-quality-posts/173914)
Comment: Ah, obrigado pela dica!

PROBLEMA DE INSTALAÇÃO WAMPSERVER


all $A_i$ are connected sets such that $\bigcap\limits_{i\in E} A_i \neq \emptyset$ then $\bigcup\limits_{i \in E} A_i$ is connected

Question: This is my proof

Suppose not.
Then, $\cup A_i$ has an open partition $\{U,V\}$
$U \subseteq \cup A_i$ so we only need to show two cases:

$U \subseteq \cup A_j$ with $U \neq \cup A_j$ for some $J \subseteq E$. Then there exists some $A_k$ such that $U \neq A_k$ with $U \cap A_k \neq \emptyset$. Thus $\{ U \cap A_k,V \cap A_k \}$ is an open partition of $A_k$. By assumption, $A_k$ is connected. It's a contradiction with [$\cup A_i$ is disconnected]

$U= \cup A_t$ for some $T \subseteq E$. Since $V \neq \emptyset$, there exists some $A_k$ such that $(A_k-U) \neq \emptyset$. Let $J=T \cup \{k\}$. Then by Case 1, It's a contradiction with [$\cup A_i$ is disconnected]

Is it okay??
I'm not sure about this...
Answer: There are several things that I don't understand in your proof. In particular:

$U \neq \bigcup_j A_j$ : on what set is the union performed?

Same things for case 2. with $T$.

I would just say as $$\bigcap_{j \in J} A_j$$ is supposed to be non empty, let's take $x \in \bigcap_{j \in J} A_j$.
As by hypothesis $$\bigcup_{j \in J} A_j \subseteq U \cap V,$$ we can suppose without loss of generality than $x \in U$ (we can swap the role of $U,V$ in the other case).
Now for any $j \in J$, $A_j$ is supposed to be connected and $x \in A_j$. Therefore $A_ j \subseteq U$ and finally $$\bigcup_{j \in J} A_j \subseteq U$$ proving that the union is connected.


Cached plugin issue while working with load balancer

Question: I have a grails application with enabled grails cache and  zipped resource plugin. We have multiple deployments of the war behind a load balancer.
When try to access the application there seems some of the images are missing. This is our problem.
When we tried to access the image directly pointing to the servers with out load balancer one server contains the image and other one doesn't contains . why this happens?
I think All the images are not created in the work folder while startup of the server. I saw that there is files count are different in two server image work folders that was defined using the  grails.resources.work.dir.
Answer: We had a similar problem w/ images using Grails 2.1, Tomcat 7, and F5 load balancer.  It was because sessions were not being correctly managed between the multiple grails app deployments.  This caused 302 redirects of images (from /images to /static) to fail because they were split between two different servers.  We were able to solve the problem by enabling sticky-sessions / session affinity in the load balancer to ensure all requests go to the same server once a session is established.  Not sure if you are experiencing the same issue, but it might be worth a try?


Factoring $(a+b)(a+c)(b+c)=(a+b+c)(ab+bc+ca)-abc$

Question: How to prove the following equality?

$$(a+b)(a+c)(b+c)=(a+b+c)(ab+bc+ca)-abc$$

I did it
$$\begin{aligned}
a^2b + a^2c + ab^2 + cb^2 + bc^2 + ac^2 + 2abc &=a^2(b + c) + bc(b + c) + a(b^2 + c^2 +2bc)\\&=a^2(b + c) + bc(b+ c) +a(b + c)^2\\&=(b + c)(a^2 + bc + ab + ac)\\&=(b + c)\left[a(a + b) + c(a + b)\right]\\&=(a + b)(b + c)(c + a)
\end{aligned}$$
I just wanted to see some different way to work out with it.
Comment: An interesting question! In mathematics it is, IMO, very interesting how to speed up tedious verifications of identities. The downvote may come from someone who does not consider this a valuable question, but I do, honestly.
Answer: Set $\displaystyle a+b+c=x$
So, we have $\displaystyle (x-a)(x-b)(x-c)=x^3-x^2(a+b+c)+(ab+bc+ca)x-abc$
Now, $\displaystyle  x^3-x^2(a+b+c)=x^2(x-\overline{a+b+c})=x^2\cdot0$


How to estimate the number of samples needed for NLP corpus?

Question: What are approaches to estimate how many samples are needed for an SVM classification task in features extracted from text?
If I have for example a set of 8 labels in a 100-dimensional featurespace. How many samples do I need to build a reasonable classifier?
Answer: There is no such formula which gives you an exact number of required samples.
However you can incrementally verify whether adding more training data will be likely to yield better results.
Using learning curves you plot subsets of your training data (in increasing sizes) against the crossvalidation score (training score is usually included as well, but i am referring to the crossvalidation here). What i am referring to as score here, can be any evaluation metric, for example accuracy.
With a sufficient number of documents you will see that the slope your crossvalidation score curve will decline until you see only little improvements.
In the end it comes down to a cost-benefit considerations (assuming the training data limit has not been reached yet). For example for the left curve (Naive bayes, left one) here a cost-efficient amount of documents to use would be around n = 500.
For more information see: learning_curve in scikit-learn


Cannot upload file through HTML form

Question: I am planning to make a form which has a form through which users can upload a file on the website.
I used a CSS template where a class called pop-up-wrapper and pop up is defined. However, when I use the following code :

                <form id="form-submit" method="post" enctype="multipart/form-data">

Upload file

                        <input  type="file" name="resume" id="user-resume">

                        <input type="submit" name="submit" value="Submit" id="form-submit" class="mar">

                </form>

I have a PHP code which validates if any file has been entered by checking with
isset($_FILES['file']

but this always returns 0.
Is there anything in the CSS stylesheet which can lead to this situation where $_FILES is unable to catch the uploaded file?
TIA
Answer: You have to use the name in $_FILES, not the type.
isset($_FILES['resume'])

Comment: You just beat me! Nice one!
Answer: Just a shot here, but I don't think it's your CSS that's causing the problem. Try:
isset($_FILES['resume'])

instead.

Cannot upload file through HTML form


JQuery Show() all properties

Question: By default if you specify a speed jQuery adds a weird looking animation where it expands from the left end corner. I want it to just slide down. Is there a way to do that without importing something else like jQuery UI?
Comment: Can you share some code with us to see what you are currently doing? An easy solution to me sounds like using the `slideDown()` function...
Comment: $(document).ready(function(){
      $('.next').click(function (event) {
         $divId=event.target.id;
         $('#div-'+$divId).hide(700,'swing');
         $('#div-'+$divId).next().show(1000,'swing');
      });
      $('.back').click(function (event) {
         $divId=event.target.id;
         $('#div-'+$divId).hide(700,'swing');
         $('#div-'+$divId).prev().show(1000,'swing');

      });
Comment: You should edit your post and add it there properly.
Answer: <code> $( "#yourId" ).slideDown( "slow", function() {
    // Animation complete.
 });
</code>
Or
<code>$( "#yourId" ).slideDown( "slow" );
</code>
Or even just
<code>$( "#yourId" ).slideDown();
</code>
Look at
http://api.jquery.com/slidedown/
Comment: This is the correct answer.  JSFiddle showing example: https://jsfiddle.net/93dac06c/

JQuery Show() all properties


TemplateSyntaxError: Could not parse the remainder

Question: I'm receiving this error each time I try to access a list within a Django template. I have checked the answers to similar questions, but the problem is usually a lack of % or some other character somewhere. As long as I can see, this is not the case:
Here I'm passing a dict containing a a list of item id as keys and list of URLs to images as a value for each id. I know I should integrate this into the item model, but since I'm still at development with SQLite3 I cannot store lists easily. And anyway I am intrigued by this problem. So:

Exception Value:
Could not parse the remainder: '['item.id'][0]' from 'img_gallery['item.id'][0]'

Also, yesterday I tried using bootstrap4 flex-grid to easily achieve 5 columns. Since I'm using pagination to retrieve 20 items, my idea was slicing the list of items (model) for each row, like:
{% for item in items[0:5] %}

And I also received the same error, even when this was the recommended aproach in related answers aboput slicing data passed with a view.
In both cases I cannot find the problem, and I think both are somehow related.
I'm using latest Django 1.11.6 with Python 3.5.2.
Comment: jinja2 != django templates; the two are related but Django does not use Jinja, the latter was originally inspired by the Django template syntax but is a separate project altogether.
Comment: You shouldn't add `get_item` to your `INSTALLED_APPS`. The `templatetags` directory is in your `shop` app, which is presumably already in `INSTALLED_APPS`.
Comment: @MartijnPieters Nice to know, I always thought it was 100% jinja2. Is that the source of the error? Is that wrong syntax for Django-templates?
Comment: Yes, see my answer below.
Answer: You seem to be confused between Jinja2 syntax and the Django template syntax. Jinja2 is a separate project, inspired by Django, but not used by Django itself.
In the Django template syntax, variables in {{...}} always use dot notation, [...] subscriptions are not supported. Out of the box, the language does not support dictionary key lookups.
You can write a custom filter to achieve this, like the following, written by culebrón:
from django.template.defaulttags import register

@register.filter
def get_item(dictionary, key):
    return dictionary.get(key)

then in the template:
{{ img_gallery|get_item:item.id|first }}

Alternatively, you could switch to using Jinja2 in your Django project, replacing the built-in template language: How to use jinja2 as a templating engine in Django 1.8
Comment: I'm following the instructions in https://docs.djangoproject.com/en/1.11/howto/custom-template-tags/ but I'm still getting the error "No module named 'get_item'". I have updated the question to provide more data
Comment: @RomanRdgz: from the accept I presume you have managed to resolve it? It looked to me like you had a `__init__.py` spelling mistake. At any rate, it'd be a new question, the issue with the syntax is resolved.
Comment: @RomanRdgz: ah, I see the comment on the question; all you needed was to load the module in the template and be *part* of an already-registered app.


Conditional Convergence Property

Question: How would one prove or disprove (provide a counterexample) the statement
$$\text{If}\ \sum a_n\ \text{converges conditionally, then }\sum n^2 a_n\ \text{diverges}. $$
Answer: Hint: if $\sum n^2 a_n$ converges,  its terms are bounded.

Conditional Convergence Property


Unknown drupal_view() function although Twig Tweak is installed

Question: Acquia BLT won't let me commit some Twig.
> tests:twig:lint:all
Validating twig syntax for all custom modules and themes...
Iterating over fileset files.twig...
  ERROR  in ~/repos/agency/client-site/docroot/themes/custom/client_theme/templates/taxonomy/taxonomy-term--faq.html.twig (line 35)
      33       {{ title_suffix }}
      34

  >>  35         {{ drupal_view('faqs_per_term', 'block_1', term.id) }}
  >> Unknown "drupal_view" function.
      36

      37

 [WARNING] 28 Twig files have valid syntax and 1 contain errors.

I have installed and enabled Twig Tweak module, and rebuilt cache.
Do you know of any reason why BLT might not know the module is installed?
Possibly relevant: I'm running Drupal and BLT under Lando. The error is triggered after git push but I get the same result if I call lando blt tests:twig:lint:all directly.
Comment: Does this answer your question? https://github.com/acquia/blt/issues/2815
Comment: Works like a charm! If you make an answer out of it, I'll be glad to accept it.
Answer: If a module defines new twig filters or functions, they need to be manually excluded from the blt linter. Per a comment in the BLT issue queue, you can make these exclusions in blt.yml like:
validate:
  twig:
    functions:
      - drupal_block
      - drupal_field
      - drupal_view
      - drupal_region
      - drupal_entity
      - drupal_field
      - drupal_menu
      - drupal_form
      - drupal_image
      - drupal_token
      - drupal_config
      - drupal_title
      - drupal_url
      - drupal_link
      - drupal_messages
      - drupal_breadcrumb

This is also documented in the Overriding variables at runtime section of the blt docs (it's near the bottom of the section, under the tests: list item).


Probability based on proportions from paired samples

Question: Consider a dataset of partial pressure of oxygen (po2, in kPa) measured in paired arterial and venous blood samples from a population (n = 38251).
The distributions of both type of blood are displayed below.
Now consider the blood of a subject X whose type (arterial or venous) is unknown, and for which the po2 is measured at 2 kPa.
Question: knowing the proportions of arterial and venous po2 <2 kPa of respectively 31.56% and 1.53% in the population, is it right to say that there is 20.6 (=31.56%/1.53%) times more chance that the blood of subject X is of arterial origin than of venous origin?
Thanks for your comments.
Answer: That would be the case if all you knew was that the pO2 was less than 2 kPa. But you know more than that: you know that the pO2 was precisely 2 kPa, at least within measurement error.
One caution: the displayed values for "arterial" blood are very low, lower than those for "venous" blood. That originally confused the physiologist in me, who expects higher arterial than venous pO2. Normal arterial pO2 values are on the order of 10-13 kPa (75 - 97.5 mm Hg, in units typically used in the US) for people living near sea level. Even at the highest terrestrial altitudes, normal arterial pO2 doesn't fall as low as 2 kPa (15 mm Hg). The OP says in a comment that the "arterial" samples are really from umbilical cord blood, so I'll call them "cord blood" below despite the label on the plot.
Look at the samples in the dataset that showed a pO2 of 2 kPa. It looks like about 4100 were cord blood and 500 were venous blood, or 4600 total. Of those 4600 samples with values of 2 kPa, 89% were cord and 11% were venous.
That would be odds of about 8/1 that the new sample is cord blood, other things being equal. That estimate, however, depends on the new blood sample being drawn from a member of the same population that provided these histograms.
Comment: Thanks EdM! You're right (expect that "It looks like about 4100 were arterial blood and 500 were venous blood" and not the other way around). Thus, given your example, we can claim that there is 8.09 (=89%/11%) more chance that the blood of subject X is arterial than venous, right? Is a two-proportions z-test (e.g. prop.test R function) statistically appropriate to objectify such a case? A very clever comment about pO2 levels; in fact, these pO2 values were supposed to be from umbilical cord blood, I just wanted to simplify the example...


ARMv7 Assembly, how could I improve on this pseudorandom number generator?

Question: I have this pseudorandom function that's based off the time since unix epotch as a seed, I need to get 4 numbers between 1-5, currently what I have this doing is getting a single digit at a time and printing it. This was originally for numbers between 0-9 and changing it to be 1-5 I realized that the numbers 6-9 will always result in being a 5, meaning that 5 has a higher overall probability of occuring than any other number.
This is just for a simple guessing game so it's not doing anything cirtical
timeofday:

    MOV r7, #78         @gettimeofday returns time
    LDR r0, =time       @address of holder for time_t
    MOV r1, #0          @timezone not needed
    SWI #0

    LDR r0, =time       @set r0 back to label addr
    LDRB r1, [r0, #4]   @load epotch value from r0 into r1

    MOV PC, LR          @back to calling location, Then it will branch to the function below.

fakemod:
    CMP r1, #10         @Ensuring we don't create a negative
    SUBGE r1, r1, #10   @decrease r1 by 10 until it's a single digit
    CMP r1, #10
    BGE fakemod         @if the number in r1 is still greater than 10 loop

singledigit:            @Need a value between 1-5
    CMP r1, #5          @Checks in r1 has a value larger than 5
    SUBGT r1, r1, #1    @subtracts if r1 is a integer greater than 5
    CMP r1, #5          @compares if the number is greater than 5 still
    BGT singledigit     @if greater than 5 go back to loop start.

    CMP r1, #0       @needs to be between 1-5, so if it's 0, just add 1
    ADDEQ r1, r1, #1

    MOV PC, LR          @once it's an integer between 1-5, go back to call location.

I rather than continuously subtract 1 from a value greater than 5 and add 1 to a value of 0 I tried the following and just got "garbage" as the output:
timeofday and fakemod loop are the same.

CMP r1, #5
BGT timeofday

CMP r1, #0
BEQ timeofday

Answer: I changed the fakemod function to be the following and got the results I ideally wanted. Adding 1 to 0 isn't ideal in a random number generator but it's sufficient enough of a "hack" for my needs. Wrote this a few weeks ago so I forgot the purpose a bit.
fakemod:
    CMP r1, #5       @Ensuring we don't create a negative
    SUBGT r1, r1, #5 @decrease r1 by 5 until it's a single digit
    CMP r1, #5
    BGT fakemod         @if the number in r1 is still greater than 10 loop

    CMP r1, #0
    ADDEQ r1, r1, #1

    MOV PC, LR          @once it's an integer less than 5, go to top.


WQL/SCCM - Comparing version numbers correctly (less than...)

Question: I'm having a problem with this part of a SCCM WQL query looking for "less than version 75.0.3770.80":
... where SMS_G_System_ADD_REMOVE_PROGRAMS.Version < "75.0.3770.80"

If i'm not mistaken this is the good old problem seen before in other scenarios (file names for example) where it will return objects with version number :
75.0.3770.142

Because in it's logic "of course" .142 is "less than" .80 because .1 is less than .8. It doesn't treat it as "142 versus 80" but "1 versus 8"
Is there any way I can work around this? I'm getting a lot of false positives with this query and need to filter them out. If it was straight Powershell I could cast it as [version] but in SCCM, is it at all possible to do this comparison?
Answer: If only the last part of the version number is different, we could use the following one.
... where SMS_G_System_ADD_REMOVE_PROGRAMS.Version like "75.0.3770.[1-7][0-9]"
or ... like "75.0.3770.[0-9]"

Best Regards,
Ray
Comment: Ah, good tip with the brackets! However here it's needed to get all versions less than "75.0.3770.80", this wouldn't work
Answer: Ended up using SMS_G_System_ADD_REMOVE_PROGRAMS.Version < "75.0.3770"
Answer: This goes wrongs if the first version nr reach 100.
Better something like this
SMS_G_System_ADD_REMOVE_PROGRAMS.Version like "75.0.%" and
SMS_G_System_ADD_REMOVE_PROGRAMS.Version < "75.0.3770


ClipRRect Border has sharp edge instead of circular

Question: ClipRRect(
                    borderRadius: BorderRadius.circular(25),
                    child: ImageSlideshow(
...

I'm using the ImageSlideShow package and trying to make it have circular edges, but as in this screenshot, the circular border has a sharp edge instead of getting curved evenly, why is that and how do I perfect it?

Answer: Instead of  borderRadius: BorderRadius.circular(25), you might want to go like this.
borderRadius: BorderRadius.all(Radius.circular(25)),

this should solve the problem.
Comment: This will not make a difference. The [`BorderRadius.circular`](https://api.flutter.dev/flutter/painting/BorderRadius/BorderRadius.circular.html) is shorthand for the `BorderRadius.all(Radius.circular(..))` constructor.
Comment: Make sure to make the image fit to the size of your ```ImageSlideshow```


Use NSPredicate to check if entity already contains a value when inserting data

Question: I need to store a large number of json feeds into Core Data. There are so many feeds, that I can't call them all at once, because it takes too long for the app to load. So I call the most important ones when the app launches, and divide the rest of them throughout the app. However, I also need the store these into Core Data.
The first view is just a tableview, with names in them. When you click on a name, you're sent to the next view, where there are supposed to be some text and a few pictures. So when the second view loads, I send a request to a webservice and store the answer for the service in Core Data.
What happens is that if you click the same tableviewcell twice, the info from the service called will be written to Core Data twice, creating duplicates values. I want to avoid this.
What I want to do is check if my entity already contains one of the unique values. If it does, don't store in Core Data. If not, store it.
Here's my method:
-(void)addImage:(NSManagedObjectContext *)context withImageUrl:(NSString *)imageUrl{
NSFetchedResultsController *fetchedResultsController = [self fetchObjectsFromEntity:@"Image" withContext:context andSortKey:@"imageUrl"];

[fetchedResultsController.fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"imageUrl contains[cd] %@" , imageUrl]];

if (//WHAT TO PUT HERE?) {
    NSLog(@"Doesn't exist");
    Image *image = [NSEntityDescription insertNewObjectForEntityForName:@"Image" inManagedObjectContext:context];
    image.imageUrl = imageUrl;
}else{
    NSLog(@"Already exists");
}

-(NSFetchedResultsController *)fetchObjectsFromEntity:(NSString *)entityName withContext:(NSManagedObjectContext *)context andSortKey:(NSString *)key{
NSError *error;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:context];
[fetchRequest setEntity:entity];

if (key != nil) {

    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]initWithKey:key ascending:YES];
    NSArray *sortDescs = [[NSArray alloc]initWithObjects:sortDescriptor, nil];
    [fetchRequest setSortDescriptors:sortDescs];
}

NSFetchedResultsController *fetchedResultController = [[NSFetchedResultsController alloc]initWithFetchRequest:fetchRequest managedObjectContext:context sectionNameKeyPath:nil cacheName:@"Root"];

if (![fetchedResultController performFetch:&error]) {
    NSLog(@"Error: %@" , error);
}

    return fetchedResultController;
}

Does anyone have an idea of how I can achieve this? Is the predicate wrong? How do I check if the predicate is true or not?
Any help would be appreciated!
Answer: What you're doing is going to be very expensive. You have to remember that each time you execute an NSFetchRequest you're going to execute SQL (expensive) and do I/O (also expensive). Your goal is to limit to number of times you do that.
If you can get a list of (say 10) unique keys (in your case the imageURL) and then execute the fetch request to see which ones of those imageURLs are already in the store, that will be a lot cheaper (a factor of roughly 10 in this case).
Also, since you're not interested in the actual objects, but just whether they exist, you should set the fetch request's resultType to NSDictionaryResultType and set propertiesToFetch to an array containing just your keym i.e. [NSArray arrayWithObject:@"imageUrl"].
Finally, comparing strings is very expensive. Try not to use @"imageUrl contains[cd] %@". It required the database to do a lot of work. If you have some numeric key, e.g. a 64 bit number, that will makes things a lot faster, since you can use numeric comparison.
Putting all of this together, let's assume your unique keys attribute is called uniqueID. You can run a fetch request like this
- (NSArray *)keysMissingInStoreFromKeys:(NSArray *)someKeys;
{
    NSFetchRequest *r = [NSFetchRequest fetchRequestWithEntityName:@"Image"];
    [r setResultType:NSDictionaryResultType];
    [r setPropertiesToFetch:[NSArray arrayWithObject:@"uniqueID"];
    NSPredicate *p = [NSPredicate predicateWithFormat:@"uniqueID IN %@", someKeys];
    [r setPredicate:p];
    NSError *error = nil;
    NSArray *result = [moc executeFetchRequest:r error:&error];
    NSAssert(result != nil, @"Fetch failed: %@", error);
    NSMutableArray *missingKeys = [someKeys mutableCopy];
    for (NSDictionary *values in result) {
        id uniqueID = [values objectForKey:@"uniqueID"];
        [missingKeys removeObject:uniqueID];
    }
    return missingKeys;
}

Hope this helps.


Screen shot of container has black background instead of white

Question: I have a small java program with the purpose of taking a screen shot of a specific component with the same program.
Here is an MCVE of it
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

@SuppressWarnings("serial")
public class Screen {

    public static void main(String[] args) {
        Frame frame = new Frame("Screen Test!");
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent we) {
                frame.dispose();
             }
         });

        Container container = new Container() {

            @Override
            public void paint(Graphics g) {
                super.paint(g);
                g.setColor(Color.RED);
                g.fillRect(5, 5, 10, 10);
            }
        };

        Dimension dimension = new Dimension(50, 50);
        container.setPreferredSize(dimension);

        frame.add(container);
        frame.pack();
        frame.setVisible(true);

        BufferedImage bufImage = new BufferedImage(dimension.width, dimension.height, BufferedImage.TYPE_INT_RGB);
        container.paint(bufImage.createGraphics());

        File outputfile = new File("image.jpg");
        try {
            ImageIO.write(bufImage, "jpg", outputfile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

When the code is run it produces this file.

However, I was expected an output file which looked like this.

Have I done something wrong or missed a step?
Answer: I think you could try:
frame.setBackground(Color.WHITE);

Before adding your container
Don't forget to import the color
import java.awt.Color;

I think this is because there is no background defined, and windows fills it automatically with a white color, but there is actually no background color, causing it to be black in the screenshot.
Edit:
My bad, you need to add the backgroundColor to the Graphics you use to draw the container to the Image.
try this:
Graphics2D graphs = bufImage.createGraphics();
graphs.setBackground(Color.WHITE);
graphs.clearRect(0, 0, dimension.width, dimension.height);
container.paint(graphs);

the method clearRect is used to actually paint the background with the color you defined.
Comment: I tried setting a background of white on both the container and the frame and it made no difference. Also I did import `java.awt.Color`
Comment: @Dan see my edit, you need to add the background to the graphics you use to draw the image, not to the frame. Hope this helps.


migrating from one framework to another in python

Question: I'm having trouble deciding which python framework to use for my website. So I've decided to bite the bullet and use Django. My question is how easy (or difficult) will it be to migrate to a different framework in future if I have issues with Django ?
Comment: That depends on the other framework.
Comment: Well, I assume it would be one of the popular ones like pylons or TurboGears.
Answer: Your database queries(and object models), url config, and templates to say the least will all be specific to django. That said - if you understand what you're doing, recreating them in another package shouldn't take too long if you really need to at some later time.
edit: this is all assuming you dont integrate third party projects such as sqlalchemy and mako. Django plays nice with the builtins it ships with so it's often more trouble than its worth to use said modules.
Comment: So as I understand it, what you're basically saying is that if I put some thought into how I code, the third party objects I use etc etc, I can do the migration relatively easily.
Comment: Basically yes, if you have an understanding of how the orm is working then it should be simple enough to recreate your models in sqlalchemy later. The templating libraries are all similar, just different syntax for the same few operations (looping, conditionals etc). Sqlalchemy from django's orm will be the biggest change if you try to adjust to a new framework however if you wrap it in elixir ( http://elixir.ematia.de/trac/ ), even that won't be a huge hurdle. And of course when you say "migration", I think "rewriting templates and urlconfs to do the same thing but in a different package."
Answer: For the template part, Jinja is pretty similar to Django, but stand-alone. It might help you to migrate your templates to another framework.
(Or use it right away, I've found Jinja similar but quite superior to Django's default template system.)


Multi Git Repo's with same files

Question: First of all, there is a good chance my brain is just fried and am not thinking clearly... I am not even sure how to explain this properly :(
My Repo Setup
I have two repositories, Framework, and Client1.
The first one has all the files, including some that will be modified in the Client repo. These are just considered placeholders, or example files.
The second repository, Client1, contains added files that don't belong to Framework, as well as modifying some of the files from the Framework repo.
The Client1 repo starts off by pulling the Framework repo in, then I add/edit files to fit the clients website. When the Framework repo files are changed, I merge them into the Client1 repo.
This will end up causing conflicts. There is a chance there could be many conflicts.
Can I git pull and accept only my files for the conflicts, in one command? Just to make things faster.
Or is there anyway to do this better?
EDIT: We have changed our framework so core files are not touched by the client. They instead put files in another folder if they need to override the framework file.
For example:
The client needs to modify the Contact page controller which is located in /framework/application/controller/contact/index.php.
The client creates a file in /application/controller/contact/index.php to override the one in framework.
We have also start to use Git-Flow.
Comment: This doesn't sound like a job for Git; it sounds like you have chosen a poor architecture for your framework. Your client, which consumes your framework, shouldn't modify the framework's files in any way. Those files should be identical across all programs built on your framework. It's impossible to comment without knowing the language you're using, but generally your framework should be bundled up in some kind of library which gets included in your client application, and *never* modified by the client.
Comment: The alternative would be an architecture in which you use and extend the core classes provided by the framework without modifying its source. It's not an issue of version control. RE your example of config.php: Typically the framework would provide something like a `config.php.example` that would provide configuration keys, but not values. You'd copy this to `config.php` in each client, and version-control *that* file.
Comment: You want to pull and merge from the `Framework` repository and do what exactly? Which set of files do you want to unconditionally merge on top of the other ones? The whole point of merge conflicts is that there are changes on both sides that git cannot merge without intervention. If you drop the changes on either side you lose one line of work entirely
Comment: @meager The language I am using is PHP. I understand that the Framework files should not be touched by Client but because of circumstances I have not described this is what we would "like". Perhaps you are right though, I shouldn't be using Git. I'll do research on an alternative.
Comment: @EtanReisner A `config.php` file for example. It contains PHP constants, paths to certain directories, database authentication, and so on.
Comment: @Draven That doesn't answer the question. You can absolutely tell git to use the files (unmerged) from either side of the merge if you want to drop the entirety of changes from the other side (see the `ours` and `theirs` merge strategies). But I don't see how (in cases other than perhaps `config.php` that would generally ever be what you want, and even with `config.php` I'm not sure I see it). I also don't know that git can do that on a per-file basis automatically.
Answer: From what I can understand based on what you have said, your framework repo is essentially a template you pull into your dev repo which you actively use for development. The issue you have is when you make changes to your framework, and you want to apply those changes to your active dev environment(Client1) that you have already built on and maybe even modified the framework you pulled in before.
I could not tell you of a specific command to ensure no conflicts, but I would like to pass on a bit of knowledge on ways this may be made better.
Firstly, I think that this framework should be something that more or less stays the same, you shouldn't technically be modifying it in your client very often, that being said, I think you may be re-inventing the wheel in some areas. In truth, frameworks already exist to do just what you want, and that appears to be generating a ready to go dev environment that you can modify and redeploy without worrying about conflicts and disasters.
There is a tool I have only recently started to study, but I know enough to say I think it will answer your needs very well. That tool is Vagrant, Vagrant is a tool centered around easily configuring and setting up a dev environment with all the plugins and structure you want, and most importantly, one of its merits is the ease in changing that structure (or "Framework") and simply running a command that will destroy and redeploy your environment. The best part, the dev environment is all set up in a config file, that can be reused anywhere. Pretty nice!
Additionally, take a look at Grunt, Grunt is a tool that allows you to setup tasks and handle manual processes in your dev environment. (It does lots of stuff including js minification and linting, less compilation, running console commands), you can configure tasks and chain them together however you like to create a nice efficient workflow, definitely worth checking out.
Finally, take a look at a git principle known as git flow, it is essentially a sort of paradigm that is meant to give you a solid, professional repository structure and deployment process. It may be overkill for your needs, but one of the biggest things it promotes is the use of a dev, test and production environment. Here is a great link that outlines it well, I could go into depth on these subjects, but the tools I have mentioned have great docs and explain things far better than I can.
It is worth it to spend a lot of time setting up a good environment to tailor to your needs, it may seem like a waste, I know for me I like to jump in and start getting my hands dirty, but a well built and managed environment will save you LOTS of time in the long run.
Anyway, good luck!

Multi Git Repo's with same files


C# inheritance and interfaces confusion

Question: I am trying to use fakes for EF 4.1 DataContext to test the repository without testing the database ( due to a deployment issue)
I am doing something like this
public interface IEmployeeContext
{
    IDbSet<Department> Departments { get; }
    IDbSet<Employee> Employees { get; }
    int SaveChanges();
}

public class EmployeeContext : DbContext, IEmployeeContext
{
    public IDbSet<Department> Departments { get; set; }
    public IDbSet<Employee> Employees { get; set; }
}

public class FakeEmployeeContext : IEmployeeContext
{
    public IDbSet<Department> Departments { get; set; }
    public IDbSet<Employee> Employees { get; set; }
    public FakeEmployeeContext ()
    {
        Departments = new FakeDbSet<Department>();
        Employees = new FakeDbSet<Employee>();
    }
}

which works great most of the time but my problem is that sometimes in my code i use things like :
context.Entry(department).State  = EntityState.Modified;

and it complains that
'IEmployeeContext' does not contain a definition for 'Entry'
I cannot seem to comprehend what i need to change in the pattern to allow me access to the context.Entry and context.Database sections
Comment: Can you show the code for the declaration of `context`?
Comment: Is this a casting related problem? `IEmployeeContext` does not define a `Entry` attribute/function but instead its defined in the `DbContext` class. `((IEmployeeContext)context).Entry(department).State ..` might solve your problem.
Comment: Seems like you want your FakeEmployeeContext to also inherit from DbContext, since EmployeeContext does
Comment: The Declaration of EmployeeContext is the second class...
Comment: Casting as IEmployeeContext wouldnt help its already resolving to that .. and Casting to EmployeeContext would defeat the purpose of a n interface
Comment: public class FakeEmployeeContext : DbContext, IEmployeeContext still gives me the error because the enviroment cannot knwo that all classes that Inherit from IEmployeeContext also  Inherit from DbContext
Answer: The reason you're getting that specific error is because IEmployeeContext doesn't contain a method called Entry.
Entry is a member of DbContext.
Comment: If i make an Entry method part of the IEmployeeContext then I need to impliment it in in both EmployeeContext and FakeEmployeeContext and it is already implimented in EmployeeContext
Comment: Right, that method is coming from `DbContext`. A possible solution is to make your fake class inherit `DbContext`, although I haven't done enough with EF to be able to tell you if that will be of any use to you or not.
Comment: Just did some digging on this, and worst case, you can hide the `Entry` method from DbContext for the purposes of your fake employee context. It should, I believe, look like: `public new DbEntityEntry Entry(TEntity entity) where TEntity: class {}`

C# inheritance and interfaces confusion


SVM and non-linear predictive models - feature selection

Question: Just throwing out a general question. What do people think of applying feature selection methods when using SVMs to build predictive models? I understand that SVM have built in regularization with how they're trained, but I've heard for certain cases (e.g. features >> examples) feature selection is still useful. I'm mainly talking about non-linear SVMs (e.g. kernelized).
Is there a difference in effectiveness of feature selection when say # features >> # examples vs. # features ~ # examples vs. # features << examples?
If you don't think feature selection is useful, please explain why. If you think feature seleciton is useful (and have practical experience in this regard), please let us know what methods you've used and how they worked.
Also open to entirely different approaches to non-linear predictive modeling other than SVMs.
Thanks!
Answer: I'd say that it is generally a bad idea to use feature selection for non-linear support vector machines.  The reason for using a maximal margin classifier is that it is an approximate implementation of a theoretical performance bound that is independent of the dimensionality of the feature space in which it is constructed.  This means that over-fitting can be controlled via structural risk minimisation by carefully selecting the regularisation parameter, $C$.  HOWEVER, and it is a rather big "however", this bit of computational learning theory only applies to the construction of the maximal margin classifier in a feature space induced by a fixed kernel.  Any attempt to tune the kernel function, e.g. by adapting the kernel parameters, or via feature selection will invalidate the bounds on performance and in doing so potentially circumvent the structural risk minimisation principle.
The other reason why it is generally a bad idea is that feature selection is difficult.  If you perform feature selection by minimising some statistic computed on a finite sample of data, it is all too easy to over-fit the selection criterion, and end up with a worse model that you started with.  This is especially true where there are many degrees of freedom in the optimisation problem (e.g. one binary parameter for the inclusion of each feature).  The use of regularisation instead gives one (continuous) degree of freedom, which makes over-fitting more difficult.
I have been performing some experiments for feature selection for non-linear kernel machines, and the basic message is that in general efforts at feature selection will result in lower generalisation performance.  It helps on some datasets (sometimes it helps a lot), but usually it makes things worse (sometimes much worse).
Answer: The whole point of deploying a non-linear kernel is to increase the dimensionality of the space, hoping that in the high dimensional space, there would be a linear solution to the problem.
If you have lot of features, hopefully, they will offer some little extra information that can be used to build a better model. Doing feature selection, i.e. killing original features, and then deploying non-linear kernel, i.e. creating artificial features by combinations of the leftovers, is... strange.
Not sure about your problem but in practice it may help if the features you filter out are not offering any extra information to the solution, e.g. may happen if they are so correlated that indeed all useful information exists in remaining features. In practice feature selection may help by reducing the training time required (probably far easier and practical to go for linear kernel).
PS. and as I was writing this I realised how old is this question :)


Solve system of equations: $7^{\log_3\sqrt{x}}-3^{\log_{81}y}=4 \land 7^{\log_3x}-3^{\log_9y}=40$

Question: $$7^{\log_3\sqrt{x}}-3^{\log_{81}y}=4  \land 7^{\log_3x}-3^{\log_9y}=40$$
I cant finish any of the two equations. On the first I get to this part $7^{\frac{1}{2}\log_3x}-3^{\frac{1}{4}\log_3y}=4$ and in the second I get something similar like in this one. What do I do next?
Answer: Hint: write $$7^{\frac{\ln(x)}{2\ln(3)}}-3^{\frac{\ln(y)}{4\ln(3)}}=4$$ and $$7^{\frac{\ln(x)}{\ln(3)}}-3^{\frac{\ln(y)}{2\ln(3)}}=40$$
And then you Can write$$A^{1/2}+B^{1/4}=4$$
$$A-B^{1/2}=40$$
And then we get
$$A=16+B^{1/2}-8B^{1/4}$$
and $$A=40+B^{1/2}$$
Comment: I am not yet familar with the ln logarithms. We haven't got to that yet.
Answer: Let $A=7^{\frac12\log_3 x}$, and let $B=3^{\log_{81}y}=3^{\frac12\log_9 y}$
Then your two equations become: $$A-B=4$$ and $$A^2-B^2=40$$
Does that help?
By the way, $B$ simlifies to $B=y^{1/4}$.


Why does resolveBinding() return null even though I setResolveBindings(true) on my ASTParser?

Question: I am writing an Eclipse plug-in that uses JDT AST's ASTParser to parse a method.  I am looking within that method for the creation of a particular type of object.
When I find a ClassInstanceCreation, I call getType() on it to see what type is being instantiated.  I want to be sure that the fully-resolved type being dealt with there is the one I think it is, so I tell the resultant Type object to resolveBinding().  I get null back even though there are no compilation errors and even though I called setResolveBindings(true) on my ASTParser.  I gave my ASTParser (via setSource()) the ICompilationUnit that contains my method, so the parser has access to the entire workspace context.
final IMethod method = ...;
final ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setResolveBindings(true);
parser.setSource(method.getCompilationUnit());
parser.setSourceRange(method.getSourceRange().getOffset(), method.getSourceRange().getLength());
parser.setKind(ASTParser.K_CLASS_BODY_DECLARATIONS);
final TypeDeclaration astRoot = (TypeDeclaration) parser.createAST(null);
final ClassInstanceCreation classInstanceCreation = walkAstAndFindMyExpression(astRoot);
final Type instantiatedType = classInstanceCreation.getType();
System.out.println("BINDING: " + instantiatedType.resolveBinding());

Why does resolveBinding() return null?  How can I get the binding information?
Answer: Tucked away at the bottom of the overview of ASTParser.setKind(), carefully hidden from people troubleshooting resolveBinding() and setResolveBindings(), is the statement

Binding information is only computed when kind is K_COMPILATION_UNIT.

(from the online Javadoc)
I don't understand offhand why this would be the case, but it does seem to point pretty clearly at what needs to be different!
Comment: Just a late comment on *"why this would be the case"*: if you parse anything smaller than a compilation unit then you have no import statements, and hence binding resolution is likely to fail.
Comment: I have a similar case where the kind is K_COMPILATION_UNIT but still resolveBinding() returns null. Any idea why?


Como inserir dados no mysql via ajax + php + foundation 5

Question: Queria saber como posso inserir dados no MySQL via Ajax + PHP utilizando o Framework Zurb Foundation 5? A propriedade "data-reveal-ajax" do framework já substitui uma função Ajax de inserção?
Answer: O data-reveal-ajax funciona simplesmente para abrir um modal com conteúdo de uma url ou uma pagina que faz alguma requisição ele por si só não é capaz de fazer requisições Ajax.
Comment: Minha intenção é justamente inserir dados no mysql através do modal do Foundation 5. Então seria o caso criar uma função ajax?
Comment: Com toda certeza meu caro, crie a função.


A Class of Diophantine Equations in Three Variables

Question: This question is inspired by the problem https://projecteuler.net/problem=748
Consider the Diophantine equation
$$\frac{1}{x^2}+\frac{1}{y^2}=\frac{k}{z^2}$$
$k$ is a squarefree number. $A_k(n)$ is the number of solutions of the equation such that $1 \leq x+y+z \leq n$, $x \leq y$ and $\gcd(x,y,z)=1$. This equation has infinite solutions for $k=1$ and $k>1$ that can be expressed as sum of two perfect squares.
Let $$A_k=\lim_{n \to \infty}\frac{A_k(n)}{\sqrt{n}}$$
\begin{array}{|c|c|c|c|c|}
\hline
k& A_k\left(10^{12}\right)& A_k\left(10^{14}\right)& A_k\left(10^{16}\right)& A_k\left(10^{18}\right)& A_k \\ \hline
1& 127803& 1277995& 12779996& 127799963& 0.12779996...\\ \hline
2& 103698& 1037011& 10369954& 103699534& 0.1036995...\\ \hline
5& 129104& 1291096& 12911049& 129110713& 0.129110...\\ \hline
10& 90010& 900113& 9000661& 90006202& 0.0900062...\\ \hline
13& 103886& 1038829& 10388560& 103885465& 0.103885...\\ \hline
17& 86751& 867550& 8675250& 86752373& 0.086752...\\ \hline
\end{array}
From these data, it seems that these limits converge. I wonder if it is possible to write them in terms of known constants or some sort of infinite series. For Pythagorean triples, there are about $\frac{n}{2\pi}$ triples with hypotenuse $\leq n$.
The Python code to calculate $A_1(n)$:
def gcd(a, b):
   if b == 0:
       return a
   return gcd(b, a % b)

N = 10 ** 14

cnt = 0
for a in range(1, 22000):
   a2 = a * a
   for b in range(1, a):
       if (a + b) % 2 == 1 and gcd(a, b) == 1:
           b2 = b * b
           x = 2 * a * b * (a2 + b2)
           y = a2 * a2 - b2 * b2
           z = 2 * a * b * (a2 - b2)
           if x + y + z > N:
               continue
           cnt += 1
print(cnt)

The Python code to calculate $A_2(n)$:
def gcd(a, b):
   if b == 0:
       return a
   return gcd(b, a % b)

N = 10 ** 14

cnt = 1     # (1, 1, 1)
for a in range(1, 22000):
   a2 = a * a
   a4 = a2 * a2
   for b in range(1, a):
       if gcd(a, b) == 1:
           b2 = b * b
           b4 = b2 * b2
           x = 2 * a * b * (a2 + b2) - (a4 - b4)
           y = 2 * a * b * (a2 + b2) + (a4 - b4)
           z = 6 * a2 * b2 - (a4 + b4)
           if x > 0 and y > 0 and z > 0 and x + y + z <= N and gcd(x, gcd(y, z)) == 1:
               cnt += 1
           x = (a4 - b4) - 2 * a * b * (a2 + b2)
           y = 2 * a * b * (a2 + b2) + (a4 - b4)
           z = (a4 + b4) - 6 * a2 * b2
           if x > 0 and y > 0 and z > 0 and x + y + z <= N and gcd(x, gcd(y, z)) == 1:
               cnt += 1
print(cnt)

Comment: Do you know how to get the solution of the problem 748 (in the link you provided)?
Answer: This is a partial answer. Consider the case $k=1$. The parametric solutions are given by $(x,y,z)=\left(2ab(a^2+b^2),a^4-b^4,2ab(a^2-b^2)\right)$, where $\gcd(a,b)=1$, $a>b>0$ and $a+b$ is odd. In the triples $(x,y,z)$ generated by this parametrization, it is not necessarily always $x\leq y$. For example, $(20,15,12)$ is a triple generated by this parametrization, and $(15,20,12)$ will not be generated. This parametrization generates only the unique solutions. So we can have two possible cases, either $0<a^2-b^2\leq 2ab$ or $0<2ab\leq a^2-b^2$.
The sum of the triples = $x+y+z=4a^3b+a^4-b^4 \leq n$.
Let us consider the first case. Denote the number of solutions by $A_1^1(n)$ and $A_1^1=\lim_{n \to \infty}\frac{A_1^1(n)}{\sqrt{n}}$.
$$0<a^2-b^2\leq 2ab \implies \sqrt{2}-1\leq\frac{b}{a}=x<1$$
Number of pairs $(a,b)$ satisfying above constraints and also $4a^3b+a^4-b^4 \leq n$ can be approximated by
\begin{align}
\begin{split}
p(n)&\approx\int_{\frac{b}{a}=\sqrt{2}-1}^{1}\int_{4a^3b+a^4-b^4 \leq n}a \ da\ db\\
&=\int_{x=\sqrt{2}-1}^{1}\int_{0b>0$, fraction of which have odd value of $a+b$ is $\frac{2}{3}$. We have to multiply this factor.
\begin{align}
\begin{split}
A_1^1 &=\lim_{n \to \infty}\frac{A_1^1(n)}{\sqrt{n}}\\
&= \lim_{n \to \infty} \frac{2}{3} \cdot \frac{6}{\pi^2} \cdot\frac{p(n)}{\sqrt{n}}\\
&= \frac{2}{\pi^2} \int_{x=\sqrt{2}-1}^{1}\frac{dx}{\sqrt{1+4x-x^4}} \\
\end{split}
\end{align}
Similarly, it can be shown that for the other case exactly the same limit exists. So, $$A_1=2A_1^1=\frac{4}{\pi^2} \int_{x=\sqrt{2}-1}^{1}\frac{dx}{\sqrt{1+4x-x^4}} \approx 0.1277999513464289...$$
Using a similar approach it can be shown that
\begin{align}
\begin{split}
A_2&=\frac{2}{\pi^2} \left[ \int_{x=0}^{\sqrt{2}-1}\frac{dx}{\sqrt{3-6x^2-x^4}} +\int_{x=\sqrt{2}-1}^{1}\frac{dx}{\sqrt{4x+6x^2+4x^3-1-x^4}} \right]\\
& \approx 0.1036994744684913...
\end{split}
\end{align}
\begin{align}
\begin{split}
A_{13}&=\frac{52}{7\pi^2} \int_{x=(\sqrt{13}-3)/2}^{(\sqrt{26}-1)/5}\frac{dx}{\sqrt{20x+36x^2-5-7x^4}}\approx 0.1038855856479065...
\end{split}
\end{align}
Comment: It seems you are missing some conditions on $a$ and $b$ in you parametrization; for $(a,b)=(2,1)$ you get $(x,y)=(20,17)$, so $x\not\leq y$. And in for $(a,b)=(1,2)$ you get $y=-17$ which is not positive.
Comment: Also, I can't follow anything that you write after $A_1=...$. Where do these integrals come from? And why do you multiply them by these factors?
Comment: @Servaes I added more details. I hope everything is clear now.
Answer: To solve the Diophantine equation.
$$ \frac{ 1 }{ x^2 } +\frac{ 1 }{ y^2 } = \frac{ q }{ z^2 } $$
It is necessary to use the solution of the following equation.
$$a^2+b^2=qc^2$$
There are solutions when the coefficient can be represented as the sum of squares. $q=t^2+k^2$
$$a=-tp^2+2kps+ts^2$$
$$b=kp^2+2tps-ks^2$$
$$c=p^2+s^2$$
And the solution itself can be presented in this form.
$x=ac$
$y=bc$
$z=ab$
Comment: This answer would be greatly improved by explaining where these expressions come from, and showing why these statements are true (if they are).


Could not dind main class: XXXXX .the program will exit

Question: MM hey ^_^
i was following this post HERE and when opening .bat file an error says :
could not dind main class: net.minecraft.LauncherFrame.the program will exit.
any suggestions ??
Answer: You should probably paste the actual .bat file you used, but I believe that method no longer works with starting the minecraft launcher executable.
Comment: i used exactly the same one in the tutorial :(
Comment: That would be why, it's a bit outdated.
Comment: mm see this topic
http://www.reddit.com/r/Minecraft/comments/k7mmv/how_to_run_multiple_versions_of_minecraft/
Comment: some one says
"As a developer i'd prefer to have multiple minecraft-directories in the appdata folder and change their name to .minecraft with a batchfile instead of changing the appdata-variable, even if it doesn't effect anything. It wouldn't be portable anymore though.."
would you just explain what did he said ??
Comment: re: the reddit topic. That was a year ago, and it's still outdated.

The comment sounds like gibberish to me. As far as I understand, you can't have multiple of the same directory name in a location, and there's no reason to edit window's environment variables.
Comment: this means that there is no way to create many other minecraft in the same pc :(
thx 4 help
Comment: You can launch multiple instances, I'm not sure you really need multiple directories for anything at all.


Using predefined SVG file for creating a custom JointJS shape with ports

Question: I have a series of pre-created SVG symbols I want to use in JointJS.
I've searched about using precreated SVGs and I found to be possible to create a complete custom elements using SVG by putting the SVG in the 'markup' property - (https://groups.google.com/forum/#!topic/jointjs/pQvN_0lXPVk).
Below is the example of an SVG. Your help about how can I embed this definition in the markup property and add ports to it will be highly appreciated.
Thanks
<?xml version="1.0" standalone="no"?>
<svg viewBox="0 0 1024 768" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" stroke-linecap="round" stroke-linejoin="round" fill-rule="evenodd" xml:space="preserve" >
<defs >
<clipPath id="clipId0" >
<path d="M0,768 1024,768 1024,0 0,0 z" />
</clipPath>
</defs>
<g stroke-width="0.1" clip-path="url(#clipId0)" fill="none" stroke="rgb(0,0,0)" />
<g stroke-width="0.25" clip-path="url(#clipId0)" fill="rgb(0,0,0)" stroke="none" >
<path d="M1013.96,634.98 10.0392,634.98 1013.96,133.02 z" />
</g>
<g stroke-width="0.25" clip-path="url(#clipId0)" fill="none" stroke="rgb(0,0,0)" >
<polyline points="10.0392,133.02 1013.96,133.02 1013.96,634.98 10.0392,634.98 10.0392,133.02 " />
<polyline points="10.0392,634.98 1013.96,133.02 " />
</g>
</svg>

Answer: You can add the SVGImageElement to your markup to display arbitrary SVG in your shapes. Just convert the SVG file content to dataURL and set the xlink:href attribute.
var shape = new joint.shapes.basic.Image({
  // markup: '<g class="rotatable"><g class="scalable"><image/></g><text/></g>',
  attrs: {
    image: {
      'xlink:href': 'data:image/svg+xml;utf8,' + encodeURLComponent(svgFileContent)
    }
  }
});

http://jsfiddle.net/kumilingus/eqen3pdf/
In order to create a shape showing an SVG image and yet having ports you can e.g. use devs.Model shape and replace the only SVGRectElement in its markup with an SVGImageElement.
new joint.shapes.devs.Model({
  markup: '<g class="rotatable"><g class="scalable"><image class="body"/></g><text class="label"/><g class="inPorts"/><g class="outPorts"/></g>',
  attrs: {
  '.body': {
    'xlink:href': 'data:image/svg+xml;utf8,' + encodeURLComponent(svgFileContent)
  },
  inPorts: ['in'],
  outPorts: ['out']
});

http://jsfiddle.net/kumilingus/tm2ctvxq/
Note, that it's possible to insert the SVG file content directly into your markup (without <?xml version="1.0" standalone="no"?>). I would not recommended it for more complex SVG though.
For instance when SVG contains an SVGClipPathElement with an id. Creating 2 instances of your shape breaks condition that all the IDs in the  SVG must be unique.


Probability of getting a negative mark if one chooses options randomly in a MCQ question with negative marking

Question:
In a test with 100 multiple choice questions, a student chooses to pick an option randomly. There are four options for each questions. Answering a question correctly will give the student 1 mark, while picking a wrong option will give the student a pentalty of - 0.25 marks. There is only one correct answer for each question. What is the probability that a student will get negative marks if they follow such a strategy?

I'm stumped at even trying to model this problem. I do observe a few things, but I can't make any substantial arguments from them:

We could have a random variable, X represent the marks a student gets
while answering the 100 questions that way.
The range of values this variable can take is from -25 (all questions wrong) and 100 (all correct).
The expected value of this random variable is 6.25
How do I find the variance?
If we find the variance can we assume a normal distribution and see the area in the lower tail, below 0?
Comment: Thanks. Can I take this random variable (that counts the no of correct questions) to be binomial? (with p, the probability of success as .25 and q, the probability of failure as .75). Then I can take the mean and variance of this variable and find the cumulative probabilities (or approximate with a normal).
Comment: In R, `pbinom(19, 100, .25)` returns 0.09953041. What do you get using normal approx.? On this site it is permitted to answer your own question.
Comment: Find the distribution of random variable $X$ that counts the number of correct questions would be a good start.  Then, if $X = k,$ what will the score be? What value of $X$ just barely gives a positive score. Etc.
Comment: I've answered the question. Thank you! :)
Answer: One way to model this is:
Instead of taking X to represent the score student scores, let X represent a random variable that represents how many answers a student gets right. Let this be a binomial distribution with $ p $, the probability of success $0.25$. Now, we should look for the number of questions one would need to get right to get a score that's close to being negative.
If the student gets 20 answers right, his score would be 0. So, we need to find the probability of X being lesser than 20. This probability distribution has mean and variance: $$ \text{Mean} = n * p = 100 * 0.25 = 25 $$
$$ \text{Variance} = n * p * (1 - p) = 18.75 $$
We can now use approximate this distribution with a normal distribution. We need to find the probability of X being lesser than 20. Since 20 has a $ z $-score of -1.16, we need to find the area under the standard normal curve in the tail to the left of $ - 1.16 $.
And that gives us the probability: $ .1230 $
Comment: Right idea (+1), but a bit of improvement is possible. For the best normal approximation, you should use a continuity correction: $P(X \le 19) = P(X < 19.5) = P(X < 20),$ so use $z = (19.5 - 25)/\sqrt{18.75} = -1.27.$ and $P(Z \le -1.27) = .1020,$ which is close to the exact binomial value .0995 in my previous comment.


Why does the Law of Sines give an external angle?

Question: Why does the Law of Sines give the exterior angle below:

I am fully aware that the Law of Sines can be used in the following way:
$\dfrac{\sin 20}{250}=\dfrac{\sin \theta}{500}\implies \theta\approx 45^{\circ}$, and this angle should be the angle opposite to $500$m, but for some reason it is supposed to be the exterior angle. Can anyone explain why?
Also, in case it is relevant, this question stems from the original problem:

A small lighthouse is on a man made island just offshore. The light can illuminate effectively up to a distance of $250$ meters. From a point along the shore that is $500$ meters from the lighthouse, the sightline to the lighthouse makes an angle of $20^{\circ}$ with the shoreline. What length (to the nearest meter) of the shoreline is effectively illuminated by the light from the lighthouse?
Comment: In general, the sine of $x$ and the sine of $180^\circ -x$ are the same. So the Law of Sines doesn't care whether you want the external or internal angle. You need to choose between $x$ and 4180^\circ -x$ from additional information.
Comment: Your error is in assuming that $\dfrac{\sin 20}{250}=\dfrac{\sin \theta}{500}\implies \theta\approx 45^{\circ}$. You can conclude that $\sin\theta\approx0.684$, but that doesn't determine the value of $\theta$. There are two possible values of $\theta$ between $0^\circ$ and $180^\circ$, and you need to see what the solutions tell you about the original problem.
Answer: This problem does involve the Ambiguous Case;  one in which you are given two sides of a triangle, and an angle not between those two sides.  Depending on the exact values given, there may be two solutions, one solution (for two different reasons) or no solution.  This is the case, no matter how the problem is solved.
As others have noted correctly, your use of the Law of Sines is one way to solve this problem, as long as you recognize that the inverse sine function gives only one of the two possible angles.  The other possible solution is $(180^\circ -\theta)$,   Then use each of these angles in turn to solve for two values of the third side.
Another, quicker way to solve this problem is to use the Law of Cosine to find the two values of the base directly.  Applying the Law of Cosines, with $y$ equal to the shoreline side:$$250^2=500^2+y^2-2\cdot500 \cdot y\cdot \cos(20^\circ )$$The difference between the two solutions to this quadratic is the desired $x$
Answer: There is some ambiguity with the Law of Sines under a particular case. And that case is exactly what happens in your problem I believe. Have a look at the "The ambiguous case" paragraph of http://en.wikipedia.org/wiki/Law_of_sines.


Compactness and Cantor's Criterion

Question: Cantor's Criterion: If $\left\{C_{k}\right\}$ is a nested sequence of closed bounded, nonempty subsets of $\mathbb{R}^{n}$, then
$$
\bigcap_{k=1}^{\infty} C_{k} \neq \emptyset
$$
Furthermore, if $\lim _{k \rightarrow \infty} d\left(C_{k}\right)=0$, where $d\left(C_{k}\right)$ is the diameter of $C_{k}$, then $\cap_{k=1}^{\infty} C_{k}=\left\{x_{0}\right\}$ for some $x_{0}$ in $\mathbb{R}^{n}$
Discussion about the Cantor's Criterion when it is not Euclidean metric: Find a counter-example and consider the statement when "closed, bounded" is replaced by "compact". Are there any examples for which Cantor's Intersection Theorem would not hold for the non-Euclidean metric? Is it related to the Heine-Borel theorem, or it should be a completely different metric?
Answer: The Cantor Intersection theorem holds in general topological spaces, so no metric notion is required. This is the topological version: Let $X$ be a topological space. A decreasing nested sequence of non-empty compact subsets of $S$ has a non-empty intersection.
What may fail, if I understand correctly, is to assume $X$ is closed and bounded and $X$ is not compact. Then you may find indeed counterexamples since the theorem stated above requires the notion of compactness. For example take, in the space of rational numbers, the sets
$$C_k = [\sqrt{2}, \sqrt{2}+1/k] = (\sqrt{2}, \sqrt{2}+1/k) $$
are closed and bounded, but their intersection is empty (as Wikipedia also states).
Note that compactness is equivalent to closed and bounded only in particular spaces, not in general, while the converse is always true (if we assume the space is not too bad, that technically means requiring it is Hausdorff, but leave this part aside).
Note: for compact I mean that for every open cover there exists a finite subcover and it satisfies the Hausdorff condition.
Comment: @Snowflake: What, precisely, do you think is inaccurate in the Wikipedia article on the theorem?
Comment: @Snowflake: It gives a clear example of a metric space in which *closed and bounded* is not enough. What else do you want?
Comment: @Snowflake: The example in the space of rational numbers, which is found about halfway through the section **Statement for Real Numbers**.
Comment: Wikipedia sentences are not desired, since I also looked to them before posting this problem and found them inaccurate in terms of the explanation
Comment: Let me explain it better
Comment: I explained in detail what is asked in the problem statement, wherein there should be definitely counterexamples that do not hold for non-Euclidean metrics!
Comment: Even if you have a non-Euclidean metric but require that the set is compact, then the theorem holds.
Comment: @Son Gohan I modified the problem statement to be more clear about the metric in general.
Comment: @BrianM.Scott It does not clearly explain the necessary question asked here
Comment: @BrianM.Scott Which one?

Compactness and Cantor's Criterion


Facebook QR Code Like through iPhone Application

Question: I am trying to create a QR Code that if scanned on a phone that has the Facebook application installed, the Facebook application will go directly to the like page saved in the QR code. I have tried what this website has said, and it did not work. It opened the Facebook application but did not go to the page.
I'm trying to redirect to this Facebook page.
I would greatly appreciate anyone's help if they can give me a pointer. I am not a programmer or a technical person, so my knowledge is limited. But, I am willing learn. Thank you.
Comment: Do you have a link to the QR code that you've tried?
Comment: Yes, I have tried the following link:
Comment: Oops let me add it fb://page/279522875481579/
Comment: Is that what you were looking for?
Comment: possible duplicate of [Facebook page automatic "like" URL (for QR Code)](http://stackoverflow.com/questions/8763046/facebook-page-automatic-like-url-for-qr-code)
Answer: Something you could do is use a landing page service that lets you add 'like' buttons.
One that's free: www.likify.net.
I'm not sure you can open Facebook urls in the facebook app directly. As far as I know, only the app store and itunes can do this on iPhone.
Comment: Any application should be able to send to Facebook by using fb:// instead of http:// in the URL.
Answer: When I try to access facebook.com/ViralGliders even through my browser, it just takes me to the facebook homepage. Maybe this is an incorrect URL, or you have some permission issues..?


Traded right before the All Star Game?

Question: So let's say, for the sake of the question, that the player being traded is Clayton Kershaw.
Situation:  Kershaw is selected as the NL's starter in the All Star Game.  Couple of days before the All Star Game, the Dodgers shock the nation and trade Kershaw to the Yankees.
Question:  Does Kershaw still start for the NL?  Does he start for the AL?  Does he not start, but still play for the AL?  What happens in this situation, in terms of him and his All Star Status?
Answer: This happened to Jeff Samardzija for the 2014 MLB All-Star Game(1), though he was not selected as a starter(2).
He was traded from the Cubs (an NL team) to the A's (an AL team) just before the all-star rosters were announced. Samardzija was selected as a NL all-star as a member of the Cubs.

Does he ... play for the AL?

No.

What happens in this situation, in terms of him and his All Star Status?

The league switch rendered him ineligible to pitch for the All-Star Game.
The MLB addresses the scenario in greater detail here:

What if a selected player gets traded to a team in the opposite league before the All-Star Game?
This happened to Jeff Samardzija in 2014, when the Cubs dealt him to the A's. In such a scenario, the player is deemed ineligible to participate in the game but is still recognized as an All-Star for the original league. In Samardzija's case, he wore a generic NL jersey and All-Star Game cap for the pregame player introductions.

In other words, he's still an NL all-star, but isn't able to play in the All-Star Game.

Does [he] still start for the NL? Does he start for the AL?

If he was selected to start, his ineligibility alone would render him unable to start for either team.

Traded right before the All Star Game?


Android Heads Up notification not showing up

Question: I am not able to find where i am getting wrong in building the Notification.
I want the notification to show at top when phone is active and
on lock screen when phone is in sleep.
Here is the code that i have tried. But not able to achive the result.
<code>PendingIntent pendingIntent = PendingIntent.getActivity(context,0, openIntent,PendingIntent.FLAG_UPDATE_CURRENT);

NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "Normal")
    .setSmallIcon(R.drawable.ic_folder)
    .setContentIntent(pendingIntent)
    .setPriority(NotificationCompat.PRIORITY_MAX)
    .setCategory(NotificationCompat.CATEGORY_MESSAGE)
    .setVibrate(new long[] {1000})
    .setContentTitle(mainListItem.getTitle())
    .setContentText(mainListItem.getDetail())
    .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
    .setAutoCancel(true)
    .setVisibility(NotificationCompat.VISIBILITY_PUBLIC);

NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

notificationManager.notify(0,builder.build());
</code>
Comment: That is the issue from version 26 you need to create a notification channel to show notification.  For more check the link https://developer.android.com/guide/topics/ui/notifiers/notifications.html
Comment: What is the target sdk , compile and minimum sdk version you are using ?
Comment: Min sdk 14, target and compile sdk 26
Comment: I am running this app on android 6.0.1 Marshmallow
Comment: Try creating notification channels and see
Comment: Notification channels are only available at this moment for Android Oreo+ (version 8+). There is no compatibility with support libraries yet. We need to wait or apply other strategies
Answer: It's to late to answer...
Seems like your code is work fine for me, but for some reasons, that stop your heads-up notification to showing up.

Please check if your current working app that's managed by some system settings like Notification Center of your phone settings, if that's disabled your heads up notification, then your heads up notification not able to show as the same in my phone the Notification Center set my app's notifications to Unchecked or Disabled the "Banners" (Display on the top of status bar) setting, it does by default when i installed any applications in my phone. then my heads up notification is not showing. You need to checked or enabled it.
If your app run in the android version 26 and later, you need to create a notification channel and please check your Notification Settings make sure that's not block your app's notifications.
Hope it help.
Comment: Just to follow up, you only *need* to create a notification channel for your app if it *targets* version 26 or later, [per the docs](https://developer.android.com/training/notify-user/channels): When you target Android 8.0 (API level 26), you must implement one or more notification channels. If your targetSdkVersion is set to 25 or lower, when your app runs on Android 8.0 (API level 26) or higher, it behaves the same as it would on devices running Android 7.1 (API level 25) or lower.


Redundancy: LVM+mdadm or LVM internal RAID

Question: The task is to create LVM storage for virtual machine images. So LVM will be used in any case.
There are two ways LVM providing redundancy:

block mirroring
lvcreate -m 1 --mirrorlog mirrored -n logical_volume -L 50G vg0
internal RAID mechanism
lvcreate --type=raid1 -n logical_volume -L 50G vg0

Second way should provide reading performance boost.
As alternative we can create raid1 with mdadm and use Linux Soft Raid device as physical volume for LVM.
Which way is better and why?
Answer: mdadm raid is better for raid1 and on top of that you can put lvm for flexibility. Lvm has problems when a disk goes bad, mdadm is the tried and proved solution for raid1.
Comment: I choose pure LVM solution as it allows to provision both RAID and non-RAID LV from the same VG. It saves a lot of space in case of storing unimportant data like swap partitions.


Realizar uma busca por data em uma coluna timestamp utilizando spring data

Question: Estou tentando realizar um busca apenas pela data atual em uma coluna timestamp, ou seja sem informar as horas e sim apenas a data.
Modelo:
@DateTimeFormat(pattern = "dd/MM/yyyy hh:mm")
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "data")
private Date date;

Atualmente utilizo o Spring Data para realizar a consulta.
Classe de serviço:
public List<Order> findByDate(){
    return orderRepository.findByDate(new Date());
}

Repositório Spring Data:
@Repository
public interface OrderRepository extends JpaRepository<Order, Long> {
    List<Order> findByDate(Date date);
}

O problema que a query é feita levando em consideração o timestamp atual com valores de hora minuto e segundo e quero que o select seja feita apenas selecionando os registos de data atual.
Select com o binding de exemplo:
SELECT
    order0_.id AS id1_1_,
    order0_.data AS data2_1_,
    order0_.pedido AS pedido3_1_,
    order0_.pagamento AS pagament4_1_,
    order0_.telefone AS telefone5_1_,
    order0_.status AS status6_1_,
    order0_.total AS total7_1_,
    order0_.usuario AS usuario8_1_
FROM
    spring_admin.pedidos_zuhause order0_
WHERE
    order0_.data = ?;

binding parameter [1] as [TIMESTAMP] - [Wed Sep 20 10:15:35 BRT 2017]
Eu sei que via MySQL consigo fazer isso utilizando a função date(), mas como posso fazer isso pelo hibernate?
Answer: Como a coluna em banco armazena também informações que não apenas dia/mês/ano você tem que fazer com que a query gerada considere isto.
Uma forma de fazer isto é buscando por compras com date between o início e término do dia. A consulta no seu repositório ficaria assim:
List<Order> findByDateBetween(final Date start, final Date end);

A chamada no seu service seria algo como isto:
public List<Order> findByDate(){
    final Date start = // recupera o início do dia;
    final Date end = // recupera o fim do dia;
    return orderRepository.findByDate(start, end);
}

Veja aqui formas de obter datas de início e fim do dia: How to obtain the start time and end time of a day?
Como você mesmo citou funções nativas do SGBD podem ser usadas. O Spring Data fornece outros meios para criação de queries, como @Query e QueryDSL, além do já suportado por padrão pela JPA.


Getting Auto updates causing 100% CPU utilization

Question: Have setup Google cloud SQL server in asia-south1 zone. Issue is we are getting auto updates triggered in GCP Cloud SQL during IST day hours by Google which is causing server to reach 100% CPU utilization and causing system downtime.
Is there a way to block these updates during IST day hours and get it only in non critical (night) hours
Increased vCPUs from 1 to 2. However, that didn't help
Answer: As per Cloud SQL best practices, it is recommended to configure a maintenance window for your primary instance.
With maintenance window you can control when maintenance restarts will be performed. You can also specify whether an instance gets updates earlier or later than other instances in your project with Maintenance timing.
Maintenance window

The day and hour when disruptive updates (updates
  that require an instance restart) to this Cloud SQL instance can be
  made. If the maintenance window is set for an instance, Cloud SQL does
  not initiate a disruptive update to that instance outside of the
  window. The update is not guaranteed to complete before the end of the
  maintenance window, but restarts typically complete within a couple of
  minutes.

Maintenance timing

This setting lets you provide a preference about the relative timing
  of instance updates that require a restart. Receiving updates earlier
  lets you test your application with an update before your instances
  that get the update later.
The relative timing of updates is not observed between projects; if
  you have instances with an earlier timing setting in a different
  project than your instances with a later timing setting, Cloud SQL
  makes no attempt to update the instances with the earlier timing
  setting first.
Answer: According to the official documentation link

"If you do not set the Maintenance timing setting, Cloud SQL chooses
  the timing of updates to your instance (within its Maintenance window,
  if applicable)."

You can set your the Maintenance window DAY-TIME and choode Order of update "any", and the updates will be triggered during the Maintenance window.
Comment: Thanks. We have already set maintenance timing as follows

Preferred window :Sunday, 12:00 AM — 1:00 AM (UTC+5:30)

Order of update : Earlier.

However, updates are still happening at any time of day.

Will changing Order of update to "any" stop updates outside maintenance window ?
Comment: Maintenance timing and maintenance window are two different things. Please check my answer https://stackoverflow.com/a/58727000/4539626
Comment: From my understanding changing Order of update to "any" stop updates outside maintenance window.
Answer: Maintenance frequency is once in every few mounts. It means that in each few months database will be unresponsive once time while being maintained.
Is it possible to cancel maintenance or to make maintenance manually?