Infinite union of uncountably many sets

Question: While working through my book I have read that if $V$ is an open set, then $V$ is the union of all possible $\varepsilon$ - neighborhoods of all elements in $V$. This makes sense to me when I talk about the union of rationals, or natural numbers for instance - but what if there are uncountably many $p\in V$? Or to be more specific:

What would be a possible way to understand the notion of taking the union an uncountable number of times?

How could I formally express this idea?
Comment: See, e.g., [this question](https://math.stackexchange.com/questions/89104/union-of-uncountably-many-uncountable-sets)
Comment: You can define the thing cosntructively the same say you would do for finite or countable union. An element $x$ lies in an arbitrary (finite, countable, uncountable) union of $U_i$ if $x \in U_i$ for some $i$.
Comment: You may be thinking of finite unions as repeated binary unions, thinking of countable unions as some sort of limit of finite ones, and therefore wondering about uncountable unions. If so, it's important to realize that a completely general definition is available, as in the comment by @nicomezi, and is simpler than what you were thinking of.
Comment: It is unclear what your issue really is: Are you looking for intuition or a formal definition? If you want the former, take a look at Axiom 5 in the ZF set of axioms [here](https://en.wikipedia.org/wiki/Zermelo%E2%80%93Fraenkel_set_theory#5._Axiom_of_union).
Comment: @MoisheKohan I'm looking for both. Thanks for the link, will check it out.
Answer: If $S$ is any collection (set) of sets, we write $T=\bigcup S$ (Latex \bigcup S) to mean that any $x\in T$ iff $x$ is a member of at least one of the sets in the collection $S.$ That is, $$\bigcup S=\{x: \exists \sigma\in S:\,x\in\sigma\}.$$ The cardinality of $S$ is irrelevant. We do not "take the union" as some kind of sequence. It just exists.

Infinite union of uncountably many sets


What is the proper way to handling OnClick ButtonView and other View in RecyclerView with touch listener?

Question: I have problem on Handling OnClick ButtonView and other View in RecyclerView Staggered Grid with OnTouch.
This my item RecyclerView:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/root_parent"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="4dp"
    card_view:cardCornerRadius="10dp"
    card_view:cardUseCompatPadding="true">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <com.kamardagang.utils.SelectableRoundedImageView
            android:id="@+id/newsAvatar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:adjustViewBounds="true"
            android:src="@drawable/ic_user" />
        <Button
            android:id="@+id/btn_action"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
    </LinearLayout>
</android.support.v7.widget.CardView>

and this Adapter with Handling Click:
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.ViewHolder> implements View.OnTouchListener {

    private final GestureDetector gestureDetector;
    private Activity activity;
    public ArrayList<HashMap<String, String>> dataNews;
    private OnNewsItemClickListener OnNewsItemClickListener;

    public void setOnNewsItemClickListener(OnNewsItemClickListener onNewsItemClickListener) {
        this.OnNewsItemClickListener = onNewsItemClickListener;
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {

        final int viewId = v.getId();
        if (viewId == R.id.root_parent) {
            if (gestureDetector.onTouchEvent(event)) {
                if (OnNewsItemClickListener != null) {
                    OnNewsItemClickListener.onRootClick(v, (Integer) v.getTag());
                }
                return true;
            }

        } else if (viewId == R.id.btn_action) {
            if (gestureDetector.onTouchEvent(event)) {
                if (OnNewsItemClickListener != null) {
                    OnNewsItemClickListener.onActionClick(v, (Integer) v.getTag());
                }
                return true;
            }
        }

        return false;
    }

    public interface OnNewsItemClickListener {
        public void onActionClick(View v, int position);

        public void onRootClick(View v, int position);
    }

    public NewsAdapter(Activity activity, ArrayList<HashMap<String, String>> News) {
        this.activity = activity;
        dataNews = News;
        gestureDetector = new GestureDetector(activity, new SingleTapConfirm());
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        @Bind(R.id.root_parent)
        CardView root_parent;
        @Bind(R.id.btn_action)
        Button btn_action;

        public ViewHolder(View vi) {
            super(vi);
            ButterKnife.bind(this, vi);

        }
    }

    @Override
    public NewsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
                                                     int viewType) {
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.pin_item_news_recyclerview, parent, false);
        ViewHolder holder = new ViewHolder(v);
        holder.root_parent.setOnTouchListener(this);
        holder.btn_action.setOnTouchListener(this);
        return holder;
    }

    public void onBindViewHolder(final ViewHolder holder, int position) {
        if (position % 2 == 0) {
            holder.root_parent.setVisibility(View.GONE);
            holder.btn_action.setVisibility(View.VISIBLE);
        } else {
            holder.root_parent.setVisibility(View.VISIBLE);
            holder.btn_action.setVisibility(View.GONE);
        }
    }

    public int getItemCount() {
        return dataNews.size();
    }

    public void delete_all() {
        int count = getItemCount();
        if (count > 0) {
            dataNews.clear();
        }
    }

    public long getItemId(int position) {
        return position;
    }

    private class SingleTapConfirm extends GestureDetector.SimpleOnGestureListener {
        @Override
        public boolean onSingleTapUp(MotionEvent event) {
            return true;
        }
    }
}

The problem : the Click of R.id.btn_action can detected , but not R.id.root_parent , so how to fix it ?
Comment: Try using viewHolder.itemview.setOnClickListener( ) to set the listener for the entire view instead of root_parent.
Answer: to handle recyclerView click i have rather go with an interface that can talk with the adapter and my activity, for example you could do something like this:
public interface OnRecyclerItemClickListener {

    void onItemClickListener(View v, int position);

   // void onItemLongClickListener(View v, int position);

}

make your activity implements OnRecyclerItemClickListener and pass it to the constructor of you adapter and call its method whenever your button clicked. and do me a favorite, remove this
    holder.root_parent.setOnTouchListener(this);
    holder.btn_action.setOnTouchListener(this);

and add them inside onBindViewHolder
EDIT:
OnRecyclerItemClickListener onItemClick

public NewsAdapter(OnRecyclerItemClickListener onItemClick, /* my list */){
this.onItemClick = onItemClick;
}

public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.myButton.setOnClickListener(new OnClickLisenter(){
    public void onClick(View v){
    onItemClick.onItemClickListener(v,position);
    }
});
}

this is just a sketch.
Comment: ok i understand this method, looks cleaner.im usining this in my project (gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {) -- how do you pick up what button was clicked and then do some action on that because after that i have (public void onItemClick(AdapterView parent, View view, int position, long id) {) but that just picks up the item click or can i add something inside to pick up what button was clicked


Discrete mathematics - understanding proof by induction

Question: So I have an example of a proof that my teacher used induction to solve, but I'm having trouble understanding the inductive step in the second slide. So I get the part where they substitute k+1 in the formula, but I don't understand where the 1+2+...+  +( +1) came from and how that managed to turn into the equation in my 2nd underline?
Like the k + (k+1) portion doesn't look like it matches the original formula, and I'm confused because it looks like they substituted n with k instead of k + 1 like it was stated at the beginning of the second slide? I also don't really understand recursion, so I'd appreciate if someone explained the steps behind that transition to me as well.
Answer: When they write $1+2+\ldots + (k+1)$, they mean summing up every positive integer up to $k+1$. The integer before $k+1$ is $k$.
Hence $$1+2+\ldots + (k+1) =(1+2+\ldots + k)+ (k+1)\tag{1} $$
We already know that $1+2+\ldots + k = \frac{k(k+1)}{2}$ by the induction hypothesis, substitute this into $(1)$ and we have
$$(1+2+\ldots + k)+ (k+1)=  \frac{k(k+1)}{2}+(k+1)$$
Answer: My understanding is that- In your first underline they are considering the sum $1+2+3..$ till   $(k +1)$ .
This series can be written as $1+2+3+...+(k+1)$ = $1+2+3+...+k+(k+1)$.
In the second underline, they substituted $ 1+2+3+.. +k$ as $\frac{k(k+1)}{2}$, which was derived from the "Inductive Hypothesis".


Sum a filtered column

Question: I am trying to sum up a filtered column to count the number of occurrences. How can i sum the character data type.
bowler           dismissal_type
TS Mills         bowled
TS Mills         bowled
A Nehra          bowled
Pj cummins       bowled
TS Mills         bowled
A Nehra          bowled

I tried to sum the dismissal_type but throws me an errors saying can't sum character type
bowled <- innings%>%
 filter(dismissal_type == "bowled")%>%
 group_by(bowler)%>%
 summarize_each(bowled = sum(dismissal_type == "bowled"))%>%
 top_n()

It seems simple but can't get it done. All i want to output is:
bowler           dismissal_type  n
TS Mills         bowled          3
A Nehra          bowled          2
Pj cummins       bowled          1

Comment: Maybe `innings %>%  filter(dismissal_type == "bowled") %>% count(bowler)`?
Comment: Count(bowler) worked. Thanks
Answer: You could do
# Assuming the data frame is called bowler

# Define the subset
my_subset <- bowler$dismissal_type == "bowled"
# Count the occurrences of column bowler
my_counts <- as.integer(ave(bowler$bowler, bowler$bowler, FUN = length))
# [1] 3 3 2 1 3 2
# Initialize the column n (needed in case the subset is strict)
bowler$n <- 1L  # or any other number, na_integer, etc.
bowler$n[my_subset] <- my_counts[my_subset]
#       bowler dismissal_type n
# 1   TS Mills         bowled 3
# 2   TS Mills         bowled 3
# 3    A Nehra         bowled 2
# 4 Pj cummins         bowled 1
# 5   TS Mills         bowled 3
# 6    A Nehra         bowled 2

Comment: I would use `tapply` instead of `ave`.
Comment: @RuiBarradas But you'd need another step to match the lengths right? (I'm not really familiar with `tapply`)
Comment: No because in the expected output the OP wants only one row per count, not the counts in all input rows. All that is needed is a summary table.

Sum a filtered column


Inserting Include in Database Content

Question: I'm working with PHP and MySQL and am displaying an article stored in a database by echoing $Content. I would like to include another file just before the second paragraph, which begins with [p]In fact, you (I replaced the paragraph tags with brackets here.)
This doesn't work...
$BaseINC = '../../Geobop';
$Content = str_replace('
In fact, you', ''.require_once($BaseINC."/$MyPHP/inc/A/Test.php").'',     $Content);

It displays the error Warning: require_once(../../Geobop/2B/inc/A/Test.php In fact, you) [function.require-once]: failed to open stream: If I change A/Test.php) to A/Test.php;) (adding a semi-colon), it fails again.
If I strip out the string I'm trying to replace, it works to a point.
$BaseINC = '../../Geobop';
$Content = str_replace('
In fact, you', ''.require_once($BaseINC."/$MyPHP/inc/A/Test.php").'',     $Content);

The weird thing is, it replaces [p]In fact, you with a numeral 1, with the text I inserted in my test file (Test.php) displaying at the top of the page.
Can anyone tell me what I'm doing wrong?
I should also mention that Test.php is physically located on one website (MySite1), while the article I'm previewing is on another site. However, all my websites include files stored on MySite1. I've included thousands of files; I just haven't figured out how to do it with a str_replace operation. Thanks.
Answer: I don't think you want to require the page, but rather want the contents in a string, right? In that case, you should use file_get_contents($filename) instead. This returns a string, which can be used as an argument for str_replace. require returns 1 if there was no error. It does not return its contents(!); unless it is explicitly returned from that file using a return statement.
Turning it into:
$BaseINC = '../../Geobop';
$Content = str_replace('
In fact, you', file_get_contents($BaseINC."/$MyPHP/inc/A/Test.php"), $Content);

Using require or include does not give you their contents in a string. Instead it runs the code inside of it. If that is PHP, it is executed. If it is HTML, it is outputted. This is why you saw the string appear at the top of your page.
Comment: Actually, that might just fix half of my problem. It works in that I can now include "static content." But is there a way I can include PHP content? In other words, if I type TEST on my test file (Test.php), then use file_get_contents, it displays "TEST." But if I type TEST followed by an echo value, it doesn't display the echo value. Getting the contents of files is helpful, but there are several fairly complex includes, with lots of PHP code, I'd like to include here.
Comment: well, in that case you'd need to have the file parsed first. Often this can be done by calling it via a http-request, like so: `file_get_contents('http://localhost/Test.php')` instead of like `file_get_contents('./Test.php')`.

Inserting Include in Database Content


How to use custom tokens in view header Drupal 8

Question: I make custom token which i use in view filter but now i want to use in view header.The custom token doesn't show in view header Global: Unfiltered text (Global: Unfiltered text) or how i make "Available global token replacements" to use in view header Global: Unfiltered text (Global: Unfiltered text). Thanks in advance.
Answer: One possible soliton is to simply when declaring your custom tokens in hook_token_info()
use <code>$info['tokens']['view']</code>
Ex:
<code>$info['tokens'] = [
    'view' => [
       'my-custom-token' => [
          'name' => t('Custom Token'),
          'description' => t('A custom token I created.'),
       ],
       // 'my-second-custom-token' => [...
    ],
];
</code>


How to kill a running script from another script?

Question: I have a a.sh script that executes a infinite loop with a list of commands in background in a Debian machine and I would like to use another script b.sh to end with a.sh. As far as I know pkill -f a.sh is one way of doing it, but I want to know if there is another way of doing it
Comment: [How to stop a script within another script](https://unix.stackexchange.com/q/421707), [Stopping a running script though another script file](https://askubuntu.com/q/526886), etc.
Answer: man -k kill shows many commands to kill processes. Watch out (1) (general commands) and (8) (admin commands). At my system I get (manually filtered):
killproc (8)         - Send signals to processes by full path name
docker-container-kill (1) - Kill one or more running containers
docker-kill (1)      - Kill one or more running containers
kill (1)             - terminate a process
killall (1)          - kill processes by name
killall5 (8)         - send a signal to all processes.
pkill (1)            - look up or signal processes based on name and other attributes
skill (1)            - send a signal or report process status

Comment: Thanks I will check this commands
Answer: If you run a.sh from b.sh you can get the process id of a.sh
b.sh
    a.sh &          # Execute a.sh in the background
    APID=$!         # $APID is now the pid of a.sh

    #do some stuff or wait

    kill -SIGTERM $APID          # Give the process a chance to shut down
    kill -SIGKILL $APID          # Certain kill

This way you can kill the particular instance of a.sh if you have multiple concurrent
instances.
Comment: It's not the case but I will have in mind for a future, thanks.
Comment: First, it is better to use name `-kill` instead of number `-9`: Better readable and some numbers differ at different system. Second, give signal `-term` (the default) the first change, so that the process has a chance to clean its work. Signal `-klll` terminates a process immediately.
Comment: Agree kill -SIGTERM $APID; kill -SIGKILL $APID is better.


How to generate java classes for ORMlite from existing database

Question: I have an existing SQLite database and need to generate classes for ORMlite from this database. I could do this manually but looks like a boring and time consuming task... do you know any tools that could do it for me or at least could help me in this task?
I found a similar question about this on SO but it's a quite old one :
 how to generate a java class code from a sqlite database for ORMLite
Answer: Since I didn't find any tools that suits my needs I just wrote a quick Python script doing the job, you can get it here
Maybe it doesn't suits all needs but it suits mines so maybe it could be useful to anybody else.
Comment: Great work, only sad thing is that it supports just SQL Lite and not others DB like MySQL/Maria DB.
Comment: Thank you. Well i just did this as quickly as i could just to solve the problem I had, not really to make a great and perfect tool that always works perfectly and made to be used by others. Just shared it because i did it for me and that cost me nothing to share.
Answer: Thank you very much @Laurent for the Python script, I have adjusted the script a little so that it works with the mysql database. have fun with it.


Por que a atribuição múltipla de variáveis cria uma lista quando utilizada com o operador asterisco?

Question: Supondo que há uma tupla com três valores, ('a', 1, 'b'), e deseja-se atribuir o primeiro valor em uma variável e manter o restante em outra. Para isso é possível fazer:
a, *b = ('a', 1, 'b')

Assim, a possuirá o valor 'a' enquanto b possuirá o valor [1, 'b'].
Por que o valor definido em b é uma lista?
Não consigo ver vantagens em criar uma estrutura mutável, como a lista, a partir de um valor fixo, como também não vejo motivos em se utilizar uma estrutura que semanticamente deveria ser homogênea para alocar dados possivelmente heterogêneos.
Tanto que quando utilizado como argumento de uma função o objeto criado é uma tupla:
def foo(a, *b):
    print(a, b)

foo('a', 1, 'b')  # a (1, 'b')

Não faria mais sentido b também ser uma tupla em a, *b = ('a', 1, 'b')?
Answer: Estava lendo o livro que havia citado nos comentários novamente, e acabei me precipitando com a resposta. Dando uma pesquisada a fundo acabei achando a discussão:
https://mail.python.org/pipermail/python-3000/2007-May/007312.html
De acordo com Greg no link da discussão sobre a pep3132:
não é possível saber de forma direta o tamanho de um iterador. O único jeito de retornar uma tupla, seria primeiro criando uma lista, para então criar uma tupla.
Ou seja, necessitaria um passo a mais para o tratamento dos dados. Por isso é retornado uma lista.
Comment: **1)** _"por padrão *args monta uma lista"_: o AP prova que quando o _unpacking_ é feito nos argumentos de uma função, o retorno é uma tupla e não uma lista. Sua afirmação não faz sentido. **2)** _"Unpack serve para instanciar um valor imutável em uma variável mutável"_: li a [PEP 3132](https://www.python.org/dev/peps/pep-3132/) e não achei essa afirmação. **3)** _"Se você quiser trabalhar com tuplas nomeadas, o recomendado é utilizar namedtuple"_: Não entendi a relação com a pergunta e `namedtuples` é a única implementação nativa de Tuplas Nomeadas, então me parece óbvia a afirmação
Comment: Tenho o Fluent Python, vou dar uma olhada quando chegar em casa. E mesmo com o que você mencionou, sua afirmação _"Unpack serve para instanciar um valor imutável em uma variável mutável"_ segue não fazendo sentido. E talvez não tenha ficado claro, mas o AP gostaria de entender qual o motivo de decidirem por listas ao invés de tuplas e porque este comportamento não é o mesmo quando desempacotamos argumentos posicionais. E apenas uma discussão para entender o porquê essa decisão foi tomada, sabemos que é uma lista, mas deveria ser uma lista?
Comment: `a, *b, c = (1, 2, 3, 4, 5)` ficaria `1, (2, 3, 4), 5`.. Faria tanto sentido quanto uma lista pois você está quebrando uma sequencia em pedaços, com a diferença é que semanticamente uma tupla faria mais sentido pois é uma representação fixa do "pedaço" da sequência. A discussão é legal, o difícil é achar uma resposta do porquê essa decisão foi tomada deste jeito, pois na PEP 3132 é especificado que é uma lista, mas não explica porque tem que ser uma lista. PS: Qual capítulo do Python Fluente você se referiu? Não vou conseguir ler todo ele agora até de tarde hahahah
Comment: (não vi como estava o texto anterior da resposta - mas a resposta atual parece satisfatória para mim)
Comment: Mas a pergunta é justamente o porquê que o "unpack" cria uma lista. Também não entendi a relação da `namedtuple` com a pergunta.
Comment: Porque  a tupla em si é imutável. É como disse " se você faz unpacking, é porque você irá manipular os dados a partir das variáveis que utilizou para o unpacking.". O namedtuple é para não haver necessidade de fazer o unpack e conseguir utilizar a tupla como se fosse uma variável, não havendo necessidade de fazer o unpacking. Vou tentar ser mais conciso na resposta.
Comment: "This PEP proposes a change to iterable unpacking syntax, allowing to specify a "catch-all" name which will be assigned a **list** of all items not assigned to a "regular" name."
Por isso recomendei *namedtuple* para não haver necessidade de salvar na memória uma tupla que já possa ter sido criada. E não precisa "achar" essa afirmação, é simples. Tuplas são imutáveis, e só tem dois sentidos de fazer unpacking, manipular dados, ou nomea-los. Por isso citei namedtuples. O conhecimento que estou me basendo é num livro escrito por *Luciano Ramalho*, **Fluent Python**.
Comment: Hmm, então, mas aí que está. Qual seria o sentido em *desempacotar* uma tupla para outra tupla? É isso o que estou colocando em pauta. Se fosse apenas para dar nome aos valores da tupla, não seria mais interessante utilizar namedtuple para este caso? Qual seria o sentido de criar uma tupla a partir de outra tupla(?)
Comment: Qualquer coisa vamos pro chat do SOPt a tarde... aqui tá comprido demais já
Comment: página 27 começa Tuple Unpacking. Tenho que ir trabalhar, mas vou dar uma ida lá no chat
Answer: Não sei o quanto isso resonde a sua pergunta, mas essa implementação (lista no lugar de tupla) permite utilizar a sintaxe do * mesmo em casos onde o tamanho da sequência é desconhecida, como em geradores:
>>> gen = (x**2 for x in range(5))
>>> len(gen)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: object of type 'generator' has no len()
>>> first, *rest = gen
>>> first
0
>>> rest
[1, 4, 9, 16]

Aparentemente uma única implementação é utilizada para a sintaxe do *, fazendo com que funcione da mesma forma para qualquer iterável - juntando todos os elementos sobressalentes em uma lista - independente do tipo de iterável (lista, tupla, gerador ou até mesmo strings):
>>> first, *rest = 'mystring'
>>> first
'm'
>>> rest
['y', 's', 't', 'r', 'i', 'n', 'g']

Imagino que seria possível implementar a sintaxe do * de forma a retornar os elementos no mesmo tipo de dado inicial (tupla para tupla, string para string...), mas em alguns casos (como no do gerador) isso não daria certo. E aí estaríamos nos perguntando se seria melhor passar estes valores para lista ou tupla... :-)


Pandas Dataframe Manipulation logic

Question: Can use please help with below problem:
Given two dataframes df1 and df2, need to get something like result dataframe.

import pandas as pd
import numpy as np
feature_list = [ str(i) for i in range(6)]
df1 = pd.DataFrame( {'value' :  [0,3,0,4,2,5]})
df2 = pd.DataFrame(0, index=np.arange(6), columns=feature_list)

Expected Dataframe :
Need to be driven by comparing values from df1 with column names (features) in df2. if they match, we put 1 in resultDf
Here's expected output (or resultsDf):
Comment: why does the column `0` contains only `0`? And where did the index of the `resultDf` come from?
Comment: you are right. expectedDf is not correct. 0 should be 1 too. I will update the picture with correct result.
Answer: I think you need:
(pd.get_dummies(df1['value'])
   .rename(columns = str)
   .reindex(columns = df2.columns,
            index = df2.index,
            fill_value = 0))

   0  1  2  3  4  5
0  1  0  0  0  0  0
1  0  0  0  1  0  0
2  1  0  0  0  0  0
3  0  0  0  0  1  0
4  0  0  1  0  0  0
5  0  0  0  0  0  1

Pandas Dataframe Manipulation logic


What are some examples of functions that are continous from $[a,b]$, differentiable $(a,b)$ but not at $a$ and $b$.

Question: I am studying the MVT and Rolle's Theorem. I would like some examples of functions that are continuous from $[a,b]$, differentiable from $(a,b)$ but not differentiable at $a$ and $b$. I am aware that the derivative at the point c is defined as:
$ f'(c) = \displaystyle \lim_{x \to c} \frac{f(x) - f(c)}{x-c}$
Basically, I'm wondering why does a function have to be continuous at the endpoints of the interval, but it doesn't have to be differentiable at the endpoints. Why is this important?
My other question is, how significant is the study of open/closed sets important in calculus?
Comment: *how significant is the study of open/closed sets important in calculus?* Well, it is more like an advanced version of open/closed intervals.
Comment: Note that the limit you've written doesn't exist at $a$ and $b$ as the function isn't defined in an open neighbourhood of those points.
Comment: Note that although differentiability at the end points is not necessary for the MVT to apply, it doesn't hurt. Theorems tend to provide the reader with all the *strictly necessary conditions*. Differentiability at the end points is nice, but not necessary.
Answer: $f(x)=\sqrt{a^2-x^2}$ on $[-a,+a]$ or $f(x)=\sqrt[3]{x}$ on $[0,b],~b>0$
Comment: $\Large\color{green}{✔}^\color{red}{+}$Babak S.
Comment: ${+1^{+1}}^{+ 1} \ddot\smile$
Answer: Another example is f(x)=x*sin(1/x)  on [0,1] note here there is no derivative at x=0 not even if we allow infinity.
Comment: By x*sin(1/x) you mean $x\cdot \sin\frac1x$? (It is kind of confusing since it seems like x with $*$ in exponent. The same expression would look somewhat better in math mode: $f(x)=x*\sin(1/x)$.)
Answer: The function must be continuous at the endpoints of the interval as otherwise you could just pick f(a), f(b) arbitrarily and get crazy results.


Intervals for music

Question: I have a question concerning the intervals on a piano
Between A flat and G, is it a Major 7th or Minor 7th? It seems both scales have the same note.
Comment: Intervals come in music on whatever instrument is played, not just piano. But - they're often easier to see and understand looking at a keyboard.
Answer: Intervals are not named for the major and minor scale, but the actual distance away from root note. Let's look at the typical intervals you would see with a root of A before we discuss what Ab would look like. Typically, when you talk about intervals with the root of A, you will have these notes:

A - Bb - B - C - C# - D - (D#/Eb)* - E - F - F# - G - G# - A

As you can see, we have 12 distinct notes and 7 distinct letter names. The distance away from the root in combination of the letter name of the note gives us the interval we want. In this case, we would treat the letter names the following way:

A - 1st/8th
B - 2nd
C - 3rd
D - 4th
E - 5th
F - 6th
G - 7th

Now as you can see, some of the groups that have two distinct notes for each letter which are B, C, F, and G. The smaller of these intervals will be minor and the bigger ones will be major. The other interval are perfect, but can also be raised to become augmented or lowered to be diminished with the exception of the 1st which can only be augmented.
Applying this to the notes we used above we get:

A  - P1
Bb - m2
B  - M2
C  - m3
C# - M3
D  - P4
(D#/Eb)* - A4/d5
E  - P5
F  - m6
F# - M6
G  - m7
G# - M7
A  - P8

Now we'll turn our attention back to what Ab to G would be. It's the exact same logic, but all notes are lowered by one and you'll see:

Ab  - P1
Bbb - m2
Bb  - M2
Cb  - m3
C   - M3
Db  - P4
(D/Ebb)* - A4/d5
Eb  - P5
Fb  - m6
F   - M6
Gb  - m7
G  - M7
Ab  - P8

So with this, you can easily see that Ab to G is a Major 7th.

* The D#/Eb is known as the tritone and can be considered either a 5th or a 4th depending on what you are doing.
Answer: A♭ to G is a major 7th: G would be the 7th step in A♭ major (the whole major scale being A♭ B♭ C D♭ E♭ F G).  The minor 7th to A♭ would be G♭, with the A♭ minor scale, rarely used by the way, being A♭ B♭ C♭ D♭ E♭ F♭ G♭.
Comment: Bear in mind there are 3 manifestations of minor scales - natural, harmonic and melodic, all with slight differences in notes 6 and 7.
Answer: G is eleven semitones higher than A-flat, so it's a major seventh interval.
(See the 'Main intervals' table here - https://en.wikipedia.org/wiki/Interval_(music) )
Answer: You are confusing the terms major and minor slightly. The interval is indeed a major 7th, but maybe you feel that in the melodic and harmonic minors, also, that interval features. When the interval goes from (in your example) Ab to G, that is known as a major 7th. It's one semitone larger than a minor 7th. The minor 7th is actually found in the natural minor scale of Ab minor as a minor 7th, going from Ab to Gb.
Comment: Major scales contain both major and minor 7th's, and so do harmonic, melodic, and natural minor scales. The lower note of the interval doesn't have to be the keynote of the scale. The terminology for the interval names is simply the Latin words "major" = large, "minor" = small.
Comment: @alephzero - thanks. I was trying to keep it simplistic as the OP referred to the maj and min scales of Ab specifically.
Comment: Yes the OP referred to scales, but the naming of intervals has nothing to do with scales. I can't think of any "scale" containing a diminished octave, or an augmented third, but those are both perfectly good descriptions of intervals which are use in real-world music notation.
Comment: @alephzero - there is some correlation - maj. 3 in maj. scale, min. 3 in min. scale.
Comment: @Tim the last time I counted, a major scale contained more minor thirds than major (4 and 3). That's not much of a correlation ;)
Comment: @alephzero - I hear what you say, but that maj.3 / min.3 from root is actually the definitive of maj./min. keys, isn't it?
Comment: I don't know if it is historically correct that major and minor scales were named after the intervals but there are plenty of other scales with major and minor thirds from the key note. Personally I'm inclined to consider "scales" and "intervals" as two different things, both of which involve relationships between pitches. One could imagine a piece of music constructed from "intervals" but without any concept of "scales" or "key" - e.g. everything you hear is a glissando starting and ending with a fade in/out from silence. https://en.wikipedia.org/wiki/List_of_musical_scales_and_modes
Answer: If A♭ is below G the interval A♭ to G is a major seventh. If G is below A♭, the interval G to A♭ is a minor second (or semitone).
Answer: If you are having trouble with intervals try lowering or raising both notes. Ab - G is the same interval as A - G# or more specific a Major Seventh. The Ab Major scale does have a G note in the scale.
Comment: COuld down voters please explain there votes in a comment?
Comment: In what way is saying Ab Major has a G wrong the leading tone of Ab Major is G. Your link does not contradict me at all. It says"The A-flat major scale consists of the pitches A♭, B♭, C, D♭, E♭, F, and G. Its key signature has four flats."
Comment: I read it too fast. I thought you were trying to say it didn't.
Comment: No downvote, but why should lowering or raising both notes make it any easier?
Comment: @Tim - I think Neil is probably trying to give the octave as the reference point, and then calculate a small offset from there.

Intervals for music


Set SSRS to automatically push Report Part Updates

Question: I am looking for a way to set header styles automatically in our reports.  Every report header is different although the Logo/Branding will be the same depending on which branch of the company is selected.
I was looking at using report parts in order to have a global report file which would hold each different branding style. This way, only one file needs changes made if there was an update down the road.  Again, the header logo/branding would then change based on the parameter passed designating the branch of the company the report was coming from.
Even using this method, I still have to go through each individual report to accept the updates to the report parts. Is there a way via setting or another method to have SSRS automatically accept the updated report part so that the idea of only having to visit the global styles report file would work?
To maybe put it more simply, I want to make report part changes in Report A then have Report B,C,D automatically accept these changes, so I don't have to go through them one by one to accept manually.
I tried setting up each style as a separate report part which worked by changing based on the parameter passed. Although once I changed the styles in the global report, I had to go through all the reports utilizing these styles, and accept the part updates.
Answer: I'm not sure that report parts are meant to be used like this (although it would seem an obvious thing to do!). They are, as far as I know, designed to be reusable components during the design of a report, rather than something that gets evaluated each time a report is run.
The only options I can think of are

Make all the header content dynamic based on a parameter (in your case the branch), so logos are pulled from the database at run time along with changes to text, fonts etc.

Use a subreport in place of your header. This will work as you want it to but it may cause issues when trying to get it to repeat on each page etc. You cannot use a subreport inside a header (as far as I know)

good luck!
One final note: Report Parts were deprecated from SSRS 2019 onwards, so if you plan on upgrading anytime soon you might run into problems with your current setup anyway.
See this for more details...
https://learn.microsoft.com/en-us/sql/reporting-services/report-design/report-parts-in-report-designer-ssrs?view=sql-server-ver16


Merge columns/rows?

Question: I have
chr12 100 105 'some' 'required' 'data'
chr12 105 120 'some' 'required' 'data'
chr12 120 130 'some' 'required' 'data'

I need to make them as
chr12 100 130 'some'|'some'|'some' 'required'|'required'|'required' 'data'|'data'|'data'

That is, merge overlapping rows and append from all other columns beside the first one. Sorry if I'm sounding vague, however I don't know how to describe this situation.
Looking for a Shell script because then I can quickly process the 20 files that I need to work with.
Comment: Are there always only 2 columns? A more complete example of input/output would be useful. Also good to make an attempt of your own before posting your requirement here.
Comment: There are only two columns. The inputs are actually genomic co-ordinates. They haven't been reported as one continuous region, but are reported as mentioned above (but bigger in number).
Comment: Hi, welcome to stack overflow, please put your previous comment straightly into your question post, and also for better clarification and prevetion getting downwotes, look at [mcve] and [how to ask](https://stackoverflow.com/help/how-to-ask), then feel free to edit your post. Thank you.
Answer: Yours is a horrible question, because it is vague and you got no example or code you've been trying.
That being said, this should do the trick:
Sub stackoverflow()

Dim row As Variant
Dim finish As Boolean

    Do
        For Each cell In Range("A1:A" & Cells(Rows.Count, "A").End(xlUp).row)

            row = Application.Match(cell.Value, Range("B1:B" & Cells(Rows.Count, "B").End(xlUp).row), 0)

            If Not IsError(row) Then
                Cells(row, 2).Delete xlShiftUp
                cell.Delete xlShiftUp
                Exit For
            End If

            finish = cell = Range("A" & Cells(Rows.Count, "A").End(xlUp).row)

        Next cell
    Loop Until finish = True

End Sub

Comment: I agree that the question is not well put and incredibly vague, because I don't know how to describe it well. However, I thank you for trying to provide me with a solution! Is that a python script that you have posted? Might take me some time to get it running. I'll let you know if it works!
Comment: No, its a VBA script. Hit ALT+F11 with your Excel open, create a new module, paste and run.
Comment: The script works when there are only two fields, however now I have another requirement... Kindly check out the edit to my original question, I hope it's clear what I need help with. ALSO I have no idea when it comes to VBA scripting!

Merge columns/rows?


Formula for triangulation (3 references + distances)

Question: I am trying to implement a function that will give me the GEO location (Lat,Long) given 3 GEO reference points and radius away from each point.
The signature for the function I'm looking for is:
public static GeoLocation Triangle(GeoLocation pos1, double r1, GeoLocation pos2,
                                   double r2, GeoLocation pos3, double r3)

As example, 3 friends meet up somewhere secret. Each one can only tell me where he/she lives (GeoLocation = lat,long) and how far they are meeting from their house (r = radius). Given 3 such reference points (from all 3 friends), I should have sufficient information to calculate this secret meeting point as a GeoLocation.
This problem is very similar to the mobile / towers problem where you triangulate a mobile by measuring individual signal strengths from a few towers.
I have tried to find formulas online for quite some time now, which is why I'm posting my question here on Stack Overflow.
I will appreciate it if you could help me fill in the formula (Triangle method) - Thanks.
Code I have so far:
public class GeoLocation
{
    private double _latitude;
    private double _longitude;

    public GeoLocation(double latitude, double longitude)
    {
        this._latitude = latitude;
        this._longitude = longitude;
    }

    //Tested and working!
    public double DistanceToKm(GeoLocation loc)
    {
        double lat1, lon1, lat2, lon2;
        lat1 = this._latitude;
        lon1 = this._longitude;
        lat2 = loc._latitude;
        lon2 = loc._longitude;
        var R = 6371; // Radius of the earth in km
        var dLat = deg2rad(lat2 - lat1); // deg2rad below
        var dLon = deg2rad(lon2 - lon1);
        var a =
            Math.Sin(dLat / 2) * Math.Sin(dLat / 2) +
            Math.Cos(deg2rad(lat1))*Math.Cos( deg2rad(lat2))*
            Math.Sin(dLon / 2) * Math.Sin(dLon / 2)
            ;
        var c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));
        var d = R*c; // Distance in km
        return d;
    }
}

Code which I think is not needed, but for what it's worth:
public static Coords ToCoord(GeoLocation pos)
{
    var x = Math.Cos(pos._longitude) * Math.Cos(pos._latitude);
    var y = Math.Sin( pos._longitude) * Math.Cos(pos._latitude);
    var z = Math.Sin(pos._latitude);
    return new Coords(x,y,z);
}

class Coords
{
    public double x;
    public double y;
    public double z;

    public Coords(double x, double y, double z)
    {
        this.x = x;
        this.y = y;
        this.z = z;
    }
}

Comment: Hi @roryap. This is not a matter of not working. I have tried to find the formula online but couldn't. I have also tried to derive it myself, with no success. I can tell you the formula is not simple (I have a degree in B.Science/Physics and another in B.Engineering). This is not 2D space, it's a 3D problem, involving Latitude & Longitude. I don't find your comment constructive at all. Please read my full question.
Comment: Holy crap.  How far away from the meeting place are these people living!?
Comment: At about 50miles, you get quite inaccurate values if you presume a 2D map. Also, the formulas don't work out then, you have to add a delta error, otherwise you won't get a solution. This makes the problem so much more complicated.
Comment: I reject your premise then.  If they each live about 50 miles away from the meeting place then they are going to be more than 50 miles away from each other.  In that case they aren't friends.  They are acquaintances at best.  Maintaining a friendship at that long distance over any amount of time would be improbable.
Comment: Additionally - if this meeting is so secret, why the hell are they telling you!?
Comment: Kidding aside - this question might receive better treatment from people that know math well.. like on math.stackexchange.com
Comment: This looks promising:  http://gis.stackexchange.com/questions/48937/how-to-calculate-the-intersection-of-2-circles
Comment: @Sam, Thanks Sam, It's a good start for me.
Comment: Thanks @Sam, You're right - I should have started my search on a Maths forum
Answer: Seems this is the solution after all.
https://gis.stackexchange.com/questions/66/trilateration-using-3-latitude-and-longitude-points-and-3-distances
... far more complicated than school geometry @DrKoch
Here is the Python solution:
yC = earthR *(math.cos(math.radians(LatC)) * math.sin(math.radians(LonC)))
zC = earthR *(math.sin(math.radians(LatC)))

P1 = array([xA, yA, zA])
P2 = array([xB, yB, zB])
P3 = array([xC, yC, zC])

#from wikipedia
#transform to get circle 1 at origin
#transform to get circle 2 on x axis
ex = (P2 - P1)/(numpy.linalg.norm(P2 - P1))
i = dot(ex, P3 - P1)
ey = (P3 - P1 - i*ex)/(numpy.linalg.norm(P3 - P1 - i*ex))
ez = numpy.cross(ex,ey)
d = numpy.linalg.norm(P2 - P1)
j = dot(ey, P3 - P1)

#from wikipedia
#plug and chug using above values
x = (pow(DistA,2) - pow(DistB,2) + pow(d,2))/(2*d)
y = ((pow(DistA,2) - pow(DistC,2) + pow(i,2) + pow(j,2))/(2*j)) - ((i/j)*x)

# only one case shown here
z = sqrt(pow(DistA,2) - pow(x,2) - pow(y,2))

#triPt is an array with ECEF x,y,z of trilateration point
triPt = P1 + x*ex + y*ey + z*ez

#convert back to lat/long from ECEF
#convert to degrees
lat = math.degrees(math.asin(triPt[2] / earthR))
lon = math.degrees(math.atan2(triPt[1],triPt[0]))

print lat, lon`


How can i make this algorithm more memory efficient?

Question: I have been working on this piece of code for a couple of days and it seems
to work just fine for search trees of relative small size, but working with higher ones gives segmentation fault.
I have tried to find the specific place where such error comes from by using printing flags, and it seems to break at the is_goal() function. But the code of that function can be assumed as correct.
So the problems seems to be a memory problem, that's why I have the queue in the heap, and also the Nodes that I am creating. But it still crashes.
Are there any more memory saving tricks that can be taking into account that I am not using? Or maybe there is a better way to save such nodes?
It is important to note that I need to use BFS (I can't use A* to make the search tree smaller).
Also if you need to know, the map is a hash table where I save the coloring of the nodes so I don't have duplicates when exploring (This is because the hash saves depending on the state information and not the Node information).
EDIT: i have been told to indicate the goal to accomplish, such is to find the goal state in the search tree, the goal is to be be able to iterate over
big problems like rubik 3x3x3, n-puzzle 4x4 5x5, tower of hanoi and such.To do so, the memory used has to be minimal since the search tree of such problems are really big, the final objective is to compare this algorithm with others like a*, dfid, ida*, and so on. I hope this is enough information.
  Node* BFS(state_t start ){

    state_t state, child;
    int d, ruleid;
    state_map_t *map = new_state_map();
    ruleid_iterator_t iter;
    std::queue<Node*> *open = new std::queue<Node*>();

    state_map_add( map, &start, 1);

    Node* n = new Node(start);
    open->push(n);

    while( !open->empty() ) {
        n = open->front();
        state = n->get_state();
        open->pop();

        if (is_goal(&state) == 1) return n;

        init_fwd_iter( &iter, &state );

        while( ( ruleid = next_ruleid( &iter ) ) >= 0 ) {
            apply_fwd_rule( ruleid, &state, &child );

            const int *old_child_c = state_map_get( map, &child );
            if ( old_child_c == NULL ) {
                state_map_add( map, &child, 1 );
                Node* nchild = new Node(child);
                open->push(nchild);
            }

        }

    }

    return NULL;
}

Comment: Please start your question with a succinct description of the goal to achieve, and give it a telling titel - `this` isn't.
Comment: You have a memleak with `open` and memleak with non returned `Node`. `std::queue> open;` would be a good start.
Comment: @greybeard thanks, i hope the edit i made is enough, i didn't change the title but explained in more detail my objective and the goal of the algorithm.
Answer: I see a number of memory leaks.
open is never deleted but maybe could allocated in the stack instead of in the heap.
std::queue<Node*> open;

More important none of the node you push in the queue are deleted this is probably the origin of very big memory consumption.
Delete the nodes that you remove from the queue and that you don't plan to reuse. Delete the nodes of the queue before your get rid of the queue.
Node* BFS(state_t start ){

    state_t state, child;
    int d, ruleid;
    state_map_t *map = new_state_map();
    ruleid_iterator_t iter;
    std::queue<Node*> open;

    state_map_add( map, &start, 1);

    Node* n = new Node(start);
    open.push(n);

    while( !open.empty() ) {
        n = open.front();
        state = n->get_state();
        open.pop();

        if (is_goal(&state) == 1) {
            for (std::queue<Node*>::iterator it = open.begin(); it != open.end(); ++it)
                delete *it;

            return n;
        }
        else {
            delete n;
        }

        init_fwd_iter( &iter, &state );

        while( ( ruleid = next_ruleid( &iter ) ) >= 0 ) {
            apply_fwd_rule( ruleid, &state, &child );

            const int *old_child_c = state_map_get( map, &child );
            if ( old_child_c == NULL ) {
                state_map_add( map, &child, 1 );
                Node* nchild = new Node(child);
                open.push(nchild);
            }

        }

    }

    return NULL;
}

Comment: Hi, tried this and keeps failing, the algorithm works fine for some cases but for bigger ones stills gives segmentation fault, but i will keep the advice you gave me: deleting the nodes and maintain the queue on the stack and the nodes on the heap. Thanks very much, i am going to try to write the algorithm from scratch to see if this helps me out.


$\Big(D\in X\;\land\; D\notin (X-Y)\Big) \implies D\in Y$. Why?

Question: Let $D \in X$. Why is this statement true? $$\Big(D\in X \;\land D\notin (X-Y)\Big) \implies D\in Y$$
I know that $D\in (X-Y) \equiv D\in X \land D\notin Y,\;$ but claiming $D\notin (X-Y) \implies D\in Y$ is like claiming "The cookie jar isn't in the kitchen therefore it must be in my room".
What am I missing?
Comment: Do we know that $D \in X$?
Comment: Yes @JimmyK4542
Answer: $$d \notin (X-Y) \iff \lnot(d \in X \land d\notin Y) \iff (d\notin X \lor d\in Y)$$ Since we know that $d\in X$, we know that $$\lnot \lnot (d \in X) \iff \lnot(d\notin X)$$ which, together with the first premise, it follows that  $d \in Y$.
Answer: This is not necessarily true, if $D\notin X$.
Of course, in the context from which you take it, you already assume that $D\in X$, so it is necessarily the case that $D\in Y$.
Comment: What? No, that comment thread wasn't big at all. When you reach 20 comments you can start talking about "not small".
Comment: Oh I understand now completely. Thanks again
Comment: You're welcome.
Comment: At some point I thought I understood (but didn't). btw, I've opened a new question because the thread got a bit big ..
Answer: If $D \in X$ and $D \not\in Y$, then by definition $D \in (X-Y)$.
But since we know that $D \not\in (X-Y)$ we must have either $D \not\in X$ or $D \in Y$.
Since you said you know that $D \in X$, then we are left with $D \in Y$.
The statement $D \not\in (X-Y) \iff D \in Y$ is like saying "Since the cookie jar is not in any of the other rooms in the house, it must be in my room" (Assuming the cookie jar is in the house).
Comment: Is this statement alone true: $D\notin (X-Y) \implies D\notin X \lor D\in Y$?
Comment: Yes it is. In fact, the implication can go in both directions.
Answer: Since you already answered that we are assuming $D \in X$, then suppose $D \not \in (X - Y)$.  Note that $X - Y = X \cap Y^{c}$.
So we have $D \not \in X - Y \implies D \not \in X \cap Y^{c}$.  But $D \in X$, and $X = (X \cap Y) \cup (X \cap Y^{c})$, so if $D \in X$, then $D$ must be in one of the two sets $(X \cap Y)$ or $(X \cap Y^{c})$.
Since we already ruled out that $D \in (X \cap Y^{c})$, then it must be that $D \in (X \cap Y)$, which implies $D \in Y$, as desired.
Answer: $D \notin (X-Y)$ if and only if $\neg (D \in X \wedge D \notin Y)$. Because of De Morgan's laws
$$\neg (D \in X \wedge D \notin Y) \iff D \notin X \vee D \in Y$$
If we suppose that $D\in X$, than $D \in Y$ must be true.


Volume of tetrahedron (integral). What function do I have to integrate?

Question: Let $A = \left \{ (x,y,z)\in [0, 1]^{3}| x + y + z \leq 1 \right \}$. Calculate the volume.
So I found the following boundaries for the integrals:

$0 \leq z\leq 1$
$0 \leq y\leq 1-z$
$0 \leq x\leq 1-y-z$

The integral is $\int_{0}^{1}\int_{0}^{1-z}\int_{0}^{1-y-z}f(x,y,z)dx dy dz$. But what is f(x,y,z)?
Answer: You are integrating $f(x, y, z) =1$.
Comment: I think I understand it. Integrating 1 is just giving the volume of the domain we want to integrate. For example if I want to know the volume/length of an real interval [a, b] I can integrate f(x) = 1 with respect to the boundaries a and b.
Comment: Why? Is this always the case, if there is no f(x,y,z) given?
Comment: @Aurelius Yes that's right.


How to check if a member chosen from the getUser option has a specific role in discordjs

Question: I am making a command with my bot that first checks if a targeted player has a specific role. the problem is that it fails to figure out if the person has the role or not, it always defaults to not having it.
<code>            // Points remove command
            if (interaction.commandName === 'points-remove') {
                const player = interaction.options.getUser('target');
                const playerid = player.roles.cache.has('1136220928666251325');
                const pToRemove = interaction.options.getInteger('points');
                const sqlQ = `UPDATE playerdata SET points = points - ${mysql.escape(pToRemove)} WHERE playerid = ${mysql.escape(player.id)}`;
                if (playerid) {
                    con.query(sqlQ, (error, result) => {
                        if (error) throw error;
                        interaction.reply({ content: `${player} has lost ${pToRemove} succesfully!`, ephemeral: true });
                    });
                } else {
                    interaction.reply('Cannot remove from unregistered player!');
                }
            }
</code>
Basically, if the person doesn't have the 'registered' role, the command won't do anything. However it always goes to the else statement.
(I apologize for the formatting of the code, it copy pasted terribly)
Comment: Hi,
it enters the else case if you have no `playerid`. The `playerId` is taken from the `player.roles.cache`. I assume, because you are using a cache, that the cache is filled async, but you are reading from it synchron. Maybe you are accessing the cache before it is filled.
Can your provide the code, where and when you fill the `player.roles.cache`.

Its often a better to use an async cache implementation like [here](https://stackoverflow.com/a/64441185/5247706).
Answer: User's don't have roles! You're code is absolutely right, except for the following line:
<code>// ❌
const player = interaction.options.getUser('target');
</code>
Changing the above code to the following should fix your issue!
<code>const player = interaction.options.getMember('target');
</code>
Comment: Thank you so much that one problem was stumping me and I couldn't find a single thread talking about the getUser option!!


List files that exist only on a given directory?

Question: I am trying to list out the files which are only in directory ./a/b or ./a/d. Now I am explicitly specifying by using (-d && $_ =~ "b") || (-d && $_ =~ "d"). Is there any way I can put needed folders in an array?
use File::Find;

my $filename = "h*.txt";
print ("Now it's:", $filename);

find({
  wanted => \&wanted,
  preprocess => \&dir_preprocess,
}, './a');

sub dir_preprocess {
    my (@entries) = @_;

    #my @tmparr=("d","b"); This isn't working

    if ( $File::Find::dir eq './a' ) {
        @entries = grep { (-d && $_ =~ "b") || (-d && $_ =~ "d")  }@entries;
    }
    return @entries;
}

my @mylist;

sub wanted{
    if($_ =~ $filename) {
    push(@mylist, $_);
    }
}

print ("It's:", @mylist);

Comment: Can you show us what @entries array contains?
Comment: Yeah I need files only from a/b and a/d
Comment: `$_ =~ "b"` tests whether the string contains a `b`, not whether it is equal to `b`. To do that, you need `$_ eq 'b'`. The `=~` operator treats its right-hand argument as a regular-expression.
Answer: You can use | as "or" in a regex expression. (-d && $_ =~ /(b|d)/) would match either b or d. You could put the names in an array and then use join to generate the regex you need.
You might want to do things like prepend the path upto that depth, else you might get at different levels of the heirarchy. Also you can add $ at the end to indicate that it comes at the end.
Comment: @karate_kid you can put the folders in an array and use join `("|", @the_array)` to get the regex you need. More info on join [here](http://perl.about.com/od/perltutorials/qt/perljoin.htm)
Comment: Hi, I tried to do that. But now it's not giving me correct result.
Comment: Now I am trying "a|b[0-9]+".. So it's working fine, but it's also pushing folder name 'b123' in list, which it shouldn't.
Comment: thats because `[0-9]+` matches 123, what do you want that to do exactly?


how to speed up this code? calculus iterating through rows and cols of a matrix

Question: I have a piece of code which performs calculations on a matrix by iterating through its rows and columns. The piece of calculus performed is a cosine distance measure, with a code I found on Internet (could not retrieve the link right now).
There can be 10,000 rows and col. The matrix is symmetric so I just need to iterate half of it. Values are float.
The problem: it is very slow (will take 3 to 6 hours it seems). Can anyone point me to improvements? Thx!
Note on the code: it uses an abstract class for flexibility: this way, the cosine calculation defined in a separate class could be easily replaced by another one.
The code:
import Jama.Matrix;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.concurrent.ExecutionException;

public abstract class AbstractSimilarity {

    HashSet<Triple<Double, Integer, Integer>> set = new HashSet();
    public ArrayList<Thread> listThreads = new ArrayList();

    public void transform(Matrix matrixToBeTransformed) throws InterruptedException,
ExecutionException {

        int numDocs = termDocumentMatrix.getColumnDimension();

        Main.similarityMatrix = new Matrix(numDocs, numDocs);

        System.out.println("size of the matrix: " + numDocs + "x " + numDocs);

        //1. iteration through all rows of the matrixToBeTransformed
        for (int i = numDocs - 1; i >0 ; i--) {
            System.out.println("matrix treatment... " + ((float) i / (float) numDocs * 100) + "%");

            //2. isolates the row i of this matrixToBeTransformed
            Matrix sourceDocMatrix = matrixToBeTransformed.getMatrix(
                    0, matrixToBeTransformed.getRowDimension() - 1, i, i);

            // 3. Iterates through all columns of the matrixToBeTransformed
//            for (int j = 0; j < numDocs; j++) {
//                if (j < i) {
//
//                    //4. isolates the column j of this matrixToBeTransformed
//                    Matrix targetDocMatrix = matrixToBeTransformed.getMatrix(
//                            0, matrixToBeTransformed.getRowDimension() - 1, j, j);

                    //5. computes the similarity between this given row and this given column and writes it in a resultMatrix
//                    Main.resultMatrix.set(i, j, computeSimilarity(sourceDocMatrix, targetDocMatrix));
//                } else {
//                    Main.resultMatrix.set(i, j, 0);

//                }
//
//            }
        }

The class which defines the computation to be done:
import Jama.Matrix;

public class CosineSimilarity extends AbstractSimilarity{

  @Override
  protected double computeSimilarity(Matrix sourceDoc, Matrix targetDoc) {
    double dotProduct = sourceDoc.arrayTimes(targetDoc).norm1();
    double eucledianDist = sourceDoc.normF() * targetDoc.normF();
    return dotProduct / eucledianDist;
  }

}

Comment: Have you profiled to see what part of your algorithm takes the longest time? Simply adding `new Date().getTime();` in the beginning/end of operations and them subtracting them can give you a nice insight.
Comment: Is this a homework project? Can you not use math software such as MatLab?
Comment: This is a professional project in academia and I need to use Java for it - bc of my own limitations I'm afraid!
Comment: I also recommend using JVisualVM to see if its memory bound and the GC has to do a lot of work. Then you could for example allocate the doubles in your CosineSimilarity class up front, to see if that reduces memory fluctuation.
Answer: You appear to be dealing with a n^3 algorithm.  n^2 because you're filling a (half) matrix.  Times n again because the methods to fill each element(dot product/fnorm) take time n.  The good news is that because the calculations don't depend on each other, you could multithread this to speed it up.
public class DoCalc extends Thread
{
  public Matrix localM;
  int startRow;
  int endRow;
  public DoCalc(Matrix mArg, int startArg, int endArg)
  {
    localM=mArg;
    startRow=startArg;
    endRow=endArg;
  }

  public void doCalc()
  {
    //Pseudo-code
    for each row from startRow to endRow
      for each column 0 to size-1
        result[i][j] = similarityCalculation
  }
  public void run()
  {
    doCalc();
  }
}

public void transform(Matrix toBeTransformed)
{
  int numDocs = termDocumentMatrix.getColumnDimension();

  Main.similarityMatrix = new Matrix(numDocs, numDocs);
  Vector<DoCalc> running = new Vector<DoCalc>();
  int blockSize = 10;
  for (int x = 0; x < numDocs-1;x+=blockSize)
  {
    DoCalc tempThread = new DoCalc(toBeTransformed,x,(x+blockSize>numDocs-1)?numDocs-1:x+blockSize);
    tempThread.start();
    running.add(tempThread);
  }

  for (DoCalc dc : running)
    dc.join();

}

Important notes:
This is a very naive implementation.  If you try to run it with arrays of your size, it will spawn 1000 threads.  You can either fiddle with the blockSize or look into thread pooling.
At best this will give you a multiple times increase in speed, 4x etc.  If you want order of magnitude gains, you will need to properly profile and/or change your algorithm to something more efficient.  Given the task you're trying to perform(running a relatively expensive task on each element in a Matrix), the latter may not be possible.
Edit: Multithreading will only increase speed significantly if you are cpu bound and have a multicore cpu with cores sitting relatively idle.
Comment: thx! a multithreading solution with a fixed pool of  threads speed up my code by a factor 3. It still took 3h to complete on a 9400x9400 matrix. Now, I am investigating solutions to get way more speed! :-) => http://stackoverflow.com/questions/9550486/tutorials-or-books-on-kernel-programming-for-opencl


Proving $f$ is continuous on $\mathbb{Q}$

Question: Let $x,y,z \in \mathbb{Q}$. Now,$\mathbb{Q} - \{x\}$ and $\mathbb{Q}-\{y,z\} $ are countable dense subsets without endpints, so they are $(g)$homeomorphic. Is
$f:\mathbb{Q} \rightarrow \mathbb{Q}$ defined by $f(\{y,z\}) = \{x\}$. and
$f = g$ on $\mathbb{Q}-\{y,z\}$ continuous.
Comment: What's $\{y, z\}$ ?
Comment: @EnjoysMath: Some set of two distinct rationals.
Answer: Assume that $y<z$, and let $\alpha$ be any irrational less than $x$. Let
$$\begin{align*}
L&=\{q\in\Bbb Q:q<y\}\;,\\
C&=\{q\in\Bbb Q:y<q<z\}\;,\\
R&=\{q\in\Bbb Q:z<q\}\;,\\
L'&=\{q\in\Bbb Q:q<\alpha\}\;,\\
C'&=\{q\in\Bbb Q:\alpha<q<x\}\;,\text{ and}\\
R'&=\{q\in\Bbb Q:x<q\}\;.
\end{align*}$$
It's possible to choose $g$ so that it's an order-isomorphism that maps $L$ onto $L'$, $C$ onto $C'$, and $R$ onto $R'$. Now let $\langle q_n:n\in\Bbb N\rangle$ be any sequence in $C$ converging to $y$; then $\langle f(x_n):n\in\Bbb N\rangle$ converges in $\Bbb R$ to $\alpha$ and hence has no limit in $\Bbb Q$. In particular, it does not converge to $x=f(y)$, so $f$ is not continuous.
Comment: :so there is no a continuous map sends $y,z$ to $x$ and bijective on the rest.
Comment: @Sobhi: That's a different question. I just showed that the $f$ in your question does not have to be continuous. I think that with some work I can probably construct a continuous $f$ taking $y$ and $z$ to $x$ that is a homeomorphism on $\Bbb Q\setminus\{y,z\}$.
Comment: @Sobhi: And I now see that you've asked it as a separate question. I was able to construct such an $f$, and I've answered the other question with it.


The meaning of "average annual compound rate"

Question: I am currently working on this problem and I am having a hard time finding the right number.

A mutual fund advertises that average annual compound rate of returns for various periods ending Dec 31 2005 are as follows:  10 yrs = 13%, 5 yrs = 17%, 2 yrs = 15% and 1 yr = 22%.  a), find the average annual compound interest rate of return for the period Jan 1 1996 to Dec 31 2000.  b), find the annual rate of return for calendar year 2004.

a), My claim is that from 1996 to 2000 there are 5 conversion periods with 17%, so the number is
$$\sqrt[5]{1.17}-1 \approx 3.199%$$
but the answer is supposedly approximately 9.1%.
b), In the 2004 period, there is only one conversion period, so the return interest should be the same as the claimed interest rate which is 22%.
But the answer is supposedly 8.4%
Can some one help?
Answer: Note that the stated returns are for periods ending in 2005 so the 1 year return is for 2005 only and not 2004. Similarly, the 5 year is for the period of 2001-2005 and not 1996-2000. Please be careful and read the dates in the question or else you will be fooled here.
It may help to consider the following interpretation of the data given in annual returns:
Return in 2005: 22%
Return from 2004 to 2005: 15%
Return from 2001 to 2005: 17%
Return from 1996 to 2005: 13%
For a which is asking for the returns from 1996 to 2000:
Note that the returns stated are as of the end of 2005 which means the 5 year return given would be 2001-2005 and so to get the returns for 1996-2000 you would have to use the 10 year return and 5 year return to determine the new average. In this case, the 10 year average is 13% and the 5 year is 17% which means that the first 5 years had to be low enough to bring the average down by 4% which would be the simpler way to see a ~9% average return though if you had to you could compute the following:
$\frac{(1.13)^{10}}{(1.17)^5}^{1/5} \approx 1.0913675213675213675213675213675$ which is 9.1%
For b which is asking for the return in 2004:
Same as a in a way where the return is the year before the 1 year return. There is the one year of 22% and the 2 year annual return of 15% where to find the other return, one could just take $\frac{1.15^2}{1.22}-1 \approx 1.0840163934426229508196721311475$ which is 8.4%. You are ignoring the dates in the question. The 1 year return would be just 2005 and the 2 year would be 2004 and 2005 combined. If you want 2004, you have to deduce this which is the part you are missing.
Comment: Ah, that's what I was calculating.  It made things far clearer.  So, it's like finding the average of a smaller group given the entire group average, but geometrically.  Thanks!
Comment: So, let me get this straight.  The total amount that can be earned in 10 yrs from 1996 to 2005 has a return rate of $(1.13)^{10}$.  That of  2000 to 2005 has $(1.17)^5$.  So when a problem like this says "average" do they mean the geometric mean rather than the arithmetic?  Is that why we take it to the $1 \over 5$ power?
Comment: In finance, usually average annual return is a geometric mean which is why the computation is a product and root instead of addition and division that would give a 9.0% return in the arithmetic case since one could just subtract the difference to get the average for the other 5 years.
Comment: Using this logic, the other problem has an average rate of $\sqrt[9]{\frac{1.13^{10}}{1.22}} \approx 1.12$. so would the answer not be 12%?
Comment: No, that would be the 9 year average annual return for 1996 to 2004 which isn't asked anywhere.
Comment: Yes, precisely.


Why the same JavaScript Code giving different outputs?

Question: Here is a piece of code :

// -------- Sample 1 ---------------
var funcs = [];
for (var i = 0; i < 3; i++) {
    funcs[i] = function() {
        console.log("My value: " + i);
    };
}
for (var j = 0; j < 3; j++) {
  funcs[j]();
}

// --------- Sample 2 --------------
var fun = [];
for(var i = 0;i < 3; i++) {
    fun[i] = function() {
        console.log('values is '+ i);
    }
}
for(var i = 0; i < 3; i++) {
    fun[i]();
}

Both the sample codes are same except the variable names. But it's giving different output. The output of the above code is :
My value: 3
My value: 3
My value: 3
values is 0
values is 1
values is 2

Can any one figure out why its happening ?
DEMO
Comment: Because variable names are important?
Comment: Try `console.log(i, j)` in the loop and see what you get.
Comment: @Bergi thnks that hepled :)
Answer: var is hoisted, so to the interpreter, the first part's i actually looks more like this:
var funcs = [];
var i;
for (i = 0; i < 3; i++) {
  funcs[i] = function() {
    console.log("My value: " + i);
  };
}
// At this point, the for loop has finished; `i` has the value of 3 now:
for (var j = 0; j < 3; j++) {
  // Each function retrieves the value of i and displays it
  // and since `i` is 3, each function displays 3:
  funcs[j]();
}

In your second sample (which is somewhat invalid JS because i gets declared twice), i gets reassigned to values 0, 1, and 2 while looping over the function that displays i.
Comment: rite. Then why doesn't the same happen with the sample 2 code?
Comment: Because in your second sample, `i` gets reassigned to values 0, 1, and 2 *while looping over the function that displays `i`.*
Comment: No, the first sample, while looping over executing the functions, uses `j`, not `i`. If this was not immediately apparent to you, which is perfectly understandable, it should serve as a nice reminder why not to use single-letter variable names :)


mod_rewrite to redirect to different virtualhost

Question: The hostname where I want to redirect to looks like:
<VirtualHost *:80>
       ServerName my.dav.hostname.com
       ErrorLog /var/log/open-xchange/dav-err.log
       TransferLog /var/log/open-xchange/dav-access.log
       <Proxy />
               Order allow,deny
               Allow from all
       </Proxy>
       ProxyPass / ajp://localhost:8009/servlet/dav/ smax=0 ttl=60 retry=5
</VirtualHost>

I want to do something like if someone goes to a URL my.hostname.com/dav, I want it to be rewritten to my.dav.hostname.com.. If the client goes to a URL other than /dav, he should not be redirected.
<VirtualHost *:80>
       ServerName my.hostname.com
       ErrorLog /var/log/open-xchange/dav-err.log
       TransferLog /var/log/open-xchange/dav-access.log
       ..
       ..
</VirtualHost>

I'm clueless on how I should proceed.
Something like this doesn't work:
RewriteEngine on
RewriteRule /servlet/webdav.infostore http://my.dav.hostname.com [L,NE,QSA]

As it actually redirects to my.dav.hostname.com which I don't want. What I want is for apache to transparently do it for me.
Answer: This should work:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^my.dav.domain.com [NC]
RewriteRule ^/dav/(.*)$ http://my.dav.domain.com/$1 [R=301,NC]

Personally I wouldn't use your subdomain structure though. It's better to use dav.subdomain.domain.com over subdomain.dav.domain.com.
Comment: I don't want a a redirect, I want apache to do it transparently. Sorry, I wasn't clear enough earlier.
Answer: If you want apache to do this transparantly (ie. the URL in the browser must not change) you could just simply mount your DAV servlet in the other server too:
ProxyPass /dav/ ajp://localhost:8009/servlet/dav/ smax=0 ttl=60 retry=5

Comment: That's not gonna work because then all requests starting going to dav servlet. I also tried it to add it under `<Location /dav`, but it seems, it's not possible


Mensagens Firebase em Portugues

Question: Fiz o cadastro de usuários pelo Firebase e após a realização do cadastro é enviado para o e-mail para o usuário validar o acesso. Porém, as mensagens do Firebase estão em Inglês. Existe a possibilidade para ficar em português essas mensagens?
Answer: Você pode fazer a customização de mensagens através do console do Firebase.
Tais alterações podem ser feitas nas opções abaixo:

Verificação de e-mail
Redefinição de senha
Alteração de e-mail
Verificação por SMS

Para configurar seu projeto do Firebase de forma que ele use um gerenciador personalizado de ações de e-mail siga as instruções abaixo:

Abra seu projeto no Firebase console.
Vá para a página Modelos de e-mail na seção Auth da sua aplicação.
Em qualquer uma das entradas Tipos de e-mail, clique no ícone de
lápis para editar o modelo de e-mail.
Clique em Personalizar URL acionável e especifique o URL do
gerenciador personalizado de ações de e-mail.

Para mais informações acesse: Criar gerenciadores de ações de e-mail personalizados
Answer: A solução foi adicionar na Action URL lang=pt

Mensagens Firebase em Portugues


standardized residuals GARCH

Question: I am having a hard time understanding ACF and PACF. I estimated a GARCH(1,1) model and now I am checking its standardized residuals. This is what I get:

I can not really understand why the lag 0 has p-value=1. Also, the Ljung-Box test on std residuals is OK.
Answer: These are not $p$-values, these are estimated autocorrelations $\hat\rho(h)$ for $h=0,1,\dots,10$. $\hat\rho(0)=\widehat{\text{Corr}}(X_t,X_{t-0})=1$, obviously, thus the value of $1$ at lag $0$. The Ljung-Box test looks at lags other than zero, and these look fairly OK, so no wonder the result is "OK", as you put it.

standardized residuals GARCH


Animate UICollectionView items on constraint change in custom layout

Question: I'm using a custom UICollectionview Layout that displays the items in a circle. On a swipe up I reset the constraints on my collectionview and animate those constraint changes. I would like my items to animate with the constraint change so it's one smooth experience.
I get them to animate but only after the constraint change (I think), it looks messy and strange, check the screencast out here: http://cl.ly/ZmA0
This is the code in the swipe gesture method:
<code>
- (void)foo:(UISwipeGestureRecognizer *)gesture {
    [self.view layoutIfNeeded];

    [self.collectionView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(self.view.mas_width);
        make.height.equalTo(self.collectionView.mas_width);
        make.top.equalTo(self.view.mas_top).offset(50);
    }];

    [UIView animateWithDuration:1.0 animations:^{
        [self.view layoutIfNeeded];
    }];

    [self.collectionView performBatchUpdates:^{
        CircleLayout *layout = (CircleLayout *)self.collectionView.collectionViewLayout;
    } completion:nil];
}
</code>
Any suggestions?
Answer: I'm not sure what MASConstraintMaker is (and the video is not working).
But within the performBatchUpdates block you are getting the collection view layout. What are you doing with it? it unused. Maybe that can point you to the right solution.


Calling a grandparent JS function that includes jquery from a nested iFrame. D7

Question: I'm calling the grandparent_func from a second-level nested iframe like so.
This works in a non-Drupal environment, but am getting the following errors when running in drupal. (yes. I did remember to include the jquery file ;-)
parent.parent.grandparent_func( Date.now(), Date.now());

ERRORS:
For the following, I get a "TypeError: $ is not a function" error

So, I enclosed jquery like so to make it drupal-friendly and get:
TypeError: parent.grandparent_func is not a function

For good measure, I double enclose it with jquery's ready function.
TypeError: parent.grandparent_func is not a function

Any thoughts?
Thanks.
Answer: Introducing a closure around the whole function (as in your 2nd and 3rd examples) will take it out of the global scope, so it won't be available on the window, and subsequently the iframe's parent (which are the same thing).
What you're looking for is more like:
function grandparent_func() {
  (function($) {
    $("#fancy_regit_link").attr("href", "/my/actual/path");
    $("#fancy_regit_link").trigger('click');
  })(jQuery);
}

That makes sure grandparent_func is global, while still providing you the jQuery object.
Comment: This worked beautifully, Clive. Thanks. I have a feeling I'm going to be putting these all over the place now. This probably will create havoc when I take it back out of drupal. By chance, Do you know if there's a quick way to make that wrapper NOT a problem. I don't really understand what it's doing. Thanks again.
Comment: No need to worry, that's nothing to do with Drupal as such it's a simple [anonymous function](http://stackoverflow.com/questions/1140089/how-does-an-anonymous-function-in-javascript-work). It'll work the same outside of Drupal as it does inside, your code won't need to change


Test of question

Question: For each natural number $n$, let $\displaystyle \sum_{k=1}^{\infty}a_k(n)$ be a convergent series. If for each k, $\displaystyle \lim_{n \rightarrow \infty}a_k(n)=a_k$, and $\displaystyle \vert a_k(n)\vert \leq M_k$ for all n where the series $\displaystyle \sum_{k=1}^{\infty}M_k$  converges, then
$$ \displaystyle \lim_{n \rightarrow \infty} \sum_{k=1}^{\infty}a_k(n)  = \ \  \sum_{k=1}^{\infty}a_k $$
Comment: This is dominated convergence theorem applied to the counting measure on $\Bbb N$.
Answer: This is also known as the Weierstrass M test.
See https://en.m.wikipedia.org/wiki/Weierstrass_M-test
Comment: Ok guy's , I was testing the Math Jax Resources!

Test of question


Editable field in view to display editable form only

Question: I'm using the Editable Views module to create a view in which the user can edit the values of numerous fields.
Currently picking an editable table formatter and adding an editable field results in showing the current value of the field above and an editable form below it.
I would like to show only the form with the current value editable, is it possible?
If its possible with another module, please feel free to suggest.
Answer: I was informed lately that another module fits better my requirements so instead of Editable Views, I had to use editablefields module.
Editable Fields provides you with an editable formatter which allows you to display the field as an editable form only.
Unfortunately it appears to be only on alpha2 for Drupal 7, but seems ok for my expectations.
Comment: Was gonna suggest it. Great module.


For $x: (1 \to b)$ where $a$ & $b$ are co prime, why is $ax \bmod b$ distinct

Question: So, out of curiosity, I was wondering why $x (1 \to b)$ where $a$ & $b$ are co prime, why is $ax \bmod b$ distinct.
For example, let $a = 5$, and $b= 8$:
$\begin{array}{c|c|c}
x & 5x & 5x\bmod 8 \\ \hline
 1 &  5 & 5 \\
 2 & 10 & 2 \\
 3 & 15 & 7 \\
 4 & 20 & 4 \\
 5 & 25 & 1 \\
 6 & 30 & 6 \\
 7 & 35 & 3 \\
 8 & 40 & 0 \\
\end{array}$
As you can see $5x \bmod 8$ is always distinct. Why?
Answer: This is basically equivalent to saying "you can divide by $a$ (mod $b$)", since these values all being distinct means there's only one solution to $ax\equiv c$ mod $b$.
This is true because if $a$ and $b$ are coprime, there are integers $n,m$ such that $an+bm=1$. Then $anx=x-bmx\equiv x$ (mod $b$). If $ax$ and $ay$ were the same mod $b$, then $anx$ and $any$ would also be the same mod $b$, but since $anx\equiv x$ and $any\equiv y$, $x$ and $y$ must also be the same.
Comment: Hi, I'm a little confused by what you meant by it being equivalent to diving by a mod b and the logic that follows. Could you explain that a little more please?
Comment: The point is that if the values weren't all distinct, you wouldn't be able to divide by $a$, because you would have some $x,y,z$ for which $ax\equiv ay\equiv z$ mod $b$, and then $z/a$ mod $b$ is not defined, because it could be $x$ or $y$.
Comment: $an+bm=1$ is Bezout's lemma.
Answer: Suppose $ax\equiv ay\pmod{b}$, with $1\le x\le b$ and $1\le y\le b$. Without loss of generality, we can assume $x\ge y$. Then
$$
a(x-y)\equiv0\pmod{b}
$$
that is, $b\mid a(x-y)$; since $a$ and $b$ are coprime, we conclude that
$$
b\mid (x-y)
$$
but $0\le x-y<b$, so we only have one possibility, namely $x-y=0$.
In a slightly different way, we can use Bézout's identity: find $u$ and $v$ such that $ua+vb=1$. Then
$$
uax=(1-vb)x=x-vbx\equiv x\pmod{b}
$$
Since from $ax\equiv ay\pmod{b}$ we get $uax\equiv uay\pmod{b}$, we conclude $x\equiv y\pmod{b}$.
Comment: thank you, great answer. One question, how did you get the first line, the assumption?
Comment: @AlessandroFarace You want to show that $ax$ gets (modulo $b$), distinct values; so we try and see what happens if two values are the same.
Answer: The Fundmental Theorem of Arithmetic (FTA): For non-zero integers $d,e,f$ if $f$ divides $de$ and $f$ is co-prime to $d$ then $f$ divides $e.$
Let $a, b$ be co-prime positive integers and let $x,x'$ be integers with $0\leq x<x'\leq b-1.$ Suppose  $ax\equiv ax' \pmod b.$ Then $b$ divides $a(x'-x)$ with $b$ co-prime to $a$ and with $x'-x\ne 0.$. So by the FTA, $\;b$ divides $x'-x.$ But $1\leq x'-x\leq (b-1)-0=b-1$ so $b$  cannot divide $x'-x.$  So  supposing $ax\equiv ax'\pmod b$ leads to absurdity.
The FTA is usually presented by first proving that if $f,d$ are non-$0$ co-prime integers then there exist integers $x,y$ with  $xf+yd=1.$ Then $y\cdot \frac {de}{f}=$ $\frac {(yd)e}{f}=$ $\frac {(1-xf)e}{f}=$ $ -xe+\frac {e}{f}\in \mathbb Z,$ so $\frac {e}{f} \in \mathbb Z.$


Cannot decrypt OPEN-SSL AES 128 ECB encrypted string using C# - The input data is not a complete block

Question: After using current Open SSL command (decrypt content from file "encrypted.msg"):
openssl enc -d -aes-128-ecb -in "C:\encrypted.msg" -out "c:\temp\decrypted.msg" -K "e2fc714c4727ee9395f324cd2e7f331f" -nopad

I get a new file where the decrypted content is the same as the original.
If a try to decrypt the same encrypted file content from C# (NET 7)
I always get an exception: ... The input data is not a complete block. ...
This is my decrypt Code

 private static string GetHASH(byte[] RawBytes, HashAlgorithm AlgoritmoDiHASH)
 {
     if (RawBytes is not { LongLength: > 0 }) return "";
     var bytes = AlgoritmoDiHASH.ComputeHash(RawBytes);
     var builder = new StringBuilder();
     foreach (var t in bytes)
     {
         builder.Append(t.ToString("x2"));
     }

     return builder.ToString();
 }

public static string GetMd5(string rawData)
{
    if (string.IsNullOrEmpty(rawData))
    {
        throw new Exception();
    }

    return GetHASH(Encoding.UTF8.GetBytes(rawData), MD5.Create());
}

  public static byte[] AESByteArrayDecryption(byte[] encryptedBytes, string key, CipherMode cipherMode = CipherMode.CBC, PaddingMode paddingMode = PaddingMode.PKCS7, int blockSize = 128, int keySize = 256)
  {
      if (string.IsNullOrEmpty(key))
      {
        throw new Exception("Chiave di decrittazione non valida");
      }

      if (encryptedBytes.LongLength == 0)
      {
         throw new Exception("Dati da decrittografare non validi");
      }

      var keyB = new byte[32];
      var tmp = Encoding.UTF8.GetBytes(key);
      Buffer.BlockCopy(tmp, 0, keyB, 0, Math.Min(tmp.Length, 32));

using (var rm = Aes.Create())
{
    rm.BlockSize = blockSize;
    rm.KeySize = keySize;
    rm.Mode = cipherMode;
    rm.Padding = paddingMode;

    using (var dencryptor = rm.CreateDecryptor(keyB, (cipherMode != CipherMode.ECB ? new byte[blockSize / 8] : null)))
    {
        using (var dencryptStream = new MemoryStream(encryptedBytes))
        {
            using (var cryptoStream = new CryptoStream(dencryptStream, dencryptor, CryptoStreamMode.Read))
            {
                var decryptBytes = new byte[encryptedBytes.Length];
                cryptoStream.Read(decryptBytes, 0, decryptBytes.Length);
                return decryptBytes;
            }
        }
    }
}
  }

 var cipherMode = CipherMode.ECB;
 var paddingMode = PaddingMode.None;
 var blockSize = 128;
 var keySize = 256;
 var pwdMD5 = CryptographyUtil.GetMd5("abcd");

   var decriptedData = CryptographyUtil.AESByteArrayDecryption(criptedData, pwdMD5, cipherMode, paddingMode, blockSize, keySize);
   var decriptedDataString = Encoding.UTF8.GetString(decriptedData);

String to derive MD5 = "abcd"
Encrypted File
j›}2}0‹ÂN_'-#€6µC÷úð+|™wyh"–Ú`WŽ µÄîôZÌ¢Cü'Êœœ4zw=-á¶(ör»"qÛ‰ ÀðMl}Ï"%ðŸ9]Ë° $"üÌR†E)zÆÝ'¦"J4-¸–éÇ  æ&þ`:¯ê—ç‹ß<+K/´ö#Ë''Âé·_NFò'øCUk³`Ú¾µh-ïQõ£®®èá}R±}å,M\™û‡Í°öç/–ÌàOÙ"ÒšßN¥þÀP
ø'†èì—Nh
#Ä›á•ÆöjȦJæËãJ'^_«.ÂK¯'ýR*ËdîdtÍB¶ÆpçZÑŸ·oM°Ž7I}ŠÏáˆjS½Ð4Æ=ßÙ¿ré(»²"=[ˆÿjй"cÕ.W®ºïI±PB/úuÓŸic¸D®_¾c£3D‰Èwë'áJì&ÛÂÙû}Cùô
—ÆÀËl¬~ЧԲÈyÇα    ÈÆhbSê¾ ç»ûg¢çð²POêA–Á"üïbV|Ë "Æ'G&éýù>ü µr ÒÅ/Í)®8XU›M}1E2ÚÀúaâ³'d¾¦Ý»TV'°ŠÖÀñÁa  ¤×}:*ØίßLÿklÌÐÄàæ4úN››w—ÊÑ ù=Pzf›ÿ%J µµ¾Nf'{eÔleÊs‹ðý…©m¤¸ò¬†0Ñü*D‰ÀøÖˆ'…RòÒ‰013¾QYó   ,&Ñ»§<»J{«»"©‡ÆÐñ,¦®â…òž~ËkAž<ꈘ]8i8ÿ0ãÚÔFÙ™ö\®ŠM—zOÓ¶·è"Y

Plain File Content
<reading version="2"><cam><name>Test-Road</name><serial>682719AE6F5E</serial><mac></mac></cam><date>2024-01-19T09:14:06.230Z</date><timestamp>1705655646230</timestamp><plate><adr><kemler>33</kemler><onu>1203</onu></adr><value>ABCDE123</value><direction>-1</direction><country>ITA</country><vehicle>truck</vehicle><speed>20</speed><x>1419</x><y>387</y><width>197</width><height>46</height></plate><images><ocr><url>http://localhost:7572/img/2024/01/19/10/2024-01-19-10-14-06-FG050EE_full.jpg</url></ocr><context><url>http://localhost:7572/img/2024/01/19/10/2024-01-19-10-14-06-FG050EE_ctx.jpg</url></context></images></reading>

Comment: You may not decode a ciphertext with a charset encoding, as you seem to have done. This will generally corrupt it. You must either make the file available so that it can be downloaded, or encode the contents of the file with a binary-to-text encoding and make it available (e.g. by loading the file with a hex editor and posting the hex encoded contents).
Comment: The most likely issue is that the contents of `encryptedBytes` (`criptedData`) are not precisely (byte-for-byte) the contents of `encrypted.msg`. If I had to guess at the difference, the first thing I'd verify is that there isn't an extra newline at the end of `criptedData`.
Comment: The error message is probably caused by a (somehow) corrupted ciphertext (s. previous comment). But apart from that, OpenSSL statement and C# code are different with regard to key size (OpenSSL: AES-128, C#: AES-256) and key derivation (OpenSSL: none, C#: via MD5). Incidentally, ECB does not use IV (you can pass `null`). Post a complete code (`CryptographyUtil.GetMd5()` is missing) and (short) sample data.
Comment: Regarding AES-ECB itself, read this: [**Why shouldn't I use ECB encryption?**](https://crypto.stackexchange.com/questions/20941/why-shouldnt-i-use-ecb-encryption)  It's OK for learning and experimenting, but its secure uses are limited.
Comment: I try to remove IV (var decryptor = rm.CreateDecryptor(keyB, null);) but I have same issue
Comment: @Andrew Henle: The encrypted data comes from third parties and I have no control over it
Comment: You are still using the wrong key: You hex encode the MD5 hash, UTF-8 encode the result and use that as key, which is wrong. Use directly as key: `MD5.Create().ComputeHash(Encoding.UTF8.GetBytes("abcd"))`. BTW, MD5 is a broken digest and thus a vulnerability.
Comment: Your "cripted file" output above is not the actual data in that file. It's most likely a Latin-1 decoding of the data, which is extremely lossy (~12.5% of the characters are unprintable and so are lost). You need to look at the actual bytes of the file, not a string decoding of it. If you are performing string encoding or decoding, that could be the cause of this particular error message as well.
Comment: Now, after get bytes directly from real encripted file i get a new Exception.
Source: System.Security.Cryptography
Exception Message: Padding is invalid and cannot be removed.
Comment: Post the ciphertext as described (either as file download or the hex or Base64 encoded content). However, this error message is strange if you are really using `PaddingMode.None`.
Answer: I found and resolved my problem changing this below lines of my postal code, related to get password bytes value:
 var keyB = new byte[32];
 var tmp = Encoding.UTF8.GetBytes(key);
 Buffer.BlockCopy(tmp, 0, keyB, 0, Math.Min(tmp.Length, 32));

With
var keyB = StringToByteArrayFastest(key);

private static byte[] StringToByteArrayFastest(string hex)
{
   if (hex.Length % 2 == 1)
     throw new Exception("The binary key cannot have an odd number of  digits");

   byte[] arr = new byte[hex.Length >> 1];

   for (int i = 0; i < hex.Length >> 1; ++i)
   {
     arr[i] = (byte)((GetHexVal(hex[i << 1]) << 4) + (GetHexVal(hex[(i << 1) + 1])));
   }

   return arr;
}

private static int GetHexVal(char hex)
{
    int val = (int)hex;
    //For uppercase A-F letters:
    //return val - (val < 58 ? 48 : 55);
    //For lowercase a-f letters:
    //return val - (val < 58 ? 48 : 87);
    //Or the two combined, but a bit slower:
    return val - (val < 58 ? 48 : (val < 97 ? 55 : 87));
}

I found the two new method mentioned above on this post:
Decrypting AES in C# where the file was encryped using OpenSSL -nosalt; the AES is expecting a size 16 byte array IV?


What happens if the 2 umpires in cricket disagree on a decision?

Question: Say the umpire at the non-striker's end has given an LBW, but the square leg umpire has observed that the ball is clearly too high to be hitting the stumps, can the square leg umpire override or advise the non-striker's end umpire's decision?
Does the square leg umpire in general have the same jurisdiction as the non-striker's end umpire?
Are there decisions the square leg umpire has more power on than the non-striker's end umpire, e.g. height wides/no-balls?
Answer: Umpires may certainly consult each other and do maintain separate jurisdictions. The newest version of the Laws of Cricket, dated 1st October 2017, published by the MCC, has several clauses dealing with this (they haven't changed significantly in meaning since the last version):

2.11 Disagreement and dispute
Where there is disagreement or dispute about any matter, the umpires together shall make the final decision. See also Law 31.6 (Consultation by umpires).

and

31.6 Consultation by umpires
Each umpire shall answer appeals on matters within his/her own jurisdiction. If an umpire is doubtful about any point that the other umpire may have been in a better position to see, he/she shall consult the latter on this point of fact and shall then give the decision. If, after consultation, there is still doubt remaining, the decision shall be Not out.

Unfortunately the Laws themselves are somewhat less explicit about which umpire has jurisdiction for each decision, only sometimes explicitly assigning them to the bowler's end umpire or not. In my experience of the game, the bowler's end umpire would certainly consider an LBW appeal his or her job and give the final decision, but only a foolish umpire in a bad umpiring team wouldn't listen to information from his/her colleague if they had anything to say.
Comment: That's true, I wonder if in club cricket, where there are no cameras, if the square leg umpire should have more input into the height of LBW decisions..


Taylor expansion of exponential function and singularities

Question: Stackexchange community,
i have a little trouble in understanding this condradtiction about singularities.
Lets consider the function $f(z)=\exp(-z)$.
This function can be expanded as a taylor series:
$$f(z)=1-z+\frac{z^2}{2!}-\frac{z^3}{3!}\pm$$
As this is "some sort of polynomial" it will never have a singularity on every finite domain of $z$.
But if I express $f(z)=\exp(-z)=\frac{1}{\exp(z)}$ and then apply the taylor series on $\exp(z)$ I get:
$$f(z)=\frac{1}{1+z+\frac{z^2}{2!}+\frac{z^3}{3!}\pm}$$
Now here comes my confusion, the new representation allows singularities of $f(z)$, as it is "some kind of polynomial" in the denominator. What is the problem here? Is it because of the radius of convergence?
EDIT: Ok it is because the fundamental theorem of calculus isn't true for infinite sums. Is there some intuitive way of understanding this phenomenon?
I would be glad if someone could solve this contradicion.
Comment: But what is the problem with second representation?
Comment: The second representation allows singularities by the fundamental theorem of algebra.
Comment: "As this is a polynomial" -- no it is not a polynomial.
Comment: Ok it is power sum, but why exactly does the fundamental theorem of algebra not hold for infinite polynomials?
Comment: See https://math.stackexchange.com/questions/109360/roots-of-the-incomplete-gamma-function/109605#109605 for the behaviour of the roots of the partial sums of the exponential function. Also https://math.stackexchange.com/questions/51586/approximating-roots-of-the-truncated-taylor-series-of-exp-by-values-of-the-la/553357#553357
Answer: It is not
"some sort of polynomial."
It is a power series
with an infinite number of terms.
Consider the polynomials
$\sum_{k=0}^n x^k
$
for any positive integer $k$
these are defined
for all real (and complex)
$x$.
But, if we consider
the infinite power series
$\sum_{k=0}^{\infty} x^k
$,
this diverges for
$|x| > 1$
and converges for
$|x| < 1$.
Answer: the denominator is never 0. no singularities


Find Jordan form of matrix with parameter $m\in\mathbb R$

Question: the (real) matrix is $\left[ \begin{matrix} 0& 0& 0\\ 1& 0& -m^{2}\\0& 1& m\\\end{matrix} \right]$.
Well, the characteristic polynomial is $p(t)=t(t^2-mt+m^2)$ so it doesn't have any real roots except 0, and then I got stuck.
Comment: @Moo that's a great paper, thank you!
Comment: You have one real and two imaginary eigenvalues - so nothing is different because we have three unique eigenvalues, thus the matrix is diagonalizable.
Comment: @Moo Unless $m=0$.
Comment: @JoséCarlosSantos: Good point!
Comment: @Moo if it's diagonalizable so there is no Jordan form, and if $m=0$ then the minimalistic polynomial is $t^2$ and I can use the theorem to show the Jordan form, am I right?
Comment: @Moo yes, the diagonal form is a special JNF case, I guess
Comment: See the examples of Jordan forms on page 5 and non-examples on page 6: http://www.ms.uky.edu/~lee/amspekulin/jordan_canonical_form.pdf - also see Example 2 on the bottom of page 6 for all the flavors of JNFs for a $3x3$ matrix
Answer: For the case in which $m \neq 0$, the matrix has three distinct eigenvalues.  So, the Jordan form is just the diagonal matrix with those eigenvalues on the diagonal.
For the case in which $m = 0$, we note that transposing the matrix produces a Jordan-form matrix.  Any matrix is similar to its transpose.


Propagate Result to next BroadcastReceiver in android

Question: I have 2 receivers and 2 GCMIntentService classes for GCM in my application; one inside my app and another one is included in a library that i have added to my application.When a message is received through GCM; I would want to some how identify which intentservice a received message is intented for and let the correct reciever handle it. Some one suggested here  to propagate result to the next receiver if its not intended for mine but i couldnt manage to do it. I would really appreciate if some one could help me with that.
Comment: I wrote that suggestion. What exactly doesn't work for you? You can use the priority to determine which receiver will be called first, and you can use the sender id to know if the message is intended for a specific receiver.
Comment: Thanks for the response. Yes i could determine which receiver is it intended for but i dont know how to propagate result to the other reciever if its not intended for me.
Comment: To identify messages for my reciever i am sending an identifier string  with the message and inside my GCMIntentService onMessage() method i check if the received message contains that string. I am not sure if thats the right approach. Did you mean something like this ? if not , what is correct place to handle this. should i define custom GCMBroadcastReceiver ?
Comment: If you don't define a custom GCMBroadcastReceiver then how do you expect to propagate the result? The default GCMBroadcastReceiver (of the now deprecated library) ends with `setResult(Activity.RESULT_OK, null /* data */, null /* extra */);`, I'm not sure about it, but setting the data and extras to null might prevent them from being passed to the next broadcast receiver.
Comment: Thanks Eran. I was using the deprecated Gcm api that wouldn't allow me overide methods of GCMBroadcastReceiver. I switched to the new GoogleCloudMessaging api and its working fine. both of them receive every message. But i still couldnt make it stop from propagating the message bundle to the other receiver once i handle it my self. I have tried both Result.canceled and result.ok.
Comment: Perhaps you should try something like this - `setResult(Activity.RESULT_OK, null /* data */, null /* extra */);` - when you wish to stop from propagating the message. I'm not sure if it will work, but it's worth trying.
Answer: Ok I have managed to solve it. Thanks to @Eran for his help. I was using the deprecated GCM api. The default implementation of GCMBroadcastReceiver had
<code>    setResult(Activity.RESULT_OK, null /* data */, null /* extra */);
</code>
in onReceive() method. This would prevent passing the result on to the next receiver. I tried to overide the onReceive method but it was final and wouldn't allow me overide it. So, i switched to the new GoogleCloudMessaging api and defined a custom Broadcast receiver and in its onReceive() metod i did this :
<code>    @Override
    public void onReceive(Context context, Intent intent) {

        String message = intent.getExtras().getString("identifier_tag");

        // ignore if message not intended for us
        if (message == null) {
            setResultCode(Activity.RESULT_OK);
            return;
        }
        if (!message.equals(IDENTIFIER_TAG)) {
            setResultCode(Activity.RESULT_OK);
            return;
        }

        ComponentName comp = new ComponentName(context.getPackageName(),
                GcmIntentService.class.getName());
        // Start the service, keeping the device awake while it is
        // launching.
        startWakefulService(context, (intent.setComponent(comp)));

        // message has been handled; do not propagate
        setResult(Activity.RESULT_OK, null, null);

}
</code>
What i did was to check if the received message was intended for me. If yes, i would invoke the intent service and  setResult(Activity.RESULT_OK, null, null); would stop the message from being passed on to other receivers. If message wasn't intended for me, i would pass it to the next receiver. also in the manifest file, i set the priority for this receiver higher to make sure it receive the message first.