Can i use Chi-Square or z-test for my hypothesis?

Question: I'm new to statistics. I'm struggling to find the right hypothesis test.
Data description
My dataset contains 5000 JIRA tickets. Of each ticket it is known within how many days it is closed. When i plot a histogram of the closure days they are right-skewed.
I took 2 random samples:

125 tickets from year 2018
125 tickets from year 2019

Sample mean
The mean average time for handling tickets in 2018 = 7.52 days.
The mean average time for handling tickets in 2019 = 17.5 days
Data converted
I also transformed the data into a 2x2 table:
<code>  YEAR  TRUE   FALSE
  2018  115    10
  2019   88    37
</code>
TRUE is that the ticket has been processed within the agreed time of 14 days. FALSE is that the ticket has not been processed within the agreed time of 14 days
How to test my hypothesis?
I want to test a hypothesis if there is a significant difference in the mean or FALSE outcomes between year 2018 and 2019.
I thought two tests would be possible:

Doing a Chi-Square test for the outcomes TRUE and FALSE from year 2018 and 2019.
I also thought it could be an option to compare the average handling time of 2018 and 2019 with a z-test to see if there is a difference.

Is it true that I could use both tests? Or should I look at other tests?
Comment: Is this an assignment in a course? If so, please flag as such.
Comment: @NickCox no, this is for a project I'm working on.
Answer: You seem to be on the right track.
Two- sample Chi-Square on the two distributions is possible (although I guess you are talking about the years 2018/19 rather than 2015/16?)
However, I have two little caveats regarding the z-test. First, you need to make sure (e.g. by repeated bootstrapping) that your sampled means are indeed normally distributed. Most likely this will be the case, given the number of tickets you have.
Secondly, z-test assumes the population variance to be known -or very well approximated by the sample variance, which again depends on the sample size and will most likely be the case. Nevertheless, just to be on the safe side, I would still consider swapping the z- with the t-test, since the latter is unaffected by the population variance problem
Comment: I mean indeed 2018/2019. I changed this in the starting post. So the conclusion can be that i'm safe with the chi-square test or else just take the t-test instead of the z-test?
Comment: yes. I would still go for the t-test, since, as a 1D-problem,  it is conceptually simpler


how to add and edit a legend in goem_hline() in R

Question: I'm trying to add a caption to geom_hline () but I don't know how I can do it.
I tried geom_hline (aes (yintercept = 18, 'Historical serie'), size = 1.5, col =" # ffff00 ") but it returns an error. I took 'Historical serie' it worked, but the caption does not appear.
library(tidyr)
library(dplyr)
library(lubridate)
library(ggplot2)

date2<-c('01/01/2000','08/08/2000','16/03/2001','06/09/2001')
name<-c('A','B','A','B')
total<-c(23,25,36,41)
esp<-c(0.363,0.4123,0.09,0.65)

df<-data.frame(date2,name, total, name, esp)%>%
  mutate(date3=as.Date(date2, "%d/%m/%Y"))%>%
  mutate(year_date=as.Date(trunc(as.POSIXlt(date3), "years")))

ggplot(data=df, aes(x=year_date, y=total, fill=name))+
  geom_col(position = "dodge")+
  scale_fill_manual(values=c("#08088A","#9F81F7"))+
  theme_light()+labs(fill="rain", title ="rain anual", x="Estation", y="total mm")+
  theme(axis.text.x = element_text(angle = 90))+
  geom_hline(aes(yintercept = 18, 'Historiacal serie'), size=1.5, col="#ffff00")

Expectative

I would like the value 18 to appear as well as its description Historical serie for the yellow line.
Comment: Does this answer your question? [Add geom\_hline to legend](https://stackoverflow.com/questions/55429396/add-geom-hline-to-legend)
Comment: change the linetype to `linetype='Historical series \n18'`
Comment: @B Williams it is not the answer, as it does not add the value "18" in the caption, only her name. So it doesn't fit my situation.
Comment: @B Williams, but the term "linetype" will appear in the caption. in the latter case, your response may be a way of getting around the situation.
Comment: Edit: This question is not duplicated as you will notice that the question caption is different from those on Stack Overflow.

See that we have a title and a value associated with the reference line, while another suggested post has only one title associated with the line
Answer: Update: OP request:
p <- ggplot(data=df, aes(x=year_date, y=total, fill=name))+
  geom_col(position = "dodge")+
  scale_fill_manual(values=c("#08088A","#9F81F7"))+
  theme_light()+labs(fill="rain", title ="rain anual", x="Estation", y="total mm")+
  theme(axis.text.x = element_text(angle = 90))

data_line <- data.frame(yintercept=18, data_line=factor(18))

p +
  geom_hline(data=data_line, aes(yintercept=yintercept, linetype="18"), size=1.5, col="#ffff00") +
  scale_linetype_manual(name = "Historiacal serie",values = c(1,1))

Comment: Please see my edit. You can change title by `scale_linetype_manual`.
Comment: very good friend. This is a good solution. I've been researching geom_hline and I saw on a github post that this command has problems, but strangely they haven't solved it yet: https://github.com/tidyverse/ggplot2/issues/1267
Comment: hi, the geom_hline () would not natively have commands for me to add the caption. Because I saw that you created another intermediate data.frame `p + geom_hline ()` to get around the problem
Comment: I noticed now here at Rstudio, that your solution didn't look like the expectation image, as I would like the value 18 to appear.
Answer: I got it with help from https://community.rstudio.com/t/how-to-add-legend-in-goem-hline-in-r/105127/2 using only geom_hline ()
alternative
date2<-c('01/01/2000','08/08/2000','16/03/2001','06/09/2001')
name<-c('A','B','A','B')
total<-c(23,25,36,41)
esp<-c(0.363,0.4123,0.09,0.65)

ggplot(data=df, aes(x=year_date, y=total, fill=name))+
  geom_col(position = "dodge")+
  scale_fill_manual(values=c("#08088A","#9F81F7"))+
  theme_light()+labs(fill="rain", title ="rain anual", x="Estation", y="total mm")+
  theme(axis.text.x = element_text(angle = 90))+
  geom_hline(aes(yintercept = 18, linetype = "18"), colour = "green", size=1.5) +
scale_linetype_manual(name ="Historical serie", values = c('solid'))


Como indexar subgrupos em R

Question: O que preciso é indexar subgrupos dentro de um grupo e que o R me traga um resultado específico, linha a linha, dependendo do subgrupo.
Primeiro preciso agrupar os dados por processo. Isso eu consegui com group_by:
dados <- data.frame(processos = c("123","123","123","abc","abc","xyz","xyz","xyz","xyz"),
                    situacao = c("a","b","c","c","b","c","a","a","b"),
                    resultado = c("0","0","0","0","0","0","0","0","0"))

dados <-
  dados %>%
  group_by(processos)

Preciso que o R verifique na coluna situacao quando o b aparece. Em seguida, que coloque todas as linhas do grupo processo com 1 e todas as linhas do grupo b como 2. Preciso que ele faça esse preenchimento processo a processo.
Detalhe que os grupos (processos) possuem tamanhos diferentes. O resultado esperado ficaria assim:
dados
         processos situacao resultado
    1       123        a         1
    2       123        b         2
    3       123        c         1
    4       abc        c         1
    5       abc        b         2
    6       xyz        c         1
    7       xyz        a         1
    8       xyz        a         1
    9       xyz        b         2

Já tentei aggregate, mutate, if_else, if, mas todos sem qualquer sucesso.
Answer: Basta usar mutate combinado com if_else. Se a coluna situacao for igual a b, resultado recebe 2. Caso contrário, recebe 1. Sequer é preciso agrupar os dados, pois a informação dos processos não é utilizada em nenhum momento.
library(dplyr)

dados %>%
  mutate(resultado = if_else(situacao == "b", 2, 1))
#>   processos situacao resultado
#> 1       123        a         1
#> 2       123        b         2
#> 3       123        c         1
#> 4       abc        c         1
#> 5       abc        b         2
#> 6       xyz        c         1
#> 7       xyz        a         1
#> 8       xyz        a         1
#> 9       xyz        b         2

Created on 2021-05-20 by the reprex package (v2.0.0)
Answer: Usa o truquezinho do cumsum, que aí adiciona 1 quando aparece um b no grupo.
dados <- data.frame(processos = c("123","123","123","abc","abc","xyz","xyz","xyz","xyz"),
                    situacao = c("a","b","c","c","b","c","a","a","b"),
                    resultado = c("0","0","0","0","0","0","0","0","0"))
library(dplyr)

dados <-
  dados %>%
  group_by(processos) %>%
  mutate(resultado = cumsum(situacao == "b") + 1)

dados
#> # A tibble: 9 x 3
#> # Groups:   processos [3]
#>   processos situacao resultado
#>   <chr>     <chr>        <dbl>
#> 1 123       a                1
#> 2 123       b                2
#> 3 123       c                2
#> 4 abc       c                1
#> 5 abc       b                2
#> 6 xyz       c                1
#> 7 xyz       a                1
#> 8 xyz       a                1
#> 9 xyz       b                2

Created on 2021-05-20 by the reprex package (v2.0.0)
Comment: Era exatamente isso! Algo tão simples, mas que me bateu muito! haha, Conhecimento é tudo mesmo!

Muito obrigado
Answer: Se o resultado do processamento é igual para todos os grupos, então não depende do grupo.
Esta solução utiliza o facto de uma condição lógica corresponder aos inteiros 0/1. Basta então somar 1 aos valores de igualdade a "b".
library(dplyr)

dados %>% mutate(resultado = (situacao == "b") + 1L)
#  processos situacao resultado
#1       123        a         1
#2       123        b         2
#3       123        c         1
#4       abc        c         1
#5       abc        b         2
#6       xyz        c         1
#7       xyz        a         1
#8       xyz        a         1
#9       xyz        b         2

Edição
Uma resposta do AP que deveria de facto ser um comentário às respostas já existentes é a seguinte:

Eu tentei desse jeito, mas ele só traz o resultado 2 na linha onde o
"b" aparece. Eu preciso mesmo é que antes do "b" todas as linhas sejam
1 e do "b" para frente todas as linhas sejam 2. Quando mudar o
processo o indicador deve voltar para 1.
Assim, no primeiro processo o resultado seria 1,2,2 e na linha 4 o
marcador volta para 1.

Depois desta resposta, passa a ser evidente que se deve agrupar por processos e o código certo será o seguinte. (Entretanto já há uma resposta igual, do usuário @Jorge Mendes.)
dados %>%
  group_by(processos) %>%
  mutate(resultado = cumsum(situacao == "b") + 1L)
## A tibble: 9 x 3
## Groups:   processos [3]
#  processos situacao resultado
#  <chr>     <chr>        <int>
#1 123       a                1
#2 123       b                2
#3 123       c                2
#4 abc       c                1
#5 abc       b                2
#6 xyz       c                1
#7 xyz       a                1
#8 xyz       a                1
#9 xyz       b                2

Como indexar subgrupos em R


Let $C\subset E$ be a convex subspace and $a\in E\setminus C$. The point in $C$ closest to $a$ is unique.

Question:
Let $E$ be a vector space with a norm $|\cdot|$ induced by an inner product, $C\subset E$ a convex set, and $a\in E\setminus C$. Show that if there are $x_0,x_1 \in C$ such that $|a-x_0|\leq |a-x|$ and $|a-x_1|\leq|a-x|$ for every $x\in C$, then $x_0 = x_1$.

Picturing a ball, the only point with such property is the one closest to $a$, which is unique, so the question makes sense. However, I haven't been able to use convexity of $C$ to finish the proof.
I found similar questions in the context of real analysis, but couldn't abstract the logic.
Comment: You have to imagine it if you wish to solve it: If you work in $\mathbb{R}^n$  for example and you assume by contradiction there exists two closest points then you have a triangle (whose vertices are the original point and these two points) this triangle has two edges of the same length. Now using "high school" geometric you can find
a closer point (the middle of these two points). Note that you have to rely on the fact that you work on an inner product space, it will not be true in general.
Answer: The geometric proof others have suggested would also be the way I'd recommend proceeding. However there does exists a more analysis based proof. Let $d = \inf_{x \in C} \lvert a - x \rvert$ and $(x_i) \subset C$ be any sequence such that $\lvert a - x_i \rvert \to d$ as $i \to \infty$. We aim to prove $(x_i)$ is a Cauchy sequence. Since the norm arises from an inner product $\langle \cdot, \cdot \rangle$, we know the norm satisfies the parallelogram identity:
$$ \lvert v + w \rvert^2 + \lvert v - w \rvert^2 = 2\lvert v \rvert^2 + 2\lvert w \rvert^2 $$
Plugging in $v = a - x_i$ and $w = a - x_j$ and rearranging gives that
$$ \lvert x_i - x_j \rvert^2 = 2\lvert a - x_i \rvert^2 + 2 \lvert a - x_j \rvert^2 - 4 \lvert a - \tfrac{1}{2}(x_i + x_j) \rvert^2$$
Since $C$ is convex we know $\frac{1}{2}(x_i + x_j) \in C$ therefore $\lvert a - \frac{1}{2}(x_i + x_j) \rvert \geq d$. Moreover since $\lvert a - x_i \rvert \to d$ as $i \to \infty$ we can find $N$ such that for all $i \geq N$ we have $\lvert a - x_i \rvert^2 < d^2 + \epsilon$. Then for all $i, j \geq N$ we have
$$ \lvert x_i - x_j \rvert^2 < 2(d^2 + \epsilon) + 2(d^2 + \epsilon) - 4d^2 = 4\epsilon $$
Therefore $(x_i)$ is Cauchy.
Now suppose that $\lvert a - x \rvert = d$ is achieved for two points in $C$, say $v_0$ and $v_1$. Then we can take $(x_i)$ to be the alternating sequence $v_0, v_1, v_0, v_1, \ldots$ and the above shows this sequence is Cauchy. So in fact $v_0 = v_1$.
This proof has some value because if we further assume $C$ to be complete (in particular $C$ is complete if $E$ is a Hilbert space and $C$ is closed), we know any Cauchy sequence has a limit. Therefore taking any $(x_i) \subset C$ such that $\lvert a - x_i \rvert \to d$, we know $x_i \to x$ for some $x \in C$ as $i \to \infty$. Moroever by continuity of the norm $\lvert a - x \rvert = d$. Therefore if $C$ is complete and convex, we can always achieve the minimum distance from $C$ to any point.
Comment: This is a really good, general answer, but it didn't work the intuition, which helped me get to the answer. It's good to have it around, though, thanks. edit: I mean, this is just what I did, but it wasn't so general
Answer: Just a hint: If $x_0 \ne x_1$ are both at distance $d,$ then one of the points interior to the segment joining $x_0$ to $x_1$ should be at distance less than $d.$
Comment: @big-lion Yes, convexity is what guarantees all points on the segment between $x_0,x_1$ are in $C.$
Comment: This, plus @Yanko's proof by contradiction suggestion, plus the above answer reminding me of the parallelogram identity led to a straightforward solution that makes sense. Your answer was the inception, though. Thanks.
Comment: If $C$ was not convex, then the midpoint between $x_0$ and $x_1$ could be outside $C$ so there would be no contradiction. Is that where we used it?


How to embed a view or a rendered node into a field group

Question: I'm afraid my question is a bit to general because I don't quite know where to start.  I still really don't have my head wrapped around the drupal 7 theming system.
Scenario
I have two content types:

Type main
Type secondary (this type has a required entity reference field, referencing Type main

The display on Type main has a set of 2 horizontal tabs htabs group named group_expandables.
Desired Outcome
What I would like to happen is, if an entity of Type secondary has been added referencing this node; add a third horizontal tab containing the Type secondary node and make it the default.
Initial Approach
These are the steps I thought through that should probably happen on page load for a node of type Main:

Look for a Type secondary node referencing this node, return if not found
If found, build up a new render array for the Type secondary node htab.  I was thinking it would be easiest to build this display in views, and load in the view, but doing it in a template file would probably work too.
Once the variable has been for the new htab, insert it in the htabs  render array and modify the render array to remove the open by default indicator on the old default tab.

So far I have used hook_preprocess_page to grab the $variables['page']['content']['system_main']['nodes'][nid]['#fieldgroups']['group_expandables'] and add a new group name to its children, clone one of the htab field groups and append it to the ['#fieldgroups'] array, and modify the elements that referenced the old htab and replace them with the name for the new tab.  Once I figured out that I needed an entry in #group_children too, I actually got the tab to appear in the group, but I haven't had any luck getting content to show up in it yet.
Question
Here are the places I'm really hung up:

Is hook_preprocess_page the best place to start this?
Is my general strategy for how to go about this sound?
How would I build my desired content into the new htab?

I'm sorry for the broad nature of the question, any pointers would be greatly appreciated.
Answer: I'm not sure your general strategy is the absolute best way to go, but I don't see any major problems, I think hook_preprocess_page is too broad as it runs everywhere and would suggest template_preprocess_node instead (even though this is a template preprocess it can be run like a normal hook preprocess in a module)
In regards to getting the content you will need to do a EntityFieldQuery using the nid of the page being viewed as a fieldCondition, the only problem I can see is when there is more than one secondary type assigned to the same main type.
An alternative approach would be to see whether it's possible to write a View which takes the nid as a Contextual Filter and then builds all the content, I think you'd need to add a Relatonship to the secondary type, etc. and if it's possible this would cut down on the amount of custom coding needed.
Comment: Thanks for the answer!  When I run template_preprocess_node I don't see the #field_groups array that I need to use to put things into field_groups, so either it is somewhere I haven't looked, or I need to use preprocess_page.  Thanks for the pointer for EntityFieldQuery.  Now that I've managed to show node inside a field group, the next step is to start building the logic for conditionally building and showing that tab, so I'll dig into that soon.


Uncaught exception 'Google_Auth_Exception' with message 'Could not json decode the token'

Question: I am using the user-example.php in the google-api-client-php library and it is throwing up the error
Fatal error: Uncaught exception 'Google_Auth_Exception' with message 'Could not json       decode the token' in /Applications/XAMPP/xamppfiles/htdocs/Calendar/google-api-php-client/src/Google/Auth/OAuth2.php:174 Stack trace: #0 /Applications/XAMPP/xamppfiles/htdocs/Calendar/google-api-php-client/src/Google/Client.php(196): Google_Auth_OAuth2->setAccessToken('[]') #1 /Applications/XAMPP/xamppfiles/htdocs/calendar/google-api-php-client/examples/user-example.php(80): Google_Client->setAccessToken('[]') #2 {main} thrown in /Applications/XAMPP/xamppfiles/htdocs/Calendar/google-api-php-client/src/Google/Auth/OAuth2.php on line 174

the code of the example is
<?php
/*
 * Copyright 2011 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
include_once "templates/base.php";
session_start();

set_include_path("../src/" . PATH_SEPARATOR . get_include_path());
require_once 'Google/Client.php';
require_once 'Google/Service/Urlshortener.php';

/************************************************
  ATTENTION: Fill in these values! Make sure
  the redirect URI is to this page, e.g:
  http://localhost:8080/user-example.php
 ************************************************/
 $client_id = '<XXXXX>';
 $client_secret = '<XXXXX>';
 $redirect_uri = '<XXXXXX>';

/************************************************
  Make an API request on behalf of a user. In
  this case we need to have a valid OAuth 2.0
  token for the user, so we need to send them
  through a login flow. To do this we need some
  information from our API console project.
 ************************************************/
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->addScope("https://www.googleapis.com/auth/urlshortener");

/************************************************
  When we create the service here, we pass the
  client to it. The client then queries the service
  for the required scopes, and uses that when
  generating the authentication URL later.
 ************************************************/
$service = new Google_Service_Urlshortener($client);

/************************************************
  If we're logging out we just need to clear our
  local access token in this case
 ************************************************/
if (isset($_REQUEST['logout'])) {
  unset($_SESSION['access_token']);
}

/************************************************
  If we have a code back from the OAuth 2.0 flow,
  we need to exchange that with the authenticate()
  function. We store the resultant access token
  bundle in the session, and redirect to ourself.
 ************************************************/
if (isset($_GET['code'])) {
  $client->authenticate($_GET['code']);
  $_SESSION['access_token'] = $client->getAccessToken();
  $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
  header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}

/************************************************
  If we have an access token, we can make
  requests, else we generate an authentication URL.
 ************************************************/
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
  $client->setAccessToken($_SESSION['access_token']);
} else {
  $authUrl = $client->createAuthUrl();
}

/************************************************
  If we're signed in and have a request to shorten
  a URL, then we create a new URL object, set the
  unshortened URL, and call the 'insert' method on
  the 'url' resource. Note that we re-store the
  access_token bundle, just in case anything
  changed during the request - the main thing that
  might happen here is the access token itself is
  refreshed if the application has offline access.
 ************************************************/
if ($client->getAccessToken() && isset($_GET['url'])) {
  $url = new Google_Service_Urlshortener_Url();
  $url->longUrl = $_GET['url'];
  $short = $service->url->insert($url);
  $_SESSION['access_token'] = $client->getAccessToken();
}

echo pageHeader("User Query - URL Shortener");
if (
    $client_id == '<YOUR_CLIENT_ID>'
    || $client_secret == '<YOUR_CLIENT_SECRET>'
    || $redirect_uri == '<YOUR_REDIRECT_URI>') {
  echo missingClientSecretsWarning();
}
?>

    <?php if (isset($authUrl)): ?>
      <a class='login' href='<?php echo $authUrl; ?>'>Connect Me!
    <?php else: ?>
      <form id="url" method="GET" action="<?php echo $_SERVER['PHP_SELF']; ?>">
        <input name="url" class="url" type="text">
        <input type="submit" value="Shorten">
      </form>
      Logout
    <?php endif ?>

  <?php if (isset($short)): ?>

      <?php var_dump($short); ?>

  <?php endif ?>

<?php
echo pageFooter(__FILE__);

Can anyone shed any light as to why i might be receiving this error? I'm sure i have all my access tokens set up correctly. I had a problem in my own code, but I can't seem to get Google's own example working.
Comment: At what point in the OAuth Flow do you get the error? Did you change the $client_id ,  $client_secret and $redirect_uri ? adding them where you have XXXXXX wont work with that sample as it has error checking to ensure that you have filled them in.
Comment: Yeah, sorry i messed up the example slightly and have edited it to show where i have actually entered my client secret etc. I get this error upon trying to access the file in my localhost.
Comment: I was facing the same issue. For my case client secret was invalid.
Answer: I have encountered the same problem. It seems that the latest Google API PHP library is expecting a json encoded token in the setAccessToken method. So what I did as a work around was encoded the tokens to json.
// $token could be retrieved from your SESSION cookie or from your DB.
$token = array(
    'access_token' => 'XXXXXXX',
    'refresh_token' => 'XXXXXXX');

$json_token = json_encode($token);
$client->setAccessToken($json_token);

Hope this helps.
Answer: Could you Copy-paste your $_SESSION['access_token']?
Try with this:
http://php.net/manual/es/function.json-last-error.php
In your code, change:
json_decode($_SESSION['access_token']);
if (isset($_SESSION['access_token']) && $_SESSION['access_token'] && !json_last_error()) {
  $client->setAccessToken($_SESSION['access_token']);
} else {
  $authUrl = $client->createAuthUrl();
}


find real number using two percentage.

Question: Would like to shorten my request and what do find equation for my below question.
If 69% is 27.35 and 79% is 27.39 then what will be value for 70%.
Thanks for your help.
Comment: I don't think the number match up  correctly. I get different results from those two values.
Comment: @A---B. I'm no maths expert. but i guess that we need to apply linear equation method
Answer: If it's a linear equation/function you're looking for, it's quite easy: the difference between 69% and 79% is 10%; in the course of that, the value increases by 0.04. That means it increases by 0.004 for each 1%, and the value corresponding to 70% must be 27.354.

find real number using two percentage.


The Simplicial Flabby Resolution of a Sheaf

Question: I study sheaf cohomology by Demailly's book and I have a trouble. Is the inductive formula at the end of page 198
$$\mathcal{A}^{[q]}=(\mathcal{A}^{[q-1]})^{[0]}$$
right? I think that $(\mathcal{A}^{[0]})^{[0]} = \mathcal{A}^{[0]}$, is it true?
May be
$$\mathcal{A}^{[q]}=(\mathcal{A}^{[q-1]}/\mathcal{A})^{[0]}$$
or
$$\mathcal{A}^{[q]}=(\mathcal{A}^{[q-1]}/\mathcal{A}^{[q-2]})^{[0]}?$$
Is this resolution have any other name?
Thanks a lot!
Answer: The explicit expression is indeed
$$\mathcal{A}^{[q]}=(\mathcal{A}^{[q-1]}/\mathcal{A}^{[q-2]})^{[0]}.$$
And the flabby sheaves $\mathcal A^{[q]}$ are also called the Godement sheaves of $\mathcal A$, while the long exact sequence
$$0\longrightarrow \mathcal A\longrightarrow \mathcal A^{[0]}\longrightarrow\cdots\longrightarrow \mathcal A^{[q]}\longrightarrow \mathcal A^{[q+1]}\longrightarrow \cdots$$
is also called the Godement canonical flabby resolution.


Dúvidas sobre iistrução prepare do PDO

Question: Tenho  a classe conexao:
<?php
 /*
 * Constantes de parâmetros para configuração da conexão
 */
define('SGBD', 'mysql');
define('HOST', 'localhost');
define('DBNAME', 'db_blog');
define('CHARSET', 'utf8');
define('USER', 'root');
define('PASSWORD', '');
//define('SERVER', 'linux');

class conexao {

    /*
     * Atributo estático de conexão
     */
    private static $pdo;

    /*
     * Escondendo o construtor da classe
     */
    private function __construct() {
        //
    }

    /*
     * Método privado para verificar se a extensão PDO do banco de dados escolhido
     * está habilitada
     */
    private static function verificaExtensao() {

        switch(SGBD):
            case 'mysql':
                $extensao = 'pdo_mysql';
                break;
            case 'mssql':{
                if(SERVER == 'linux'):
                    $extensao = 'pdo_dblib';
                else:
                    $extensao = 'pdo_sqlsrv';
                endif;
                break;
            }
            case 'postgre':
                $extensao = 'pdo_pgsql';
                break;
        endswitch;

        if(!extension_loaded($extensao)):
            echo "
Extensão {$extensao} não habilitada!
";
            exit();
        endif;
    }

    /*
     * Método estático para retornar uma conexão válida
     * Verifica se já existe uma instância da conexão, caso não, configura uma nova conexão
     */
    public static function getInstance() {

        self::verificaExtensao();

        if (!isset(self::$pdo)) {
            try {
                $opcoes = array(\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8');
                switch (SGBD) :
                    case 'mysql':
                        self::$pdo = new \PDO("mysql:host=" . HOST . "; dbname=" . DBNAME . ";", USER, PASSWORD, $opcoes);
                        break;
                    case 'mssql':{
                        if(SERVER == 'linux'):
                            self::$pdo = new \PDO("dblib:host=" . HOST . "; database=" . DBNAME . ";", USER, PASSWORD, $opcoes);
                        else:
                            self::$pdo = new \PDO("sqlsrv:server=" . HOST . "; database=" . DBNAME . ";", USER, PASSWORD, $opcoes);
                        endif;
                        break;
                    }
                    case 'postgre':
                        self::$pdo = new \PDO("pgsql:host=" . HOST . "; dbname=" . DBNAME . ";", USER, PASSWORD, $opcoes);
                        break;
                endswitch;
                self::$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
            } catch (PDOException $e) {
                print "Erro: " . $e->getMessage();
            }
        }
        return self::$pdo;
    }

    public static function isConectado(){

        if(self::$pdo):
            return true;
        else:
            return false;
        endif;
    }

}

E a classe classBancoDados:
<?php
    class classBancoDados
    {
        protected $ComandoSQL;

        // Construtor

        Function __construct()
        {
            $this->setComandoSQL();
        }

        //Métodos Públicos

        public function getComandoSQL()
        {
            return $this->ComandoSQL;
        }

        public function setComandoSQL($ComandoSQL)
        {
            $this->ComandoSQL = $ComandoSQL;
        }

        public function SetSELECT($Campos = "", $Tabela = "", $CampoOrdenacao = "", $Ordem = "")
        {
            if(($Campos != "") && ($Tabela != ""))
            {
                $this->ComandoSQL = "SELECT  " . $Campos . " FROM " . $Tabela;

                if($Ordem != "") {
                    $this->ComandoSQL .= " ORDDER BY ";
                    $this->ComandoSQL .= $CampoOrdenacao;
                }
            }

        }

    }

                                        /*
                                    $sql = 'SELECT UF, Cidade, Endereco, Numero, Bairro, Telefone  FROM hoteis';
                                    $rs = $conexao->prepare($sql);
                                    $rs->execute();
                                    */

    $conexao_db = new classBancoDados();
    $conexao_db->SetSELECT("*", "hotei","UF, Cidade");

    $conexao = conexao::getInstance();
    $ResultSet = $conexao->prepare(*** O que deve vir aqui?);
    $registros = $ResultSet->fetchAll(PDO::FETCH_OBJ);

echo ??? o que deve vir aqui?

Estou estudando PHP7  e sou leigo e gostaria de saber o que devo colocar na instrução Prepare para obter uma resposta válida do do banco de dados.
Obrigado desde já pela atenção
Answer: Você deve colocar a query que quer executar. No seu caso, pelo que entendi é o valor de $this->ComandoSQL. Por exemplo:
<?php
$result = $conexao->prepare($this->ComandoSQL);

Comment: Muito Obrigado!!! funcionou... era exatamente o que eu pretendia... para obter o retorno da consulta. valeu !!!!
Comment: Marca a resposta como aceita clicando no checkmark, por favor.

Dúvidas sobre iistrução prepare do PDO


Intersection between a horizontal plane and a torus. Problem with complex values

Question: [EDIT: I have replaced $a$ by $R_1$ in my previous post to make your reading and understanding easier, as this is a more general expression.]
I think I have a basic question but I cannot figure out an easy solution.
I am intersecting a torus with an horizontal plane, which I will move from the upper part to the bottom to calculate the area the intersections at different heights. Thus, I need to obtain the parametric curve equation of each intersection to compute the area as: $$A=\int{y(v) x'(v) dv}$$.
My problem is that I am unable to obtain a "closed" parametric curve, since there are certain complex values in the calculation that I cannot avoid. I obtain something like this when I cut the torus in the region between the inner and outter diameters:
intersection between plane and torus (parametric curve as black line)
Parametric intersection curve
Parametric intersection curve plus its negative counterpart
As can be seen, even trying to replicate the full geometry by the addition of the negative values parametric curve (just in case this solves something...), there is a small region that does not allow any connection to create a full closed curve to be integrated to obtain the enclosed area.
Does anyone know what am I doing wrong? I would appreciate any help a lot.
Details of my procedure:
Parametric equations of the torus:
$$ x(u,v) = R_2*\sin(v),$$
$$ y(u,v) = (R_1+R_2\cos(v))\cos(u), $$
$$ z(u,v) = (R_1+R_2\cos(v))\sin(u), $$
with $v \in [0, 2\pi]$, $u \in [0, 2\pi]$, $R_1$ the radial position of the center of the revolutioned circunference, and $R_2$ the radius of the said circunference in revolution.
Parametric equations of the plane:
$$z(x,y)=h,$$
with $h$ an specific height which will be varied. It is just a horizontal plane.
To obtain the parametric curves, I have to make equal both $z$ values:
$$(R_1+R_2\cos(v))\sin(u) = h, $$
Thus: $\sin(u) = \frac{h}{R_1+R_2\cos(v)}$. I can substitute this value in y(u,v) to obtain y(v) by either using $u=\arcsin(\frac{h}{R_1+R_2\cos(v)})$ or $\cos(u)=\sqrt{1-\sin(u)^2}$. By using the latter one, we can get the following parametric curve for the intersection:
$$ x(v) = R_2*\sin(v),$$
$$ y(v) = (R_1+R_2\cos(v))\sqrt{1-\left(\frac{h}{R_1+R_2\cos(v)}\right)^2}, $$
with $v \in [0, 2\pi]$.
When $\left(\frac{h}{R_1+R_2\cos(v)}\right)^2$ > 1, the square root yields the said problematic complex values.
Many thanks in advance for your time to read this post.
Best regards.
[EDIT: An easy working Matlab script to visualize this situation:]
<code>close all;
R1=3; R2=1;
h=3.7; %Example of height
L1=4; L2=4; %some limits for the plane

%Plane equation
syms u v
yp=v;
zp = h;
xp = u;
fsurf(xp, yp, zp, [-(L1 + 2*R1)/2, (L1 + 2*R1)/2 , -(L2 + 2*R2)/2, (L2 + 2*R2)/2], 'LineStyle', ls, 'FaceColor', 'm'); hold on;

%Torus equation
syms u v
%a=R1+R2;
x_t = R2*sin(v);
y_t = (R1+R2*cos(v))*cos(u);
z_t = (R1+R2*cos(v))*sin(u);
fsurf(x_t, y_t, z_t, [0, 2*pi, 0, 2*pi], 'LineStyle', ls, 'FaceColor', 'g');

%Intersection
syms v
x_i = R2*sin(v);
y_i = (R1+R2*cos(v)).*(sqrt(1-(h/(R1+R2*cos(v)))^2) ) ;
z_i=h+v-v; %tricky to plot a 2D plot in a 3D figure
fplot3(x_i,y_i,z_i, [0, 2*pi], 'k-', 'LineWidth', 4); xlabel('x')
hold on

syms v
x_i = R2*sin(v);
y_i = -(R1+R2*cos(v))*(sqrt(1-(h/(R1+R2*cos(v)))^2) ) ;
z_i=h+v-v; %tricky to plot a 2D plot in a 3D figure
fplot3(x_i,y_i,z_i, [0, 2*pi], 'k-', 'LineWidth', 4); xlabel('x')
hold on

</code>
Comment: Is it possible that those values of $h$ correspond to non-intersections?
Comment: @preferred_anon Thanks for your reply. No, I am pretty sure there is intersection, as shown in the figures
Comment: Your [problem](https://i.stack.imgur.com/lHDnX.png) seems to go away in geogebra.
Comment: @Jan-MagnusØkland Thank you so much for your valuable response!!! I wonder whether this is a consequence of MATLAB precision (e.g. sqrt(1-1.000001) yields a complex number rather than 0). How is v varied in your Geogebra computation? Between 0 and 2pi too? Best regards
Comment: That's right. The commands used are Curve and Surface.
Comment: @Jan-MagnusØkland If you are sweeping from 0 to 2*pi then it is weird... because for the values set in your Geogebra example, you have sqrt( 1 - (2.3/(3+cos(v)))^2 ). If v is, for instance, v=2.792 rad (that is, 160 degrees), then you have a complex value: 0.0000 + 0.4960i !
Comment: The points that show up do make up the half of the curve (the other half coming from the negative square root). And you're right the values from about $v\in (2.3,4)$ don't contribute.
Comment: Many thanks for all of your responses, @Jan-MagnusØkland. After creating my own Geogebra simulation and trying other ways in MATLAB to plot this, I can confirm that my problem was only present in MATLAB visualisation using fplot/fplot3 for parametric plotting. As you suggest, complex number simply do not contribute and this happens for certain values of $h$, $R1$ and $R2$, easily identifiable as I said in my question. I hope this helps anyone else.
Answer: Hint:
Using the cartesian equation of the torus
$$
\left(R_2-\sqrt{x^2+y^2}\right)^2+z^2=R_1^2
$$
you can arrive at an equation of the form
$$
y=f(x,z)
$$
Comment: I would need in principle the parametric equations, since my problem is more complicated (I create pieces of torus joined to other volumes, controled by the angles v and u in the equations above). However, your suggestion may be interesting in case I am desperated not being able to solve this!
Answer: After creating a Geogebra simulation and trying other ways in MATLAB to plot this (simply to use the standard plot() command), I can confirm that my problem was only related to visualisation in MATLAB when using fplot()/fplot3() for parametric plotting. My "issue" with complex numbers simply had nothing to do with this. These numbers do not contribute to the plot. I hope this helps anyone else.
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Difference-in-differences with two treatments

Question: I have two groups.
Group 1 received intervention A and Group 2 received intervention B. I'm interested in seeing if intervention A is more effective than intervention B. People cannot be enrolled in both interventions at the same time.
Am I able to use difference-in-differences to compare the two interventions, or would I need to include a third group where the people receive no intervention (control group)? What I have are the dates in which someone enrolled in their respective intervention and the pre-enrollment and post-enrollment outcomes. The outcome was measured every 3-6 months pre-enrollment and every 3-6 months post-enrollment.
Also, since people can enroll in any of the interventions at different times, I would like to standardize the time dimension as the number of days before and after enrollment into the intervention. If I were to include a third group, how would I standardize time since there is no enrollment?
Comment: Welcome. First, do you have panel data? If so, then are you working with quarterly (biannual) observations over many years? Second, do individuals start treatment at different times?
Comment: Thanks. I have panel data, but it's unbalanced; measurements are taken every 3 to 6 months over many years. Individuals start treatment at different times. Since people tend to stay in their respective program for at least one year, I plan on looking at observations 365 days before program enrollment and 365 days after program enrollment.
Answer:
Am I able to use difference-in-differences to compare the two interventions, or would I need to include a third group where the people receive no intervention (control group)?

In general, a baseline group of individuals that never experience either of the two interventions is ideal. And including the two intervention groups in a single regression equation will make it easier to assess for differences between the two treatments.

The outcome was measured every 3-6 months pre-enrollment and every 3-6 months post-enrollment.

It appears individuals may opt into either of the two interventions, but not both. The interventions are therefore disjoint, so there's no reason to interact the two treatment variables. Note also that the "post-periods" vary across individuals, and so you should use the more general framework for difference-in-differences testing. Review the top answer here to help you get going.

Also, since people can enroll in any of the interventions at different times, I would like to standardize the time dimension as the number of days before and after enrollment into the intervention.

You didn't say why you're doing this, but if I may wager a guess, it's probably to do some sort of event study analysis and/or coefficient plotting. This makes sense given the context. To do this correctly, each treated individual is some number of days before or after their first day of treatment. Most refer to this practice as "centering" the treated units around the immediate intervention period.

If I were to include a third group, how would I standardize time since there is no enrollment?

You don't.
In settings with binary (i.e., 0/1) treatments, the controls remain consistently 0 for all days pre- and post-intervention. We have no reliable way to determine when the unexposed group would have entered into treatment. To see this visually, review my answer here. Note the fake data frame used for illustrative purposes; the first item (unit) is 0 in all periods.
Comment: Thank you, very helpful. When using centering, does the generalized difference-in-differences estimator need to be used, or can I use the non generalized estimator?
Comment: In settings where the timing of treatment administration differs across units, you must use the *generalized* difference-in-differences estimator.


To find all integers n such that the given expression is a perfect square

Question: The question is as follows

Determine all integers n such that $n^{4}-n^{2}+64$ is the square of an integer

Here is my approch

Let $n^{4}-n^{2}+64=k^{2}$. On multiplying both sides by 4, we get
$$4n^{4}-4n^{2}+256=4k^{2}$$
$$\Rightarrow(2n^{2}-1)^{2}+255=4k^{2}$$
$$\Rightarrow(2k+2n^{2}-1)(2k-2n^{2}+1)=255$$
The only ordered pair of factors possible are (3,85); (5,51); (15,17). We need not consider negative factors as we are squaring later.
Thus, we get $k=8, 14, 22$, which implies $k^{2}=64, 196, 484$ and finally $k^{2}-64=0, 132, 420$
$$\Rightarrow n^{4}-n^{2}=0, 132, 420$$
These 3 equations admit only $n=0, \pm1$ as integer solutions.
However, $n=\pm8$ also satisfies. Thus, my solution is incomplete or wrong

 Could anyone please point out the mistake in my solution or provide the necessary extension to fix it.Thanks a lot for help!! :)
Comment: Did you try $(1,255)$
Comment: Thanks. I missed that
Answer: Everything you did was correct, but you missed the factorization $255=1\cdot 255$. This gives $4k=1+255=256$ and so $k=64$, giving
$$n^4-n^2=k^2-64=64^2-64,$$
which gives that $n=\pm 8$ -- exactly what you missed.
Answer: Another approach:
$(n^2-n)(n^2+n)=(k-8)(k+8)\space\space\space\space\space (1)$
Since $n^2+n>n^2-n$ and $k+8>k-8$ we cnstruct following system of equations:
$\begin{cases} n^2-n=k-8\\n^2+n=k+8\end{cases}$
Sum these relations you get:
$2n^2=2k$ $\rightarrow$ $n=\pm k$
subtracting gives:
$2n=16$ $\rightarrow$ $n=8$
For $k^2$ also $-8$ can be solution.If we put $\pm 8$ in (1) RHS beomes zero and we get :
$n= 0, 1, -1$


Group theory $G \triangleright H , H \cong \mathbb{Z}, G/H \cong \mathbb{Z}/ n \mathbb{Z}$.Then Classfication of $G$

Question: Let $G$ be gorup  and $H$ be normal subgroup of $G$.
Suppose that $H \cong \mathbb{Z}$ ($\mathbb{Z}$:integer) and $G/H \cong \mathbb{Z}/ n \mathbb{Z} (\mathbb{Z} \ni n \geq 2 )$.
Then I'm stuck in next problems.
(1)If $n$ is odd number, G is abelian group.
(2)Classfy the group G up to isomorphism
Please tell me any idea and help me.
Answer: Let me give you a headstart: in general, if $N \unlhd G$, then conjugation on $N$ induces an automorphism of $N$, hence $G/C_G(N) \hookrightarrow Aut(N)$. Here $C_G(N)=\{g \in G: g^{-1}ng=n, $ for all $n \in N\}$, the centralizer of $N$ in $G$. Now $Aut(\mathbb{Z}) \cong \mathbb{Z}/2\mathbb{Z}$. Hence, if $n$ is odd, we see that in your case $G/C_G(H)$ must be trivial, that is $H \subseteq Z(G)$. Since $G/H$ is cyclic, it follows that also $G/Z(G)$ is cyclic and it is well known that implies that $G$ is abelian. This proves (1). Can you work on (2) now?
Comment: I read your response and I don't understand where "assumption $n$:odd number" uses.
I have tried it,but it dosen't work. If you do not mind, please give me help about (2) as (1).
Answer: Hint: Classify the homomorphisms $\Bbb{Z}/n\Bbb{Z}\ \longrightarrow\ \operatorname{Aut}(\Bbb{Z})$.
Comment: Sorry,What is definition of that homomorphism?
Comment: I didn't define a homomorphism. I suggested you figure out what *all* homomorphisms from $\Bbb{Z}/n\Bbb{Z}$ to $\operatorname{Aut}(\Bbb{Z})$ are. Are you familiar with semidirect products?
Comment: No,I can't figure out.
Comment: I am unfamiliar with semidirect products.
Comment: I honestly have no idea how to answer this question without semidirect products.
Comment: Please tell me the idea using semidirect products
Comment: When I ascertain it, I understand semidirect products.


Transfer Emails from a host to another (Bluehost to Hostgator

Question: I want to transfer Email accounts from Bluehost to Hostgator.
I've read everywhere that using a full cPanel backup will do the job.
My question is, can I transfer the mail dir via FTP from a host to another?
If this doesn't work, both of my hosts supports cPanel so any further advice is appreciated.
I Do not have FTP access of the old host, the owner of the previous host is giving me a TAR of the mail dir.
Comment: Questions concerning the use of **shared web hosting by end users or resellers**, rather than the administration of web hosting, are off-topic. These questions should be directed to your web hosting provider's support channels.
Answer: You have a lot of variables here. In order for your tar plan to work, you're going to need to ensure that the new mail server supports mailboxes in the format you have inside your tarball. To do this, you're going to need to know what mailserver you're using and how to configure it. To do that, you should ditch cPanel - it does things in completely non-standard ways, and obscures the details needed to actually know what is going on with your server, and which are needed to troubleshoot things in the future.
If you still have IMAP access to the old host, using imapsync would honestly be the easiest migration path. Doing this, you don't need to worry about mailbox format - the target mailserver will sort that out for you.
Answer: Using the IMAP mail protocol, you use your mail client to copy e-mails from hoster to another. If you have a bigger migration project, you can use a cloud-based IMAP migration service.
Comment: Altghough not exactly what I'm looking for, Thanks for this, I'll keep it in mind!
Comment: This might be fine for a single account, but for multiple accounts, using a standard mail client is quite laborious and error-prone.


Como abrir no tamanho original uma imagem que está dentro de um ImageView?

Question: Eu tenho algumas imagens dentro de imageView, e  precisava abrir estas imagens no tamanho original quando clicar sobre elas. Alguém sabe como fazer isso? Agradeço desde já.
Comment: O que quer dizer com "abrir"?
Comment: clicar sobre ela.
Comment: Você clica e depois? Como vai apresentá-la?
Comment: Eu achei que tinha classe pronta do Android para tratar isso, mas vou ter que pegar a ImageView clicada e mandar para uma activity com um layout grande.
Comment: Eu faço isso mesmo, abro em uma activity apenas para exibir a imagem.
Comment: e para dar zoom na imagem? como você faz? estou procurando isso agora.
Answer: Coloque essa propriedade no seu ImageView

android:scaleType="center"

Informações sobre ScaleType.
Comment: o "CENTER_INSIDE"  funcionou como eu precisava, mas vlw
Comment: @daniel12345smith `CENTER_INSIDE` não apresenta a imagem com o tamanho original, ele a redimensiona para as dimensões da *ImageView*
Comment: Sim, mas como eu coloquei a imageView dentro de um layout do tamanho da tela ficou a mesma coisa que utilizar o "wrap_content". Mas obrigado pela dica
Answer: Os atributos definidos na ImageView é que irão determinar o tamanho da imagem.
A forma de ela ser apresentada, redimensionada(scaled) ou cortada, irá depender do atributo android:scaleType.
No entanto, quando a quiser apresentar no tamanho original os atributos que definem o comprimento e largura devem ser declarados como wrap_content
android:layout_width="wrap_content"
android:layout_height="wrap_content"


Using an 8 Ohm amplifier output with a 16 Ohm cabinet

Question: My amp's highest output is 8 Ohm and the only cab I have right now is a 2 x 12 wired in series (I think), which is additive making it 16 Ohm (again, I think - Correct me if I'm wrong).
The manual for my amp says that the 8 Ohm output can be used with the 16 Ohm cab in what it calls a "Safe Mismatch".
What qualities can I expect in the sound when using a "Safe Mismatch" in this manner? The manual neglects to say what a "Safe Mismatch" actually means and how it will affect the sound produced.
As requested in some answers/comments:
It's a Mesa Boogie Mark V:25, tube amp, with selectable 25 or 10 W output for each channel.
Comment: A quick research suggests that this is different in tube vs. solid state amps. It would probably help to get a better answer if you can specify what amp you're using.
Comment: With 8 ohms output from the amp., simple safe rule is any speaker >8 ohms is fine, any speaker <8 ohms is not.
Comment: @Tetsujin: no, any solid-state amp is actually completely fine with headphone impedance.
Comment: the causes are slightly different, the results are similar
Comment: I wouldn't push that rule too far, your 250Ω headphones are not going to do it much good at all ;)
Comment: @Tim for Solid State amps yes, for Tube amps no.
Answer: A tube power amplifier (like the final stage in your Mark V) has to have an output transformer to lower the output impedance (the "Ohms") to a level appropriate to drive a speaker. What does that mean? Well if you know what voltage and current and power are, then one way to look at impedance is how much of the power you are putting out is in voltage and how much is in current? That ratio is one interpretation of impedance.
The ratio of voltage to current coming out of power tubes is relatively high. But you need lots of current to make a speaker move, so you have to trade some of that voltage in for more current. That's what a transformer does. How much do you trade in?
The answer to that question is chosen by the amp designer and is your amp's rated output impedance. That means your amp is designed to put out its rated power with a specific ratio of voltage to current. The amp will pretty much put out how much voltage it's putting out in any situation, and it's designed to put out a certain amount of current along with that. Designed meaning that if it is not allowed to put out all the current it can, then you won't get the full rated power, meaning your sound will be quieter and maybe less clear. However, if your amp is allowed to put out more current than it is supposed to, then bad things can happen.
Current creates heat, more current is more heat, and too much heat can melt things. Like your output transformer. If your transformer isn't the first to go, then there are plenty of components in the amp that can be melted or just destroyed in other ways by passing too much current.
So you have to hold your amp back from running crazy with current. This is what a speaker's nominal load impedance number is meant to indicate. It's not a precise number, but it's good enough for making sure you're not letting your amp run away with itself and overheat.
Here's the short short version: If your speaker cabinet's nominal load impedance is equal to or greater than your amp's rated output impedance, you will be safe. Safe at least in terms of not overheating your amp. If the speaker's impedance is higher, as stated before you won't get the rated output power and there may be some tonal changes. There are lots of interesting interactions between a speaker cabinet and an amplifier, so how the sound will change isn't so easy to predict, but if the speaker impedance is higher, you can safely experiment and found out how it sounds.
One more thing to check is that the rated power dissipation of the speaker cabinet is greater than the rated output power of the amp. That way all the current coming out of the amp won't melt the speaker.
If you ever get into live sound PAs, just know that it's a different world because those amps are not tube amps. You still need to pay attention to power levels for sure, impedance not so much, and the rules of thumb will be different. But that's not relevant to your question. I just didn't want you to think back to this years later and think you can set up your PA the same way as your Mark V.
Comment: I'm sorry, this is incorrect. Solid State power amps are OK with any speaker impedance which is higher than the amp but tube amps can be damaged if you run into a speaker load that is too high impedance, Usually you're safe by one order (8 ohm out into a 4, 8, or 16 for instance).
Comment: I posted a [new answer below](https://music.stackexchange.com/a/103614/19010) with more info.
Answer: If they're 2x8 Ohm in series, then yes that would give 16 - but guessing is no good.
3 ways to find out, check the maker's plate on the back, get a multimeter & test it, or take the back off & look.
For an annoyingly under-technical explanation, read on...
The reason 16 is 'safe' is that amps have a tolerance; 8 - 16 is pretty standard. Some can work down at 4 Ohms & a very few at 2. Running an amp into too low impedance will suck it dry (not a technical term ;-) & kill it pretty quickly at high volumes, through overheating.
Running into too high an impedance would really start to impact your output volume & eventually overload a valve amp's power stage.
If you really want brain-hurting detail, see How are speakers matched with audio amplifiers? (avoiding overloading either)
Answer: 16 ohm speakers are unlikely to be a problem. The term "safe mismatch" is really a misnomer. Amplifiers are not "matched" to the speakers. The amplifier output impedance is normally very low. But the amplifier has voltage, current and power limits that should not be exceeded. Additionally, valve amplifiers don't like very high impedance loads as stray inductance in the output transformer can result in very high voltages being generated. These can cause flash-over in the output tubes and/or breakdown of the output transformer insulation.
Your 16 ohm speakers will have one quite predictable effect - if the amplifier is rated at say 100W into 8 ohms, it will only deliver approximately 50W into 16 ohms.
Answer: I am not a technical savy person per say! But through experience I know that running a 16ohm speaker with a Tube Amp rated at 8ohm will not blow up your amp, only thing I have noticed is volume difference, earlier breakup of the tubes, and some noise! I have run them mismatched for years with no real technical issues with transformers, or any other component other than Tubes! The Tubes really take the blunt end of it all, they may run a little hotter than normal! But in all my years of playing and experimenting with amps and cabs, I have never had an issue!
Comment: Just don't do it the other way round.
Answer: From this site:

Impedance Mismatch Between the Power Tube and Speaker
As mentioned earlier to get the most power out of the amplifier the power tube and speaker should match their impedance. But what happens when they don't match?
Low Mismatch
If your output transformer is designed to match your power tubes to an 8 ohm speaker and you connect a 4 ohm speaker (4 ohm load and 50% decrease) then the impedance as seen by the power tube plate decreases by 50% too. Less impedance will cause plate current to increase. The power tubes are stressed by this increased plate current so the power tube lifespan can be shortened. This is especially true of Class A amps because they idle near max current flow. Since the plate current idles near maximum, the entire power supply also runs at maximum output so the rectifier tube and power transformer will run hotter. Power filtering effectiveness is reduced as current demand increases so hum and noise may increase, especially in Class A amps. Increased hum can cause ghost notes which are caused by hum interacting with musical notes to create false harmonic tones.
The increase in primary current will cause the output transformer to run hotter.
Many vintage Fender tube combo amps have an aux speaker jack that's wired in parallel with the built in speaker. Plugging in a speaker rated at the same ohms as the built in speaker will cut the speaker load in half for a "one step" low mismatch. Fender designed their output transformers to handle this and is considered safe.
But there are two possible sonic improvements with a power tube and speaker low mismatch. Sweet sounding second harmonic distortion in the power tube increases and not-so-great sounding third harmonic distortion decreases dramatically. This is why it's worth experimenting with different speaker loads, you may like the tone you get.
High Mismatch
If you connect a 16 ohm speaker to your 8 ohm output transformer the impedance as seen by the power tube plate increases and plate current decreases which can lengthen the lifespan of your power tubes, especially in Class A amps. This decrease in plate current will decrease demands on the power transformer and it will run cooler. Power filtering effectiveness is increased as current demand decreases so hum and noise should decrease, especially in Class A amps. Decreased hum can help prevent ghost notes.
Since the power tube and transformer are not coupled at maximum efficiency the amp's power output is reduced.
We get the opposite of the sonic improvements of a low impedance mismatch: Sweet sounding second harmonic distortion in the power tube decreases and nasty sounding third harmonic distortion increases.
The main problem with a high impedance mismatch is flyback voltage generated in the output transformer which can damage the power tubes and the output transformer itself. The flyback voltage spikes can cause the power tube to arc between pins or burn through the thin lacquer wire insulation used in the transformer windings. This is normally not a concern when going "one step" away from a match such as running a 4 ohm output transformer with an 8 ohm speaker unless the output transformer is cheaply made or really old. But running the 4 ohm transformer with a 16 ohm speaker can generate very high flyback voltages when running the amp hard near max volume.
If your power and/or output transformers run hot with a matched output transformer and speaker load then mismatching them is more of a risk. The bottom line is the greater the low impedance mismatch the harder your amp works, and the greater the high impedance mismatch the more likely you are to burn out your output transformer and/or power tubes. For tube amps a low mismatch is typically safer than a high mismatch. The opposite is generally true for solid state amps.

So generally, for a well built and designed amp going one step in their direction (8 into 4, or 8 into 16) should be safe. I you're running into a lower impedance your power tubes and transformer will work harder, and you'll burn out your tubes faster. If you're running into a high impedance then your tubes will have an easier time, but your output transformer risks frying itself with flyback voltages. And replacing an OT is not cheap.
So in a pinch, a "safe mismatch" is safe, but you're better off sticking to an even match if you can.
Comment: Looks like many popular amps have flyback diodes to prevent damage from flyback voltages. So which is the greater risk might depend on the specific amp design.
Comment: Those diodes would still have a safe operating spec though, so I wouldn't assume you can trust them to an infinite mismatch. Not to mention you're trusting your $500 output transformer to a 5 cent diode.
Answer: I used 16 ohm horn driver with 8 ohm pc speaker crossover/amp board the Maximum Volume is significantly reduced although it works great see bandmix.com/punkroku for audio sample
MCM Horn driver specs page: https://www.tiny.cc/mcmhorn
Answer: Personally, I would never trust a "Safe Mismatch"... Obviously, systems are protected against those who don't care and don't understand impedances, but even though they say it is safe, it will reduce the life span of the amplifier.
Tube amplifiers are more fragile to these changes mostly because the tubes heat a lot already when working like they're supposed, if you make them work like it isn't supposed to, they will heat even more...
Personally, if you really have no other choice, I would open the cab and connect only one speaker to the input, making it match the 8 ohm, you will lose the headroom and power will be half, but you'll be safe until you have another option.
For further response, the amp's type would help (tube/solid state)
Comment: It's not the valves that are damaged, it's the op transformer.
Comment: My experience: A lead from amp to speaker shorted out while setting up at a gig recently. It blew an internal fuse in my 1970 Marshall JMP. But before the fuse blew, one of the EL34 power valves glowed a really lovely and very bright purple, got incredibly hot, and stopped working. Running with too low resistance definitely can mess your valves up - although a short circuit is an extreme example.
Comment: Too low a load impedance is not considered a safe mismatch for the reasons in the comment. Too high a load impedance is safe.
Comment: Although you are right, and most common problems are in the transformers, I don't think it's too good for the valves either...
Comment: @user2808054 my point exactly...


Classification with a neural network when one class has disproportionately many entries

Question: I try to train a neural network using a dataset with several classes $c_1, c_2, \dotsc, c_{10}$. The class $c_1$ has a lot more entries in the training set than the other classes, and this makes my neural network to classify most of the the test set entries as being $c_1$.
What preprocessing should I make?
Answer: You are coping with an imbalanced dataset.
Lucky for you, you are not alone.
This is a common problem.
For surveys on the topic see Editorial: Special Issue on Learning from Imbalanced Data
Sets (6 pages) and Learning from Imbalanced Data (22 pages)
The method I like best is the following:
The method is based of the boosting algorithm Robert E. Schapire presented at "The strength of weak learnability" (Machine Learning, 5(2):197–227, 1990. The Strength of Weak Learnability ).
In this paper, Schapire presented a boosting algorithm based on combining triplets of 3 weak learners recursively. By the way, this was the first boosting algorithm.
We can use the first step of the algorithm (even without the recursion) to cope with the lack of balance.
The algorithm trains the first learner, L1, one the original data set.
The second learner, L2, is trained on a set on which L1 has 50% chance to be correct (by sampling from the original distribution).
The third learner, L3, is trained on the cases on which L1 and L2 disagree.
As output, return the majority of the classifiers.
See the paper to see why it improves the classification.
Now, for the application of the method of an imbalanced set:
Assume the concept is binary and the majority of the samples are classified as true.
Let L1 return always true.
L2 is being trained were L1 has 50% chance to be right. Since L1 is just true, L2 is being trained on a balanced data set.
L3 is being trained when L1 and L2 disagree, that is, when L2 predicts false.
The ensemble predicts by majority vote; hence, it predicts false only when both L2 and L3 predict false.
I used this method in practice many times, and it is very useful.
It also has a theoretical justification so all fronts are covered.
Comment: That's because it is a good paper... I fixed the link, Thanks.
Comment: @DanLevin: Would you mind explaining how to construct the "set on which L1 has 50% chance to be correct (by sampling from the original distribution)?" I am looking at the original paper by Schapire (thanks, by the way, for sharing it) where he defines these "oracles" as follows: `flip coin; if heads, return the first instance $v$ from the original distribution for which the predicted label is correct; else return the first instance $v$ from the original distribution for which the predicted label is incorrect`. I am confused how this would return a _set_ of points, as each call gives one point.
Comment: The use of oracles is due to the mathematical framing. I practice what will you do is to label all the samples using L1. Now you will have a set on which L1 is right and a set on which L1 is wrong. Sample x/2 items from each one of them and you are done.
Comment: the first two links seem to go to the same paper.
Comment: What if I use probabilities instead of classes? For example, my L1 and L2 learners return something like [0.15 0.85] instead of 1. How can I use L3 learner to improve my score (I use logloss) in such case?
Comment: Boosting works with probabilities too. See for example http://web.cs.iastate.edu/~honavar/singer99improved.pdf
Comment: Can you explain essence of it? Your explanation with L1, L2 and L3 was very useful and easy to understand, while this document contains a lot of math, much harder for me and other readers. Thanks in advance!
Comment: These are two separate topics. The L1-L3 algorithm is way to cope with imbalanced dataset. The paper is about boosting of classifiers that provide confidence with each prediction (e.g., the sample is positive with 80% certainty). In which of them are you interested?
Comment: My question - how to combine probabilistic predictions from L1, L2 and L3? In case of labels it's easy, I should just pick majority of votes. But what if I have probabilities and I want to reduce logloss?
Comment: The more exact way will be to use L1 as the majority and the majority rate as its confidence. From there you can continue with the algorithm described in page 4 of the above paper. A much easier way is to reduce the confidence into a predication (by using a threshold) and then use the original method. In case that the area near the boundaries (low confidence) isn't too large, the results will be quite close.
Comment: I heard on the grapevine that a good way to deal with imbalanced data sets is to simply make random copies of smaller set examples until you have balance.
Comment: @DavidC, using copies is a way to do over sampling. One clear benefit of this methods is that the new samples are indeed representative. However, you can use weight to the samples and reach the same results with a smaller data set. You can also consider techniques like smote for over sampling, getting new samples but having the risk of not being representative. https://www.jair.org/media/953/live-953-2037-jair.pdf
Answer: An important point to make here is that classifying all of the patterns as $c_1$ might be the correct answer, from a statistical decision theory perspective.  If misclassification costs are equal, we want to classify the pattern according to the class with the highest posterior probability, i.e. $p(C = c_i|\vec{x})$, which depends on the prior probabilities.  So it may be that the prior probabilities of the minority classes are sufficiently low, and the distribution of patterns for each class sufficiently broad, that the true posterior probability is always highest for the majority class.  If this is not acceptable for your application, then that probably means that your misclassification costs are not equal, so you need to think about what the costs of each kind of misclassification actually are, and build that into your cost function used to train the network.
Note if your network outputs estimates of probability of class membership, then it is offten possible to post-process the output of the trained network, rather than pre-process and retrain - see the excellent boook by Chris Bishop ("Neural Networks for Pattern Recognition").
In my experience, it isn't so much a "class imbalance problem" per se, but that there are just too few patterns from the minority class to accurately estimate their distribution, and if you increase the size of the dataset (but keep the ratios the same) the problem often goes away.


Update dinâmico com verificação de variáveis $_POST

Question: Estou com um problema. Estou montando um update dinâmico, mas não estou conseguindo montar na query a parte dos parâmetros a serem atualizados. Segue o código abaixo para ficar claro o que preciso:
function UpdateCommand($table, $params, $id){
        $database = new Database();
        $database->database_connect();

        $select = "SELECT * FROM {$table}";

        $resultselect = mysqli_query($database->database_connect(), $select);
        // Aqui não consigo dar sequência

        $query = "UPDATE {$table} SET {$params} WHERE id_{$table} = $id";
        echo $query;
        //$result = mysqli_query($database->database_connect(), $query);

        $database->database_close_connection();
    }

Esse update, serviria para qualquer tabela, que seria informada no parâmetro. O mesmo aconteceria com o id. O problema ficou na parte dos campos a serem atualizados. E duas coisas me dificultaram nisso.
1ª- Cada tabela pode ter quantidade de colunas diferentes, então pensei em montar um select para pegar essas colunas e depois usá-las com as variáveis informadas pelo formulário, porém, não consegui fazer isso.
2ª - Mesmo que eu extraia de maneira correta as colunas da tabela, como eu iria dar um SET nelas para cada coluna? Isso ficou um pouco confuso para mim.
Esqueci de colocar que eu precisaria fazer uma verificação das variáveis $_POST que foram setadas. Mas esse item aqui é menos relevante, o que importa mais é o update.
Answer: Obtendo o nome das colunas de uma tabela
$result = mysqli_query("SHOW COLUMNS FROM nome_da_tabela");
while ($row = mysqli_fetch_assoc($result)) {
    $data[] = $row;
}
print_r($data);

Setar os valores
Daqui para frente precisa adotar algum padrão para que os dados sejam compatíveis com as colunas.
Vamos supor que os dados estejam num array simples.
$dados = array('valor 1', 'valor 2', 'valor 3');

Para facilitar, os nomes das colunas devem estar também num array simples e exatamente na mesma posição de seus respectivos valores
$colunas = array('coluna_do_valor_1', 'coluna_do_valor_2', 'coluna_do_valor_3');

Então basta iterar ambos os arrays para montar a query SQL:
foreach ($colunas as $k => $v) {
    $params[] = $v." = '".$dados[$k]."'";
}
$params = implode(', ', $params);

$query = "UPDATE {$table} SET {$params} WHERE id_{$table} = $id";

Note que deve ter alguns cuidados básicos com essa lógica apresentada na pergunta pois precisa ter um padrão para campos do tipo auto incremento, normalmente o id da tabela. Como é auto incremento, não poderá ser setado no update.
Sou contra o que pretende fazer. Contudo, me abstenho em opinar e optei pela forma mais objetiva.
Comment: Daniel, tem algum outro jeito melhor para fazer isso por uma função?
Comment: Não tem função nativa para fazer todos esses processos. Crie a sua própria como já está fazendo.  Apenas demonstrei como fazer. Basta adaptar para dentro da função que está criando.


Why L1 regularization can "zero out the weights" and therefore leads to sparse models?

Question: I'm aware there is a very relevant explanation on L1 regularization's effect on feature selection at here: Why L1 norm for sparse models [Ref. 1].
To better understand it I'm reading Google's tutorial on Regularization for Sparsity: L₁ Regularization [Ref. 2].  When it comes to the following part, there's some statements I emphasized that I do not understand:

You can think of the derivative of L1 as a force that subtracts some
  constant from the weight every time. However, thanks to absolute
  values, L1 has a discontinuity at 0, which causes subtraction results
  that cross 0 to become zeroed out. For example, if subtraction
  would have forced a weight from +0.1 to -0.2, L1 will set the weight
  to exactly 0. Eureka, L1 zeroed out the weight.

I imagine when it says "L1 has a discontinuity at 0" it means the loss of the L1 like in the following  figure [Ref. 1]:

But why it will "cause subtraction results that cross 0 to become zeroed out"?
Why "if subtraction would have forced a weight from +0.1 to -0.2, L1 will set the weight to exactly 0"?
Is it related to that L1 is not differentiable at $w = 0$?
Answer: Consider their metaphor whereby L1 regularization is "a force that subtracts some constant from the weight every time".
First of all, it's only analogous to a physical force if the friction term is very high since forces induce acceleration, and acceleration is integrated to form velocity, which is integrated to form position.  If friction is high, then the velocity never persists and the integral of the force over time is roughly the total change in position.
So, consider that every time step, the position $x$ (weight or whatever you're regularizing) experiences a force that applies a total acceleration over that time step of $-k\, \textrm{sgn}(x)$.
Suppose $x$ is smaller than $k$.  It seems like applying the force would make $x$ overshoot zero.  However, if you subdivide the time step into smaller time steps and $k$ into smaller total accelerations (since the force is integrated over smaller periods), in the limit of subdivision $x$ simply goes to zero.
If this were the L2 norm, you could ask the same question about overshooting.  Only now there is a simple physical metaphor: an overdamped pendulum (in mud), which does not overshoot.


Criar coluna Média Móvel para varios ativos (python - finanças)

Question: gostaria se saber como fazer a coluna de média ao lado de cada empresa da lista
import numpy as np
import pandas as pd
import yfinance as yf

empresas1 = ['USIM5.SA','ITSA4.SA','PETR4.SA','WEGE3.SA','BBAS3.SA']
# historico de volume das empresas em colunas
hist_vol = yf.download(empresas1, period='5y')['Volume']

# definindo as coluna das médias
periodo1 = 20

# saida (resultado)
hist_vol

Resultado atual sem tratamento:

Resultado esperado para a saída dos resultados após adição das colunas:
Comment: Isto responde à sua pergunta? [Como adicionar uma nova coluna com a média do grupo em pandas?](https://pt.stackoverflow.com/questions/494909/como-adicionar-uma-nova-coluna-com-a-m%c3%a9dia-do-grupo-em-pandas)
Answer: Vou sugerir uma abordagem um pouco diferente; ao invés de partir de um dataframe onde cada coluna representa uma empresa, vamos trabalhar com um dataframe onde cada coluna representa um atributo do seu dado, e cada linha representa uma instância dele (nesse caso, podemos pensar na instância como sendo o estado da empresa em um dado ponto do tempo).
Esse tipo de formatação de dados é chamada de dados limpos ou organizados (do inglês tidy data), e facilita muito a nossa vida quando queremos realizar operações dentro de determinados grupos (no seu caso, cálculo da média móvel para cada empresa). Inclusive muitas bibliotecas de Python já estão prontas para trabalhar com dados limpos de forma bastante simples.
Primeiro passo - limpando os dados:
data = hist_vol.reset_index().melt(id_vars=['Date'], var_name='Company', value_name='Volume')
print(data)

#            Date   Company      Volume
# 0    2016-08-26  BBAS3.SA   8260600.0
# 1    2016-08-29  BBAS3.SA   8798800.0
# 2    2016-08-30  BBAS3.SA   8116800.0
# 3    2016-08-31  BBAS3.SA  18848500.0
# 4    2016-09-01  BBAS3.SA   8984100.0
# ...         ...       ...         ...
# 6200 2021-08-20  WEGE3.SA   9713000.0
# 6201 2021-08-23  WEGE3.SA   6477600.0
# 6202 2021-08-24  WEGE3.SA   7439700.0
# 6203 2021-08-25  WEGE3.SA   7436300.0
# 6204 2021-08-26  WEGE3.SA   1345200.0
#
# [6205 rows x 3 columns]

Viu como ficou mais simples? Cada coluna representa o volume de uma dada empresa em um dado ponto do tempo.
Aqui aplicamos dois métodos sobre o dataframe: reset_index serve para tirar a data do índice do dataframe e transformá-la em uma coluna padrão. Já melt serve justamente para consolidar dados espalhados em diversas colunas - dá para pensar como sendo o oposto de pivotar uma tabela.
Segundo passo - calculando a média móvel:
periodo = 20
data['Mean_Volume'] = data.groupby('Company')['Volume'].transform(lambda x: x.rolling(periodo).mean())
print(data)

#            Date   Company      Volume  Mean_Volume
# 0    2016-08-26  BBAS3.SA   8260600.0          NaN
# 1    2016-08-29  BBAS3.SA   8798800.0          NaN
# 2    2016-08-30  BBAS3.SA   8116800.0          NaN
# 3    2016-08-31  BBAS3.SA  18848500.0          NaN
# 4    2016-09-01  BBAS3.SA   8984100.0          NaN
# ...         ...       ...         ...          ...
# 6200 2021-08-20  WEGE3.SA   9713000.0    8973000.0
# 6201 2021-08-23  WEGE3.SA   6477600.0    9101260.0
# 6202 2021-08-24  WEGE3.SA   7439700.0    9136580.0
# 6203 2021-08-25  WEGE3.SA   7436300.0    8076375.0
# 6204 2021-08-26  WEGE3.SA   1345200.0    7556780.0
#
# [6205 rows x 4 columns]

Aqui, utilizamos groupby para agrupar os dados por cada empresa, e em seguida transform, que aceita uma função qualquer, aplica a cada grupo e em seguida devolve uma coluna de mesmo tamanho dos dados não-agrupados (em resumo, isso serve para criarmos uma nova coluna nos dados não-agrupados, mas cujos valores foram calculados para cada grupo). E a função que passamos para transform é justamente uma média móvel de janela = periodo.
Como esperado, a média móvel dos volumes nos primeiros pontos de tempo foram NaNs, porque ela só é calculada a partir do momento em que há um número de pontos >= periodo (a forma de calcular da média móvel pode ser configurada - veja a documentação de DataFrame.rolling aqui).
Demonstração - seus dados já estão agrupados, agora basta utilizá-los. Por exemplo, você pode obter a média móvel de uma dada empresa com:
empresa_de_interesse = 'BBAS3.SA'
valores = data.loc[data['Company'] == empresa_de_interesse]['Mean_Volume']
print(valores)

# 0              NaN
# 1              NaN
# 2              NaN
# 3              NaN
# 4              NaN
#            ...
# 1236    13849830.0
# 1237    14491865.0
# 1238    14894930.0
# 1239    14850910.0
# 1240    14518300.0
# Name: Mean_Volume, Length: 1241, dtype: float64

A biblioteca seaborn funciona muito bem para plotar dados organizados em dataframes limpos:
import seaborn as sns
import matplotlib.pyplot as plt

sns.lineplot(data=data,  x='Date', y='Mean_Volume', hue='Company')
plt.show()

Nesse caso, o argumento hue='Company' faz com que o seaborn separe a plotagem de cada empresa em linhas de cores diferentes automaticamente.
Gráfico gerado:


Your Android SDK is missing, out of date or corrupted

Question: I tried to install android studio after installing Java SE 9 version an get this error
Comment: My issue was specifically a freak issue with build-tools 33.0.0 https://stackoverflow.com/a/68430992/332578
Answer: Files -> setting -> Android SDK -> you can see the 'edit' that you can change the path of the Android SDK. ->  click the download button
Comment: I didn't have a "download" button, but clicking "next" in the wizard view worked for me.
Comment: Very odd, the regular SDK manager flow was just looping giving the above error. Follow these steps and it magically works. I think stuff was a little confused due to a recent Windows reset install.
Answer:
File > Setting > Appearance & Behavior > System Settings > Android SDK > [Edit] Button Click (Blue Color Link Button)
then, it will be show a Dialog [ SDK Setup ]
push [Next] button & [Finish] button

Good Luck ~~ ♪♬  (^.^)
Answer:
To change the update channel for an existing install, proceed as follows:

Open the Preferences window by clicking File > Settings (on Mac, Android Studio > Preferences).
In the left panel, click Appearance & Behavior > System Settings > Updates.
Be sure that Automatically check for updates is checked, then select a channel from the drop-down list (see figure).
Click Apply or OK.

It's from Android Developers Guidelines
Answer: You can go to you sdk manager and download the lastest API for sdk platform, all of sdk tools and check for SDK Update Sites
Comment: describe the way, please


CKEditor throws exception: 'n' is null or not an object

Question: I have traced the root of this exception to the sourcearea plugin of CKEditor v3.0.1.  It occurs (occasionally) after the user has entered content into the editor and he then clicks on the small arrow in the upper right hand of the editor (close toolbar arrow).  Has anyone seen this problem?  We are using IE6.
<code>onResize(){
   textarea.hide();  // EXCEPTION occurs because textarea is null
   textarea.setStyle( 'height', holderElement.$.clientheight + 'px');
   textarea.show();
};
</code>
After the problem begins (n = textarea = null), it occurs every time the right arrow is clicked.
Comment: If it's on IE6 only, I would add a != null check and be done with it. I don't know the plugin you're using but this looks like a timing issue .
Comment: I agree.  The plugin is sourcearea.
Answer: As Pekka suggested, I now check for null and call it a day.


Composite primary keys with PetaPoco for Exists and GetById methods

Question: I found this nice branch of PetaPoco by schootime which handles composite primary keys.
Now what I didn't find is how he handled in his version of PetaPoco methods which require a primary key, with composite keys like for example db.Exists and db.GetById methods.
With a single primary key you just pass the value but how to threat those methods with multiple keys? Should I pass a dictionary of string/object instead with the primary column name and the value?
If you are using this branch, any hint would be appreciated.
Also is there a way of using the Page method to query results for all the results with PetaPoco? Meaning passing no pages/items per page.
Comment: I'm unsure what you mean by your last question about paging?
Answer: These methods take an object, which can be an anonymous object. eg.
<code>db.SingleById<User>(new{ Name="John", Email="email@example.com"});
</code>
Comment: The Exists works but the IsNew does not yet.
You could always pass the page number as 1 and make the page size a really big number, but I'm not sure why you would do this. Just use `Fetch<>` if you want all the results.
Comment: Thanks Schotime this is wonderful... will Exists, IsNew, Save methods work in the same way?

About paging it was not related to this issue I was just wondering if it's possible to use the db.Page() method to request ALL results (without paging)
Comment: Yes schotime agress is a nonsense. Thank you for your support so far. Too bad petapoco development seems struck it's really wonderful bit of code


What's the difference between $\lim_{n \to \infty} \mu ([n,+\infty))$ and $\mu (\lim_{n \to \infty}[n,+\infty))$?

Question: What's the difference between $\lim_{n \to \infty} \mu ([n,+\infty))$ and  $\mu (\lim_{n \to \infty}[n,+\infty))$?
Some of my friends say that $\lim_{n \to \infty} \mu ([n,+\infty))=+\infty$ and  $\mu (\lim_{n \to \infty}[n,+\infty))=0$.
I don't know whether it's right. Is there any reference for this?
Answer: Given a sequence of sets $A_n$ with $A_{n+1}\subset A_n$, one defines
$$
\lim_{n\to\infty}A_n=\bigcap_{n=1}^\infty A_n
$$
When you have $A_n\subset A_{n+1}$, you use union instead of intersection.
In your case, if $A_n=[n,\infty)$, then $A_{n+1}\subset A_n$, so
$$
\lim_{n\to\infty} A_n=\bigcap_n A_n=\emptyset
$$
On the other hand, each $A_n$ has infinite (Lebesgue) measure.
Comment: Thank you, Reveillark!! Your answer is easy to understand. It's very helpful!
Answer: I'm assuming $\mu$ denotes the Lebesgue measure on $\mathbb R$.

First, let's address $$\lim_{n \to \infty} \mu ([n,+\infty))=+\infty$$
Clearly, $\mu ([n,+\infty))=+\infty$ for all $n\in\mathbb Z$, so the limit has to be $+\infty$.
When it comes to $$\mu (\lim_{n \to \infty}[n,+\infty))=0\tag1$$
it depends on what $\lim_{n \to \infty}[n,+\infty)$ mean as a set. One way to think about it is to consider the lim sup of sets:
$$\limsup A_n= \bigcap_{N=1}^\infty \left( \bigcup_{n\ge N} A_n \right)$$
In that case, clearly, $$\lim\sup[n, +\infty)=\emptyset$$ which leads to $(1)$.

Another  way to interpret $(1)$ is to consider the indicator function $\mathbb{1}_{[n;+\infty)}$ of $[n, +\infty)$. Then $(1)$ means $$\int_{\mathbb R}\left(\lim_{n\rightarrow+\infty} \mathbb{1}_{[n;+\infty)}\right)d\mu = 0$$
which is true by the dominated convergence theorem.
Comment: Thank you, Stefan Lafon!! Your approach is so concise and comprehensive. You are a good teacher!
Comment: You're too kind!


Performing a "reading"

Question: I'm in a university chamber music group and our director is ambitious, consistently giving us many pieces that are above our level to play with insufficient time to learn them well before performance.
When it's clear that we are not ready to perform, even if we've been practicing the piece for months, she will label it a "reading" on the concert program and have us perform anyway.
I confronted her about it, saying that I felt that was dishonest to the audience. She said that there is a musical tradition of "readings," and she's not calling them "sight readings" so it doesn't actually imply that we are seeing the piece for the first time.
To what extent is that true? What exactly is "a reading"?
Comment: Giving the audience a chance to hear an under-rehearsed version of an unfamiliar piece (or giving both the composer and the audience a chance to hear a work in progress) is one thing. Asking the audience to listen to a half-baked performance of well-known music, for whatever reason, is something else. I wouldn't expect audience members to *pay* for the second experience more than once - but if you have a captive audience of other students and the concerts are free, that changes the ground rules.
Comment: Coming from stackoverflow, I wrote a factual question about terminology and was expecting literal answers. Seems this site is friendlier -- I got not only an answer, but also some great advice & support! Thanks.
Comment: Never come across the term, but why does she do it, knowing that it could all fall apart? Pressurising you to practise more?
Comment: When this happens, do the audiences ever show any sign of being bothered, or even noticing something is wrong?
Comment: alephzero, Concerts are all free... this is actually a class at a university with very little focus on music. Audiences are very patient -- mostly our friends & family, who don't generally go to this sort of performance. @Tim Yes, I think she feels that we have to be pushed if we are to improve.
Comment: I've heard the term "reading" as a type of prepared sight reading. For instance, a composer might want a piece heard, so they schedule a "reading," giving everyone their parts a little bit in advance. This way it's not completely sight reading, but it's also not really rehearsed. But in your context I'm not sure what to say.
Comment: Your director is just, well,  wrong in all dimensions.  Pushing people beyond capabilities doesn't work here any more than it does in any other field of endeavor.  I'd strongly urge you, as a group, sit down w/ her and tell her she needs to stop (and even threaten not to play the "reading" pieces).  A huge part of ensemble play is learning to blend and interact, and that's impossible when the players can't even get the notes.  I know -- I've been in similar situations.   Rehearsing, as well as performing, music too difficult for the group is a waste of everyone's time.
Comment: That's bizarre to me. The only time I've ever done a "reading" for an audience was when the piece was newly composed and the composer was in attendance to listen to his/her own piece for the first time. It wasn't a public performance, by any means. "Reading" might also apply to groups that are choosing their repertoire: they might do a reading to judge which of several pieces they want to polish for performance. I agree with others here that your director is pushing you too hard.
Comment: I'd suggest you try to take a long-term view - look back after a year and see how much your sight-reading and general playing has improved.
Answer: I've been involved in classical music for 25 years and taught for over 10 years, and have never heard the term "reading" used like that.Sounds like your music director just made it up on the spot to justify having something to show whoever she reports to.   I'm not sure what position you're in, but perhaps report her to a higher up. In the end, probably nothing will happen to her (especially if she had tenure), but if it's not going to get you in too much trouble, at least it will go on her record.  Lastly, just try to make the best of a bad situation by trying to see how much you can push yourself to learn in such a short time. Think of it like a boot camp of sorts, it's horrible, but you'll come out the other side stronger than you came in. If anything else, it'll be a good war story to tell people one day. :) Good luck!
Comment: Thanks for the info and insight. You're right that she wants something to show... an interesting twist is that I realized I think it's really the videos she's after. The concerts are poorly advertised and barely attended, but she records video and posts the parts where we play best online. Playing under this director has indeed improved my musical abilities enormously, as well as my ability to respond gracefully to stressful situations, and to negotiate. I put my foot down and "strongly suggested" that we cut certain sections of certain pieces so that we could salvage others.

Performing a "reading"


Finding the Riemann integral of a simple function $\int_0^1f(x)dx$

Question: I am dealing with the integral: $$\int_0^1f(x)dx$$ with $$\begin{equation}
  f(x)=\begin{cases}
    0, & \text{if $x<0.5$}\\
    1, & \text{if x $\geq$ 0.5}
  \end{cases}
\end{equation}
 $$
And I would like to find the Riemann integral and test for Riemann integrability. I know that the integral must be equal to $0.5$ but when I look at the definition, I dont quite know how to formally write up a proof for this. The way I learned is, is that I split my interval $[0,1]$ in arbitrarily many smaller intervals, such that $0=x_0 < x_1 <  \ ... \ < x_m=1$.
Then I can choose points in between those smaller intervals $\xi_1,\xi_2,.....,\xi_m $ and have a Riemann sum defined as $\sum_{j=1}^mf(\xi_j)*|I_j|$ where $|I_j|$ denotes the length of an interval.
Where do I start when I want to prove that the integral is equal to $0.5$? What confuses me in a way is that I dont know how I split the interval, since I have to prove it so that it applies to all intervals, no matter how I split $[0,1]$ up. Any help is greatly apreciated.
Comment: How would you prove that the integral of $f(x)=1$ equals $0.5$ on the interval $[0.5,1]$, using Riemann sums?
Comment: For this particular function, for any partition you come up with there are 2 cases to check: one where there is an endpoint right at x=0.5 and one where 0.5 is contained in an interval. $${}$$ In the first case the Riemann sum equals the integral exactly, and in the second it is equal up to a factor of the partition's coarseness.
Answer: Here's a little bit to start you off with:
Let $N$ be the largest index for which $x_i<0.5$.
Then you know that $f(x_i)=0$ if $i\leq N$ and $f(x_i)=1$ if $i>N$.
This means that $$\sum_{i=1}^m f(\xi_i)|I_i| = \sum_{i=1}^{N-1} f(\xi_i)|I_i| +f(\xi_N)|I_N| + \sum_{i=N+1}^m f(\xi_i)|I_i|$$
and you can simplify this sum quite a lot. Both of the sums can be simplified a lot, and for the middle point, you know that no matter what $\xi_N$ is, the term $|I_N|$ must be small do it doesn't really matter.
Answer: The Riemann sum can be expressed as
$$\sum_{i = 0}^m f(\xi_i)|I_i| =\sum_{i:\; 0.5\in I_i} f(\xi_i)|I_i| + \sum_{i:\; 0.5\notin I_i} f(\xi_i)|I_i|\text{.}$$
Prove that the first sum on the right goes to $0$ (and that it contains at most two terms) and the second goes to $0.5$, when $\max_i |I_i|\to 0$.


Trying to find a good way to control servos at different speeds using johnny-five.io

Question: I am currently trying to figure out a configuration in controlling servos connected to Arduinos using Nodebot johnny-five.io hosted on an RPi. My main goal is to make a hexapod from scratch; I don't like the idea of kits because it's all cookie cutter code and parts that you put together and it's more or less a remote controlled car where you didn't learn anything.
I just learned the basics about servos (which I'm selecting servos over stepper motors). And unfortunately, as a default, servo speed cant be controlled via PWM, only position. So the way around this is to create a loop that increments the servo 1 degree (or more) at a time with an X ms delay in the loop until the servo has reached the desired position. Now, this is fine and all if you're only controlling one servo at a time or X amount of servos at a time for moving to one set position to another. But I'm shooting for a fluid motion here; I want one leg to start moving before another leg has stopped. True fluidity in motion, to accomplish this, I would need an infinite loop that would check on input states set by control commands that the API would receive.
The problem here is that while loops are not asynchronous. So, I need to find a way to kick a loop off that sets the different servos at different speed ranges and different positions, and at the end of the loop checks for new input state updates. And I need to do this without creating a memory leak.
One way would be to create a set of dependency scripts that worked asynchronously for each of the servos (3 servos per leg, 6 legs, 18 servos thus 18 mini dependencies), but I'm not sure if that would be too much overhead or put much strain onto the RPi.
Am I overthinking this?
Answer: You could create a simple servo class and give each instance its own speed and starting position using an 'update' method. Use a longer delay to have the servo move slower. In the main loop you can continuously check for some input, tell the servos to move if necessary, using the update method.
<code>#include <Servo.h>

class HexapodLegServo
{
  Servo servo;         // Servo instance
  int pos;             // Position/angle of the servo
  int delay_millis;    // 'Delay' between each update
  long prev_millis;
  int degree_change;       // Angle increase each update
  int start_pos;       // Position to start at
  int pin;             // Pin servo is connected to

  public:
    HexapodLegServo (int whichPin, int delayMillis=15, int startPos=0)
    {
      pin = whichPin;
      delay_millis = delayMillis;
      start_pos = startPos;
      degree_change = 1;
     }

     void attachToPin()
     {
       servo.attach(pin);
       setStartPos();
     }

     void setStartPos()  // Set initial position of the servo
     {
       servo.write(start_pos);
       pos = start_pos;
     }

    void update()  // Servo sweeps from end to end, and back
    {
      if (millis()-prev_millis > delay_millis)
      {
        prev_millis = millis();
        servo.write(pos);
        pos += degree_change;

        if ((pos <= 0) || (pos >= 180))
        {
          degree_change *= -1;  // Start moving in the reverse direction
        }
      }
    }
  };

// Main script
const int BUTTON = 4;  // Button on pin 4
HexapodLegServo right_leg(9);
HexapodLegServo left_leg(10, 30, 90);

void setup()
{
  Serial.begin(9600);
  pinMode(BUTTON, INPUT_PULLUP);  // Using a button to tell servos when to move

  right_leg.attachToPin();
  left_leg.attachToPin();
}

void loop()
{
  if (digitalRead(BUTTON) == LOW)  // If button is pushed (can be any type of input)
  {                                // update the position of the servos continuously
    right_leg.update();
    left_leg.update();
  }
}
</code>


Split a string in C#

Question: I have a string contains text "AA55BB10CC1DD10E123". I have to split the string and place it in List as text / value field like
AA | 55
BB | 10
CC | 1
DD | 10
E | 123
Thanks
Comment: Welcome to StackOverflow! We are not a code writing service. While we're happy to assist with your *specific* question, please show us what you've written so far and what particular problem you've encountered. Read [How do I ask a good question?](http://stackoverflow.com/help/how-to-ask) for more details.
Comment: And what have you tried?
Comment: What's your split criteria?  Any number of letters followed by any number of numeric digits?
Comment: @DStanley, seems like from first letter to last digit before letter, if you understand me
Answer: string text = "AA55BB10CC1DD10E123";
var letters = Regex.Split(text,@"\d").Where( t => !string.IsNullOrEmpty(t));
var digits = Regex.Split(text, @"[A-Z]").Where(t => !string.IsNullOrEmpty(t));
var myList = letters.Zip(digits, (l, d) => new {l,d});

Answer: Using my magic crystal ball, I have determined this was the answer you were looking for!
string[] split = Regex.Matches("AA55BB10CC1DD10E123", @"[A-Z]+\d+")
    .Cast<Match>()
    .Select(x => Regex.Match(x.Value, @"[A-Z]+").Value + "|" + Regex.Match(x.Value, @"\d+").Value).ToArray();

Answer: Please try showing what you have tried, this is what you are looking for i think.
List<string> split = Regex("[A-Z]{1}[a-z0-9]*");
    split= reg.Matches(InputText).Cast<Match>().Select(m => m.Value).ToList();

Comment: There's no reason to instantiate the list in your first line of code if you're going to just throw it away on line 3.
Comment: That is very true, it was more just to show the split using Regex.

Split a string in C#