Where would an S3 upload speed cap originate?

Question: I do a ton of uploading to S3 and am experiencing capped speeds and I can't quite figure out how to address it.
The setup: Windows Server 2008 R2 x64, external HD, using a Java based upload tool called Jsh3ll and custom VBS scripts to kick the jobs off.
Running one process at a time, I am always limited to about 4mbps. I have FiOS at 35/35mbps speeds, so it isn't an outright limit. AND, I can run parallel instances and can go all the way up to 35mbps, so I know the problem isn't gateway/nic/machine/amazon related. Running parallel instances works to a degree as a solution, but increases the complexity of my workflow greatly. Solving this would make my life dramatically easier.
When I was first doing this I was playing around with a bunch of Windows TCP parameters and was able to briefly get unconstrained bandwidth, but it wasn't repeatable.
Thoughts?
Answer: I strongly suspect you're seeing a bandwidth-delay product (BDP) artifact. A "long, fat pipe" (high bandwidth, high latency) limits the amount of data that TCP can put "in flight" at any given time. Your observation that parallel transfers run faster is a big indicator of BDP coming into play.
What's your round trip latency to S3 look like?
You might try enabling the Compound TCP Congestion Provider (CTCP) via the netsh interface tcp set global congestionprovider=ctcp command. This congestion provider is supposed to "aggressively" set the send window to put more data "in flight" on high bandwidth, high latency networks.
From the Microsoft Research paper:

For TCP connections with a large TCP Receive Window size and a large bandwidth-delay product (the bandwidth multiplied by the latency of the connection), Compound TCP (CTCP) in the Next-Generation TCP/IP stack aggressively increases the amount of data sent at one time ... In testing performed internally at Microsoft, large file backup times were reduced by almost half for a 1 Gigabit-per-second connection with a 50-millisecond round-trip time. Connections with a larger bandwidth-delay product can have even better performance.
Comment: Sorry for the delay in responding, I wanted to make sure I had a reboot and was able to test under the same conditions.

It appears that this hasn't yet solved my problem.

What else can I check? Tracert to S3 doesn't give me the full latency picture, but up to level3 in WA, I'm sub 30 ms.


create a database from a copy C# application using Azure Sql

Question: I am trying to figure out the best way to create a database from a copy of a database.
The C# application has the user register to become a user of the website and once the registration is approved then it needs to look at the Main database and create a direct copy of it. So for this example, MainDB(name of the main database) has all of the schema needed to create a copy for the user. So when the user registers it would create UserDB (name of the copy database for user).
Right now I am doing this by the below code,
        SqlConnection cn;
        SqlCommand command;
        SqlDataReader dataReader;

            cn.Open();
            string dbName = UserDB;
            command = new SqlCommand("CREATE DATABASE " + dbName + " AS COPY OF MainDB", cn);
            command.CommandTimeout = 120;
            dataReader = command.ExecuteReader();
            cn.Close();

This is working, but it is so unpredictable on how much time it takes to populate in azure, that I can not figure out a reasonable amount of time to wait before a timeout and throwing an error when creating a user for the new database.
I was wondering if there is a faster way to do this for a C# application. Possibly importing a bacpac file of the database into an Azure Data Factory, and creating the database from there? But I have not been able to find an example of this to run code using a C# application. I have just read that it reads faster, not sure if true.
Any help is much appreciated!
Comment: Is this helpful for you https://stackoverflow.com/questions/23464034/converting-a-blob-bacpac-to-bacpac-file-to-import-database-to-sql-server-azu?
Answer: I'm not sure if recovering a database from bacpac will be significantly faster. But the time spread required for recovery should be less.
The following C # code will import the database:
using Microsoft.SqlServer.Dac;

var services = new DacServices (connectionString);
services.ImportBacpac (BacPackage.Load (fileName), restoredDatabaseName, cancellationToken);

Please note that the restored database will be restored at the default price tier. This can be very important if you are restoring several small databases, each of them will consume ~ 450 $.
With the help of the following sql command you can find out in what price tier the original database was.
SELECT
    s.edition as [Edition],
    s.service_objective as [ServiceObjective],
    s.elastic_pool_name as [ElasticPoolName]
FROM
    sys.databases d
        JOIN sys.database_service_objectives s
            ON d.database_id = s.database_id
WHERE d.Name = @dbName

After importing the .bacpac, install the edition for the database:
ALTER DATABASE [@dbName] MODIFY (EDITION = @ edition, SERVICE_OBJECTIVE = @ ServiceObjective)

or elastic pool:
ALTER DATABASE [@dbName] MODIFY (SERVICE_OBJECTIVE = ELASTIC_POOL (name = [@elastic_pool_name]));

Answer: How up to date does the UserDB have to be?  I ask because if the performance is that unpredictable and responding immediately is important you'd consider running it in the background ahead of time so you have a recent DB you can use on standby.
Also is it the schema AND the data?  Because if it's just the schema then copying whole database seems like overkill.
How big is the database right now?  Bacpac files work well for small databases, but once you're in the range of a few hundred GB good luck
Happy to look further into this
Answer: If I understand the issue after looking at the code , you are creating a USERDB and want to have the schema and the data in the USERDB  from MASTERDB .
Well you can use a bacpac file ,  bacpac file is simply a ZIP file with the data for each schema . If I were you , I could have copied the files to a blob and let ADF copy the data to the USERDB . The advantage of doing this way is that we can implement parallelism in the copy activity and the USERDB is will be ready sooner .


Limitar tamanho de um item em flexbox

Question: Estou tentando fazer uma toolbar com flex, porém os ícones estão tomando toda a toolbar quando eu passo com o cursor por cima:

@media screen{

    :root{
        --primary-color: #29f1c3;
    }

    *{
        margin: 0;
        padding: 0;
    }

    img{
        max-width: 100%;
        height: auto;
    }

    /*    Navgation    */
    .main-toolbar{
        background-color: var(--primary-color);
        width: 100%;
        min-height: 56px;
        display: flex;
        justify-content: center;
    }

    .main-toolbar .menu-btn{
        background: none;
        border: none;
        outline: none;
        display: flex;
        margin-left: 3%;
        cursor: pointer;
    }

    .account-btn{
        background: none;
        border: none;
        outline: none;
        display: flex;
        flex: 1;
        flex-direction: row-reverse;
        margin-right: 3%;
        cursor: pointer;
    }

}

            <button class="menu-btn">

            </button>

            <button class="account-btn">

            </button>

Como podem ver ao passar o mouse por cima toda a toolbar fica selecionável, como faço para apenas os botões ficarem selecionáveis?
Comment: O problema é esse `flex: 1` no seu segundo botão. Se não tiver nenhum motivo específico, remova ele e substitua o `justify-content` na sua classe `main-toolbar` para: `justify-content: space-between`. Vai continuar com a mesma aparência de agora.
Comment: @Renan te entendo bem camarada, pode acreditar! A situação está cada vez pior... Força ai
Comment: @Renan seu comentário resolveu me problema, obrigado
Comment: @Renan parece que o problema é esse mesmo, pq vc não posta como resposta?
Comment: @hugocsl ando meio desanimado de participar. :/
Answer: você precisa remover o display:flex das tags button, remover também a propriedade flex:1 do segundo botão e para alinhar você pode usar a propriedade justify-content. Segue abaixo o código corrigido.
 - obs1: comentei o que precisa ser removido;
 - obs2: troquei as imagens por algumas que encontrei na web só para elas ficarem visíveis aqui.

<!doctype html>

    <meta charset="iso-8859-1">
    <title>Teste</title>

        <button class="menu-btn">

        </button>

        <button class="account-btn">

        </button>

Limitar tamanho de um item em flexbox


TensorFlow 2.0 output specification in NLP model

Question: I just started playing with TensorFlow 2.0 now that the new api is out. However, I do not get the model output specification.
The model below is a simple example from their site with the mnistdataset. If I understand correctly, there are 60000 images (28x28) pixels. Each input image has one corresponding digit (0-9) output.
import tensorflow as tf

mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

print(y_train.shape) # <-- output dimension (60000,)

model = tf.keras.models.Sequential([
  tf.keras.layers.Flatten(input_shape=(28, 28)),
  tf.keras.layers.Dense(128, activation='relu'),
  tf.keras.layers.Dropout(0.2),
  tf.keras.layers.Dense(10, activation='softmax') # <-- output nodes 10
])

model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

model.fit(x_train, y_train, batch_size=5, epochs=5)
model.evaluate(x_test, y_test)

Note from the print out, we have one dimensional training array i.e.:(60000,) but in the last layer we specify 10 nodes! Why? I understand why 10 nodes if the output was one_hot'ed - but as shown we have a single digit.
If someone can explain whats going on here - I would really appreciate it.
Answer: This works because the model uses the sparse_categorical_crossentropy loss function. It is like a regular categorical crossentropy loss that doesn't require the labels to be one-hot encoded to work!
Alternatively you could one-hot encode the labels and train on a categorical_crossentropy loss:
import tensorflow as tf

mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()

# One-hot encode the labels
y_train = tf.keras.utils.to_categorical(y_train, 10)
y_test = tf.keras.utils.to_categorical(y_test, 10)

x_train, x_test = x_train / 255.0, x_test / 255.0

print(y_train.shape) # <-- output dimension (60000, 10)

model = tf.keras.models.Sequential([
  tf.keras.layers.Flatten(input_shape=(28, 28)),
  tf.keras.layers.Dense(128, activation='relu'),
  tf.keras.layers.Dropout(0.2),
  tf.keras.layers.Dense(10, activation='softmax') # <-- output nodes 10
])

model.compile(optimizer='adam',
              loss='categorical_crossentropy',  # <-- changed loss function
              metrics=['accuracy'])

model.fit(x_train, y_train, batch_size=5, epochs=5)  # still works
model.evaluate(x_test, y_test)

Comment: The output layer is 10-wide, though, with probabilities for each digit.
Comment: Ahh I see - I did quick search after you mentioned it and found this: https://jovianlin.io/cat-crossentropy-vs-sparse-cat-crossentropy/


PB / SQLite3 JOIN TABLES

Question: I have create 3 tables, and I want data of the 3
T1

idt1 - PRIMARY KEY
n1t1
n2t1

T2

idt2 - PRIMARY KEY
n1t2
n2t2

T3

idt3
idt1 - FOREIGN KEY
idt2 - FOREIGN KEY
n1t3
n2t3
n3t3
n4t3

I search this informations : n1t1, n2t1, n1t2, n1t3, n2t3
Code :

$stmt = $db->prepare("SELECT t1.n1t1 AS t1_n1t1, t1.n2t1 AS t1_n2t1, t2.n1t2 AS t2_n1t2, t3.n1t3 AS t3_n1t3, t3.n2t3 AS t3_n2t3
    FROM t1
    INNER JOIN t3 ON t1.idt1 = t3.idt1
    INNER JOIN T2 ON T3.idt2 = T2.idt2
");

if ($result = $stmt->execute()) {
    $arr = $result->fetchArray();
    foreach ($arr as &$row) {
      echo "1 : " .  $row["t1_n1t1"] . "
";
      echo "2 : " .  $row["t1_n2t1"] . "
";
      echo "3 : " .  $row["t2_n1t2"] . "
";
      echo "4 : " .  $row["t3_n1t3"] . "
";
      echo "5 : " .  $row["t3_n2t3"] . "
";

    }
}

Errors :
I have values displayed (1: 2) it varies and above an error
Warning: Illegal string offset on somes names as n1T1 ect .
I have see that my idt1 and idt2 (FOREIGN KEY) on t3 have a column name : 0
Screen :
screen tables
I insert with a exemple.csv :
n1t3;n2t3;n3t3;n4t3
123;n2a;n3a;n4a
456;n2b;n3b;n4b
789;n2c;n3c;n4c
456;n2d;n3d;n4d

Code :
I add my FOREINGN KEY in
if (($file = fopen('exemple.csv', 'r')) === FALSE)
    echo "SQLite 3 : error CSV";

$req = $db->exec("CREATE TABLE t3 (idt3 integer PRIMARY KEY AUTOINCREMENT, idt1 integer, idt2 integer, n1t3, n2t3, n3t3, n4t3 FOREIGN KEY(idT1) REFERENCES t1(idt1), FOREIGN KEY(idt2) REFERENCES t2(idt2))");

$req = $db->prepare("INSERT INTO t3 (idt1, idt2, n1t3, n2t3, n3t3, n4t3) VALUES (:idt1, :idt2, :n1t3, :n2t3, :n3t3, :n4t3)");

$idt1 = 0;
$idt2 = 0;

$req->bindValue(':idt1', $idt1++, SQLITE3_INTEGER);
$req->bindValue(':idt2', $idt2++, SQLITE3_INTEGER);
...

I have retire first line, name table at t1 & t3 for test with it
fgetcsv($file);

But always the same error code...
New screen tables :
screen tables v2
Comment: I think that you simplified your code and the columns that you use in the query do not exist in the tables. Edit your question and post the correct code.
Comment: Please in code questions give a [mre]--cut & paste & runnable code, including smallest representative example input as code; desired & actual output (including verbatim error messages); tags & versions; clear specification & explanation. Give the least code you can that is code that you show is OK extended by code that you show is not OK. (Debugging fundamental.) For SQL that includes DBMS & DDL (including constraints & indexes) & input as code formatted as a table. [ask] Pause work on the overall goal, chop code to the 1st expression not giving what you expect & say what you expect & why.
Comment: Please [use text, not images/links, for text--including tables & ERDs](https://meta.stackoverflow.com/q/285551/3404097). Use images only for what cannot be expressed as text or to augment text. Include a legend/key & explanation with an image. PS It is hard to follow this layout, it is disorganized. Also it is hard to follow your writing. Use enough words, sentences & references to parts of examples to clearly & fully say what you mean. PS It is best to debug within one layer at a time. Show what each layer gives & gets. PS What is your 1 question?
Comment: Please before considering posting read your textbook and/or manual & google any error message or many clear, concise & precise phrasings of your question/problem/goal, with & without your particular strings/names & site:stackoverflow.com & tags; read many answers. If you post a question, use one phrasing as title. Reflect your research. See [ask] & the voting arrow mouseover texts.
Answer: whenever you join tables together with the same column name in each, you must prefix the column name with the table name (or alias) , it is a good practice to just use that syntax as a default and ALWAY prefix column names with table names (or aliases)
<?php

$stmt = $db->prepare("SELECT T1.N1 AS T1_N1, T1.N2 AS T1_N2, T2.N1 AS T2_N1, T2.N2 AS T2_N2, T3.N1 AS T3_N1, T3.N2 AS T3_N2
    FROM T1
    INNER JOIN T3 ON T1.idT1 = T3.idT1
    INNER JOIN T2 ON T3.idT2 = T2.idT2
");

if ($result = $stmt->execute()) {
    $arr = $result->fetchArray();
    foreach ($arr as &$row) {
      echo "1 : " .  $row["T1_N1"] . "
";
      echo "2 : " .  $row["T1_N2"] . "
";
      echo "3 : " .  $row["T2_N1"] . "
";
      echo "4 : " .  $row["T2_N2"] . "
";
      echo "5 : " .  $row["T3_N1"] . "
";
      echo "6 : " .  $row["T3_N2"] . "
";

    }
}

Comment: I have test this good method, but I have always this error ```Warning: SQLite3::prepare(): Unable to prepare statement: 1, no such column: T1.n1T1```
Comment: Ok I have find for what, but now I have this ```Fatal error: Call to undefined method SQLite3Stmt::fetch() ``` In start I have ```$db = new SQLite3('exemple.db');```
Comment: The same with ```$req->fetchArray()``` error ```Fatal error: Call to undefined method SQLite3Stmt::fetchArray()```
Comment: I have values displayed (1: 2) it varies and above an error ``` Warning: Illegal string offset `` `on somes names as n1T1 ect ..
Comment: Ah ok, I think I see the issue, I thought what you listed above was the column names, changing the code again, but can you please post the table structure of each table ?
Comment: I have update the code, they are columns with title name, and one without, I have add a screen of tables

PB / SQLite3 JOIN TABLES


Prove the sequence is Cauchy

Question: Prove with definition that it is Cauchy
$$a_n = \frac{n+3}{2n+1},$$ wheree $n$ is a natural number
I have seen other examples such as $\frac{1}{n}$ and such that show how to prove they are Cauchy but I am confused on how to choose $N$ in this case.
Answer: We have: For any $\epsilon > 0$, choose $N  > \dfrac{10}{\epsilon}$, and if $m , n \ge N$, then: $\left|a_m-a_n\right|=\dfrac{5|m-n|}{(2m+1)(2n+1)}<\dfrac{5}{2m+1}+\dfrac{5}{2n+1}< \dfrac{5}{m}+\dfrac{5}{n} \le \dfrac{5}{N}+\dfrac{5}{N}= \dfrac{10}{N}< \epsilon$. This shows $\{a_n\}$ is a Cauchy sequence.
Comment: Thank you. So pretty much we can make anything look like 1/n since if there's other terms in the denominator it will always be less than 1/n?
Comment: @MathMan: For this problem, yes since you have more linear terms below than above, and you can freely drop those terms you don't want. You might get $\dfrac{1}{n^2}< \epsilon$, and it still does it for $N > \sqrt{\epsilon}$.
Comment: ok thank you for your help!
Answer: Notice that $$\frac{n+3}{2n+1} = \frac12 + \frac5{4n+2}$$Clearly the $\frac12$ doesn't affect the "cauchiness" of the series, so this is equivalent to seeing whether $\frac5{4n+2}$ is cauchy, which is a very similar proof to that of $\frac1n$.

Prove the sequence is Cauchy


Unable to find a route in Laravel with Apache

Question: Every route I currently try in Laravel 4 is throwing a 404 error.
I only have two pages; the homepage, and a login page.
Now my issue is that I cant navigate to the /login route.
But when I change my login route to the default route which is 172.16.55.136/laravel/public/, then it works.
So the login route is 172.16.55.136/laravel/public/login which then gives me as 404.
This is the route file:
Route::get('/', array('as' => 'home' ,'uses' => 'HomeController@getIndex'));

Route::get('/login', array('as' => 'login', 'uses' => 'AuthController@getLogin'));
Route::post('login', array('uses' => 'AuthController@postLogin'));

I also changed my apache2 config file to the following:
<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>

Is there something else that I can do to fix this?
Answer: Your index directory should be the public folder in Laravel, as that is where the entrypoint exists (public/index.php)
Change your config to the following:
<Directory /var/www/laravel/public>
  Options Indexes FollowSymLinks
  AllowOverride All
  Require all granted
</Directory>

Then just access your laravel app at http(s)://hostname
Comment: Thanks allot @Amelia for your help, my login window now appears to be in http://172.16.55.136/laravel/public/index.php/login


How do I get name and label of fields in user profiles?

Question: I want to get the list of fields added to user profiles(listed here admin/config/people/accounts/fields). I need machine name and label of each field. How do I get them?
Answer: You can use the field_info_instances() function to get that data:
$fields = field_info_instances('user', 'user');

foreach ($fields as $field) {
  $machine_name = $field['field_name'];
  $label = $field['label'];
}

Comment: For anyone that want instance for single field, please use:
`field_info_instance('user', 'field_available_date', 'user')`
Comment: What's the third argument, `user`, for? The manual only shows two arguments: https://api.drupal.org/api/drupal/modules!field!field.info.inc/function/field_info_instances/7 `field_info_instances($entity_type = NULL, $bundle_name = NULL)`
Comment: Assuming you're referring to sobi3ch's comment @user1359, that's a different function (no 's' on the end)


Using a RAID Controller as Pass-thru vs RAID0

Question: I have a server with DellPerc H750 Storage controller.
I want to use the controller as Pass-thru/Non-RAID  but I have the below questions:
A) Is it possible in the future to replace the controller with a HBA one without losing data ?
B) If I used the RAID0 configuration for each disk independently instead of the pass-thru config , would that lead to a better performance or not ?
Answer: To answer the question A, yes. If you just do straight passthrough of the disks with NO RAID, then they are just disks and you could later change it to an HBA and it would be no different.
To answer question B, there are a few concepts being confused here. RAID0 takes many drives and stripes data across them to improve performance. You wouldn't have RAID 0 on a single disk.
Pass through is no RAID at all.


Suprema always exist $\iff$ Infima always exist

Question: Let $X$ be a poset (or only preordered or even just equipped with a plain relation).
Is it true that suprema always exist iff infima always exist:
$$\left(\forall A\subseteq X: \sup A\text{ exists}\right)\iff\left(\forall A\subseteq X: \inf A\text{ exists}\right)$$
Comment: @Carl: No, the natural numbers are not a counterexample. Consider the empty set. It has no infimum since the collection of lower bounds is the natural numbers itself and this one has no maximum.
Comment: question corrected...
Comment: If you are planning to answer your own question immediately, the least you can do is to say so explicitly in the question, so that other people can judge whether to spend time on it. But in general this should be something you do quite rarely; you have answered a large number of your own questions recently.
Comment: Oh yes you're right it'd be nice if I mention that this is meant as Q&A - will do it next times. Thanks for the advice!
Comment: Isn't $\mathbb{N}$ a counterexample to this, since it has no supremum but any subset has an infemum?  Are people answering a slightly different question than what is asked? (i.e. suprema always exist for sets with an upper bound iff infema always exist for sets with a lower bound)
Comment: @Freeze_S Yeah you're right, I didn't think about the empty subset.
Answer: Yes, indeed $\inf A=\sup A_-$ and $\sup A=\inf A_+$ with $A_+:=\{c:c\geq A\}$ and $A_-:=\{c:c\leq A\}$.
Define for brevity:
$$A\leq c:\iff a\leq c\text{ for all }a\in A$$
Since suprema are the least upper bounds resp. infima the greatest upper bounds it holds:
$$\left(\sup A_-=\min A_{-+}\leq A_{-+}\right)\text{ resp. }\left(\inf A_+=\max A_{+-}\geq A_{+-}\right)$$
But $A\subseteq A_{-+}$ resp. $A\subseteq A_{+-}$ so it also holds:
$$\left(\sup A_-=\min A_{-+}\leq A\right)\text{ resp. }\left(\inf A_+=\max A_{+-}\geq A\right)$$
Since suprema are lower bounds resp. infima upper bounds it holds:
$$\left(\sup A_-=\min A_{-+}\geq A_-\right)\text{ resp. }\left(\inf A_+=\max A_{+-}\leq A_+\right)$$
Concluding:
$$\left(\sup A_-=\inf A\right)\text{ resp. }\left(\inf A_+=\sup A\right)$$
Answer: Hint: Let $(X, \le)$ be a partial order, where every subset $Y \subseteq X$ has a supremum. Given any, $Z \subseteq X$ - we want to show it has an infimum -, let
$$ i = \sup\{y \in X \mid y \le z, \quad \text{all } z \in Z\}$$
that is the sup of $Z$'s lower bounds. Now show $i = \inf Z$.
Answer: Suppose every subset of this poset has a supremum.
Given a set $A$, let $f(A)$ be the set of all lower bounds of $A$.  Then $f(A)$ has a supremum.  Every member of $A$ is an upper bound of $f(A)$, since every member of $A$ is $\ge$ every lower bound of $A$.  Hence $\sup A\le$ every member of $A$.  In other words, $\sup f(A)$ is a lower bound of $A$.  And $\sup f(A)\ge$ every other lower bound of $A$ since $\sup A$ is by definition the supremum of the set of all lower bounds of $A$.  Hence $\sup f(A)=\inf A$.
In other words, every subset of the poset has an infimum.
PS: We can strengthen the conclusion a bit, so that it applies to some posets in which not every set has a supremum.  The strengthened conclusion says: If $A$ is any subset of a poset, and the set of all lower bounds of $A$ has a supremum, then $A$ has an infiumum.
Answer: First recall the pointwise order: for sets $A,B$,
$$A \leq B :\equiv (\forall a \in A, b \in B :: a \leq b)$$
if either is a singleton set $\{x\}$ we write just $x$ for brevity;
eg, we define upper and lower bounds as
$$A_+ := \{ u \,:\, A \leq u \} \;\;,\;\; A_- := \{l \,:\, l \leq A\}$$
Anyhow, to the task at hand,
$
\;\;\; \text{sups exist} .
\\ \equiv \text{for every set } A \text{ there is an element } s
\text{ being the least upper bound of } A
\\\equiv \forall A :: \exists s :: s \text{ upper bound of A and least such}
\\\equiv \forall A :: \exists s :: \; A \leq s \leq A_+
\\\Rightarrow \forall A :: \exists s :: \; A_- \leq s \leq A_{-+} \;
\text{by instantiation: it holds for all $A$, and so holds for $A_-$}
\\\Rightarrow \forall A :: \exists s :: \; A_- \leq s \leq A \;
\text{ since $A \subseteq A_{-+}$ and $X \subseteq Y \geq l \Rightarrow l \leq X$}
\\ \equiv \text{for every set } A \text{ there is an element } s
\text{ being a lower bound of } A \text{ and the greatest such }
\\\equiv \text{infs exist.}
$
Hence, existence of sups implies existence of infs. The converse holds by duality, (or an exercise to the reader.)
This' essentially Freeze_S's answer in a more linear form; aiming for clarity.
Hope this helps!


Universal Player Music com Web Services

Question: Alguem já fez uma aplicação com um player de musica vindo de um webservices?
Estive pesquisando um e encontrei o android-UniversalMusicPlayer da Google open source, porem tem um trecho de código que não estou conseguindo adaptar para o meu proprio webservices
<code>protected static final String CATALOG_URL = "http://storage.googleapis.com/automotive-media/music.json";
</code>
Esta linha que se encontra acima eu altero para minha propria URL, mas quando executo não aparece nenhuma musica, alguem conseguiu já fazer utilizando Retrofit?
Answer: Hector,
Se você acessar a url, vai ver como é feita a estrutura do Json que eles criaram.
Para que você somente mude a URL para o seu WebService, ele deve estar exatamente como está o criado pelo exemplo do Google.
Nele, existe uma chave chamada music que é um array:
<code>{"music" : [
    { "title" : "Jazz in Paris",
      "album" : "Jazz & Blues",
      "artist" : "Media Right Productions",
      "genre" : "Jazz & Blues",
      "source" : "Jazz_In_Paris.mp3",
      "image" : "album_art.jpg",
      "trackNumber" : 1,
      "totalTrackCount" : 6,
      "duration" : 103,
      "site" : "https://www.youtube.com/audiolibrary/music"
    }
]}
</code>
E dentro de cada laço do array, existe as informações referentes as músicas, você precisa ou deixar exatamente igual, ou mudar o parseamento do array de acordo com o seu Json.
Comment: Até esse ponto tudo bem consegui entender, a questão é que queria fazer com retrofit, e o webservices utilizo o CodeIgniter Restful, porém os resultados não obtive sucesso, e olha que estou seguindo o padrão desta estrutura json.

Universal Player Music com Web Services


firebase realtime database .orderByChild not returning correct order

Question: I am using firebase and i'd like to order my results by quoteID. However orderbychild is not getting returning the first or last item from the list that as expected.
this.props.firebase.db.ref('quotes').orderByChild("quoteId").limitToFirst(1).once("value", snapshot => {
  const entry = snapshot.val();

  console.log(entry);

})

my data structure is as follows:
{
  "1ec658d2-a7cb-45b8-8d9b-9c2a6783365d" : {
    "dateCreated" : "2019-12-02T16:06:50+01:00",
    "owner" : "DVRVSpeOXQV6wAmHAdpAe6iPQ5i2",
    "quoteID" : "200115001",
    "timeStamp" : 2075985276
  },
  "3e95a6ba-df85-4dbb-97b0-cf36df068bc1" : {
    "dateCreated" : "2019-09-27T09:17:58+02:00",
    "owner" : "xZBFCq4ho3V2G8dZTvK7RjsnTr43",
    "quoteID" : "200115002",
    "timeStamp" : 1
  },
  "d95d1f32-804b-4625-8f7e-e0bfb4f032e6" : {
    "dateCreated" : "2019-12-10T14:39:40+01:00",
    "projectName" : "testPropject timestamp2",
    "quoteID" : "191210000",
    "timeStamp" : 1575985180
  }
}

I get the entry with qouteID '200115001' returned as first single item. I cannot understand why not '191210000' is not returned first in lexographical order as described in documentation
https://firebase.google.com/docs/database/web/lists-of-data#data-order
Comment: you query "orderByChild("quoteId")  instead of "quoteID". It's probably case sensitive
Answer: The snapshot you get from Firebase contains 3 pieces of information for each matching child node:

Its key.
Its value.
Its relative position to the other returned child nodes.

When you call snapshot.val(), this data is converted to a simple JSON object. And in that object there is only place for two of these pieces of information: the key and the value. The order of keys in a JSON object is undefined, so the order of the results gets lost when you call snapshot.val().
To maintain the order, iterate over the child nodes with snapshot.forEach(). Something like this:
this.props.firebase.db.ref('quotes').orderByChild("quoteId").limitToFirst(1).once("value", snapshot => {
  snapshot.forEach((child) => {
    console.log(child.key);
    console.log(child.val());
  })
})

Comment: Hi @frank-van-puffelen, thanks for your response.
I tried your snippet, however, i still get unexpected results. As I return only 1 value from the database with .limitToFirst(1), I expect this to be the first in an ordered (by 'quoteID' ) list. However, the ordering seems to put "200115002" before "200115001" or "191210000"
Comment: Hmmm.... I misread your question. But when I try to reproduce it seems to work fine for me: https://jsbin.com/pumijoz/edit?js,console


Entity Framework - select data

Question: I haven`t got visible territory do you know why (in my LINQ)?
Example
 var student = (from s in ctx.Students
                where s.StudentName == "Student1"
                select s).FirstOrDefault<Student>();

Database (table Territories):

LINQ

LINQ with ctx have also problems

TerritoryId

Correct:
public ActionResult Index()
        {

            using (var ctx = new NORTHWNDEntities())
            {

                var Territory = (from s in ctx.Territories
                                 where s.TerritoryDescription
                                       == "Student1"
                                 select s).FirstOrDefault<Territories>();
            }

            return View();
        }

Thanks all for your time! and help.
Comment: Shouldn't be `from s in ctx.Territories`?
Comment: Do you create a variable like `using var ctx = new MyContext())`?
Comment: Do you mean your code is compiling but you can't see `Territory` in the design ? did you try refreshing the edmx, or deleting it and creating a new one ?
Comment: Do you return anything in the view at all?
Comment: @Gert Arnold this is not problem. Problem is with LINQ. In my project .ctx is not visible I make all things step by step from this tutorial. http://entityframeworktutorial.net/querying-entity-graph-in-entity-framework.aspx#.US9DNUfXono  I know there are other way to take data from table but this example is very simple and I would like to use this way.
Comment: @Gert Arnold What I have to write to have access to ctx? becuase when I write MyContext() Resharepr ask me "Create class my Context"
Comment: try to rebuild you project. or restart your computer.
Answer: Is it visible ctx in the context where you are doing the query?
The problem looks like you didn't create well an instance of your data context (ctx) or may be that variable (ctx) in not visible the that context.
Comment: You could create the local variable, or you could also declare a private variable at controller level scope and then initialize that variable in controller's contructor. Then the variable will be visible in all your actions.
Comment: you know I using VS 2010 create .edmx and now I would like to take data from Territoy using LINQ but ctx is not visible. Resharper tell me "create local variable ctx" what I have to do?
Answer: Check the class to see if the property is marked as private.
Comment: access is public to this table.
Comment: I was refering to the TerritoryID itself, it could be marked as private and the Table as public.
Comment: I edtited my post can you look it?
Answer: Shoul not be:
(from s in Territories where s.TerritoryID == "Student1" select s).FirstOrDefault<Territories>();

Answer: ctx is not something that magically appears when you create a context diagram. To use your context you must instantiate it like so:
using(var ctx = new MyContext())
{
    var territory = ....
}

where MyContext should be replaced by the name of your context class.
Comment: what I have to add because MyContext() or MyEntity() is not visible.
Comment: Well, I don't know the name of your context class. See my addition.
Comment: public partial class NORTHWNDEntities : ObjectContext
    {} <- I understand NORTHWNDEntities I have to put

Entity Framework - select data


It failed because the native React runtime does not include the Node standard library

Question: The package at node_modules\crypto-js\core.js attempted to import the Node standard library module crypto. It failed because the native React runtime does not include the Node standard library. Read more at https://docs.expo.io/workflow/using-libraries/#using-third-party-libraries
Getting this error when running npm start
Comment: did you find a solution for this?
Answer: for expo instead of crypto you can use expo-crypto
you can install it as below
expo install expo-crypto
in your codes
import React, { useEffect } from 'react';
import { StyleSheet, View, Text } from 'react-native';
import * as Crypto from 'expo-crypto';

export default function App() {
  useEffect(() => {
    (async () => {
      const digest = await Crypto.digestStringAsync(
        Crypto.CryptoDigestAlgorithm.SHA256,
        'Github stars are neat'
      );
      console.log('Digest: ', digest);
      /* Some crypto operation... */
    })();
  }, []);
...

as from expo documentation


VBA, ThisWorkbook object doesnt support property or method

Question: I am trying to copy from one workbook to another. I first open workbook B and try to copy to workbook A. However I am getting error Object doesnt support this property or method on line ThisWorkbook.Sheets("BusinessDetails").Range("C4").Paste
Shouldn't ThisWorkbook refer to the workbook and module where the code is running? What am I missing here?
Thanks.
  Sub Update()

    Dim FilePath As String
    Dim fname As Variant
    Dim myPath As String
    Dim Source As Workbook

    Application.DisplayAlerts = False

    LastRowclear = WorksheetFunction.Max(Sheets("BusinessDetails").Cells(Rows.Count, "AF").End(xlUp).Row)
    Worksheets("BusinessDetails").Range("C4:AF" & LastRowclear).Clear
    myPath = "sample path"
    fname = Dir(myPath & "Business_Level_Report*")

    Set Source = Workbooks.Open(myPath & fname)
    With Source
    .Activate
    LastRow = WorksheetFunction.Max(Sheets("BusinessDetails").Cells(Rows.Count, "AE").End(xlUp).Row)
    Source.Sheets(1).Range("B4:AE" & LastRow).Copy
    End With

    ThisWorkbook.Sheets("BusinessDetails").Range("C4").Paste

    Workbooks(fname).Close savechanges:=False

    End Sub

Answer: There's no Range.Paste method. The problem has nothing to do with ThisWorkbook.
I would use the Destination parameter of Range.Copy:
Source.Sheets(1).Range("B4:AE" & LastRow).Copy _
    Destination:=ThisWorkbook.Sheets("BusinessDetails").Range("C4")

though you can also use Range.PasteSpecial with xlPasteAll.


convexity of certain function, alternative proof

Question: I want to show that $f:\mathbf{R} \to \mathbf{R}$ given by $f(x) = |x|^p$ is convex for $p \geq 1$. But I don't want to use the derivative of $f$. How can I do this?
Really, it boils down to showing $f(\lambda x + (1-\lambda)y) \leq \lambda f(x) + (1-\lambda) f(y)$. Then I would have $|\lambda x + (1-\lambda)y|^p \leq (|\lambda x| + |(1-\lambda) y|)^p$. I thought about taking a taylor expansion here, but that doesn't seem to be a good idea.
Comment: Even if you wanted to use derivatives you can not because $|x|^p$ is not differentiable at zero.
Answer: Every supremum of affine functions is convex hence the following remarks yield the result. First, for $p=1$,
$$|x|=\sup\{x,-x\}.
$$
Second, for each $p\gt1$, let $\alpha_t^{(p)}$ denote the affine function defined by
$$\alpha_t^{(p)}(x)=a_ptx-b_p|t|^q,
$$
where $q$ is the exponent conjugate of $p$, defined by $\frac1p+\frac1q=1$. Then, for some suitable values of $a_p$ and $b_p$ that I will let you discover,
$$
|x|^p=\sup\{\alpha_t^{(p)}(x)\,;\,t\in\mathbb R\}.
$$
This can be generalized to the function $x\mapsto\|x\|^p$ in every $\mathbb R^d$, using, for $p=1$,
$$
\|x\|=\sup\{\langle t,x\rangle\,;\,t\in\mathbb R^d,\|t\|=1\},
$$
and, for $p\gt1$,
$$
\|x\|^p=\sup\{\alpha_t^{(p)}(x)\,;\,t\in\mathbb R^d\},\qquad
\alpha_t^{(p)}(x)=a_p\langle t,x\rangle-b_p\|t\|^q.
$$
Comment: @Neal No problem... :-)
Comment: Your profile says this is answer number 4000. Nicely done! :)
Comment: @Neal True (I hadn't even noticed...).
Comment: I had clicked through to your profile from another answer on a whim and noticed you had 4001 answers. I'm not stalking you, I swear!


Prove that $\gcd(n,p-1)=1$ if $p$ is the smallest prime divisor of $n$

Question: Let $n$ be a natural number greater than $1$, and $p$ be the smallest prime divisor of $n$.
How can I prove that $\gcd(n,p-1)=1$?
Answer: Hint $\ $ By hypothesis, the prime factors of $\,n\,$ are $\,\color{#c00}{\ge p}.\,$ But the prime factors of $\,p\!-\!1\,$ are $\,\color{#c00}{< p}.$
Answer: Let $k=\gcd(n,p-1)$ then $k$ divides $n$ and assume that $k>1$ so by the fundamental theorem of arithmetic any prime $p'$ that divides $k$ is a prime that divides $n$ which is impossible since $p'\le k<p$ and $p$ is the smallest prime divides $n$ so $k=1$.
Comment: What would we do without the FTA! ;-)
Answer:
Let $x_1<x_2<\dots<x_i$ be the prime factors of $n$
Let $y_1<y_2<\dots<y_j$ be the prime factors of $p-1$
We know that $y_j \leq p-1 < p = x_1$
Therefore $y_1<y_2<\dots<y_j<x_1<x_2<\dots<x_i$
Therefore $n$ and $p-1$ have no common prime factors
Therefore $\gcd(n,p-1)=1$
Answer: Assume $\gcd(n,p-1)\neq 1$. Consider $q$ a prime divisor of $\gcd(n,p-1)$.
$q|\gcd(n,p-1)|n$ and as $q$ is prime, $q\ge p$. But as $q|\gcd(n,p-1)|p-1$, $q<p$. This is impossible.
Answer: If p is the smallest prime that divides n, then there is no smaller number that divides n: proof - assume so and let q < p divide n, then by definition q is not prime, so q has prime factors which are less than q (and therefore less than p) and since q divides n then these prime factors divide n - contradiction.
If q divides p - 1, then q < p and therefore q cannot divide n, so GCD (n, p-1) = 1.
Answer: The smallest prime divisor is also the smallest non-trivial divisor. Hence $p-1$ does not divide $n$ unless $p-1=1$. In either case, this means that $\gcd (n,p-1)=1$.


Using array to attach files via mailx in bash

Question: I have just started learning bash and am working on my first small project.
I am trying to use an array as a argument to attach files using mail however though a file exists in my directory mail is returning : No such file or directory
I have tried manually typing the commands in via shell specifying the filename without the usage of arrays and this works without any errors.
Here is the code:
In my directory say for instance I have File1, File2, File3. The file names will always begin with the name "File" however the numbers for each file will differ.
First I define an array with the File numbers:
esend=(1 2 3)

Then I loop over each iteration of the array and create a copy of this array appending each iteration with -a [Filename]
# Loop over array and build the arguments for mailx.

for i in "${esend[@]}"

do

   # for each iteration append onto array with -a [filename]

   mailarray=( "${mailarray[@]}" "-a $(find -name "File$i" | sed "s|^\./||")" )

done

The values in the each index should be "-a File1 -a File2 -a File3" and now my plan is to use this as the arguments for mail
# "${mailarray[@]}"  will contain the arguments ( -a File1 -a File2 -a File3 )

echo "File being sent from mail" | mailx "${mailarray[@]}" -s "Script.sh" -r "firstname.lastname@example.com" firstname.lastname@example.com

The actual result is that mail returns File1: No such file or directory found.
Either I am doing something wrong here, or simply we cannot use this approach?
Comment: The string `"-a $(...)"` inside the loop should be two strings `"-a"` and `"$(...)"` in order for them to expand to distinct tokens (command arguments) in the final `mailx "${mailarray[@]}"` invokation.
Comment: Thanks for explaining! What you are saying makes sense and I've made a change to my code so that when the "-a" is separate string when creating the array. That fixed it for me!
Answer: In Your case You need to de-quote Your array variable mailarray in order to get represented as arguments otherwise it is represented as one string in Bash:
mailx ${mailarray[@]} -s "Script.sh" -r "email@example.com" email@example.com

But be aware that this is dangerous way e.g. any files with special characters won't be handled correctly. In addition You are also not handling multiple outputs of find. Also removing path with sed is not necessary, rather better to keep.
I would rather rewrite to something like this (supports multiple find outputs while loop, supports special characters -print0, exits with return code of mailx):
#!/bin/bash
mailargs=()
for ((i=1;i!=4;i++))
do
  while IFS= read -r -d $'\0'
  do
    mailargs+=("-a" "${REPLY}")
  done < <(find ./ -type f -name "File${i}" -print0)
done
echo "File being sent from mail"
mailx "${mailargs[@]}" -s "Script.sh" -r "email@example.com" firstname.lastname@example.com
exit $?

Consider also option e.g. to tar multiple files.


How to return the date value from DatePickerDialog in Android?

Question: I am new to android . I ve created a Date picker in android using following guide .http://developer.android.com/guide/topics/ui/controls/pickers.html
 public  class DatePickerFragment extends DialogFragment
  implements DatePickerDialog.OnDateSetListener {

StringBuilder sb = new StringBuilder();
public static String date;
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
    // Use the current date as the default date in the picker
    final Calendar c = Calendar.getInstance();
    int year = c.get(Calendar.YEAR);
    int month = c.get(Calendar.MONTH);
    int day = c.get(Calendar.DAY_OF_MONTH);

   // Create a new instance of DatePickerDialog and return it
   return new DatePickerDialog(getActivity(), this, year, month, day);
   }

  public void onDateSet(DatePicker view, int year, int month, int day) {
   // Do something with the date chosen by the user

sb.append(year);
sb.append('-');
sb.append(month+1);
sb.append('-');
sb.append(day);

date = sb.toString();
System.out.println("The date is "+date);

    }

I need to return this date value (date = sb.toString()) to my MainActivity   . Since the onDateSet method is void what should I do ?
Additional Information - DatePickerDialog Triggers at the MainActivity class ,But not with single button click . There are several processes happens in side a single button , Date picker will triggers only when certain condition is met . I do not want to display the  date value either . Just want it returned for further processing.
Appreciate any kind of guidance
Changed onDataset method and justshow()
public void onDateSet(DatePicker view, int year, int month, int day) {

// Do something with the date chosen by the user
    sb.append(year);
    sb.append('-');
    sb.append(month+1);
    sb.append('-');
    sb.append(day);

    date = sb.toString();
    MainActivity.newdate=sb.toString();
    System.out.println("The date is "+MainActivity.newdate);

}
        public void justShow(){
System.out.println("The date is "+MainActivity.newdate);

}
This is the relevant Part From Main(After making changes suggested in first reply )
    DateToken mydate=new DateToken();
    String test=dayvals.get(0);
    DialogFragment df=new DatePickerFragment();

    if(test.equalsIgnoreCase("day")){

        df.show(getSupportFragmentManager(), "DatePik");

    }

    System.out.println("Date is on Main"+newdate);

  DatePickerFragment dpf=new DatePickerFragment();
  dpf.justShow();

newdate is the static String , but still outputs null. In both MainActivity and justShow methods . But in onDataSet method date outputs correctly
Comment: [This](http://androidchennai.blogspot.in/2012/05/simple-calendar-control-android.html) is the exact reference you need
Answer:
You could create a public method in your DatePickerFragment to return the string.
You could have a static variable in your MainActivity that this class writes to.
You could use SharedPreferences to store the string.

I would go with the first option, it's the simplest if your application is basic.
There are multiple ways of going about this as you can see, so it's important to look at how the user interacts with your app and when that date is needed. The public return method is nice if you hold a reference to the Fragment in MainActivity and you don't need the data ASAP.
The static variable is nice if you need the string changed as soon as the user chooses a date.
The last method is wasteful and is least recommended, but there is no static "magic" being done.
Comment: Thanks for the reply . I have to build the string inside the onDataSet method which should be void . How can I pass the generated value to another method ? I tried following

public void justShow(){

 System.out.println("The date is "+date);

}

But when I calling justshow() method it out puts date as null , and it executing prior to onDataset method (I do not know why ) . So i am gonna try your second option
Answer: Although this was asked 4years ago and last active 1-year ago (as at my answering). I hope the below helps.
package com.example.fragments;

import java.util.Calendar;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.widget.DatePicker;

/**
 * Date picker fragment bit 18/03/2017.
 */

public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {

  private OnDateSetListener callbackListener;

  /**
   * An interface containing onDateSet() method signature.
   * Container Activity must implement this interface.
   */
  public interface OnDateSetListener {
    void onDateSet(DatePicker view, int year, int month, int dayOfMonth);
  }

  /* (non-Javadoc)
   * @see android.app.DialogFragment#onAttach(android.app.Activity)
   */
  @Override
  public void onAttach(Context activity) {
    super.onAttach(activity);

    try {
      callbackListener = (OnDateSetListener) activity;

    } catch (ClassCastException e) {
      throw new ClassCastException(activity.toString() + " must implement OnDateSetListener.");
    }
  }

  @NonNull
  @Override
  public Dialog onCreateDialog(Bundle savedInstanceState) {
    // Use the current date as the default date in the picker
    final Calendar calendar = Calendar.getInstance(getResources().getConfiguration().locale);
    int year = calendar.get(Calendar.YEAR);
    int month = calendar.get(Calendar.MONTH);
    int day = calendar.get(Calendar.DAY_OF_MONTH);

    // Create a new instance of DatePickerDialog and return it
    return new DatePickerDialog(getActivity(), this, year, month, day);
  }

  @Override
  public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
    if (callbackListener != null) {
      callbackListener.onDateSet(view, year, month, dayOfMonth);
    }
  }
}

Then do next in MainActivity
    public class MainActivity extends AppCompatActivity implements View.OnClickListener, DatePickerFragment.OnDateSetListener {

  private EditText edittextDate;

  private Locale locale;

  private DialogFragment datePicker;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    locale = getResources().getConfiguration().locale;
    datePicker = new DatePickerFragment();

    edittextDate = (EditText) findViewById(R.id.edittextDate);
    edittextDate.setOnClickListener(this);
  }

  @Override
  public void onClick(View v) {
    switch (v.getId()) {

      case R.id.edittextDate: {
        datePicker.show(getSupportFragmentManager(), "datePicker");
        break;
      }
    }
  }

  @Override
  public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
    final Calendar calendar = Calendar.getInstance(locale);
    final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);

    if (getCurrentFocus() != null) {
      switch (getCurrentFocus().getId()) {

        case R.id.edittextDate:
          calendar.set(year, month, dayOfMonth);
          edittextDate.setText(dateFormat.format(calendar.getTime()));
          break;
      }
    }
  }
}

Comment: How we can use an object that implements the ```DatePickerDialog.OnDateSetListener``` instead of use the same activity?
Comment: @JCarlos, The Activity or Fragment will still need to implement this object (which already implements _DatePickerDialog.OnDateSetListener_). Tried showing this in _ DatePickerFragment_ and _MainActivity_ above.
Answer: Implement a Listener Interface in your activity and pass it to the DatePickerFragment.
Then trigger the listener by calling it's methods.
It's described here:
http://developer.android.com/guide/topics/ui/dialogs.html#PassingEvents
Answer: Here is how you can get a Date from a DatePickerDialog:
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
    // onDateSet method
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        myday = dayOfMonth;
        mymonth = monthOfYear + 1;
        myyear = year;
        date = String.valueOf(myday) + getString(R.string.iphan) + String.valueOf(mymonth) + getString(R.string.iphan) + String.valueOf(myyear);

        Log.i(TAG,"Date: "+date);
    }
}; // DatePickerDialog.OnDateSetListener close

@Override
protected Dialog onCreateDialog(int id) {

    switch (id) {
    case DATE_DIALOG_IDdob:
        // Current Calendar Date
    final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);
    return new DatePickerDialog(this, mDateSetListener, year, month, day);
    }
    return null;
} // onCreateDialog() close

Answer: Use the below code to return the date in Date-type,  in your onDateSet() method
Date date = new Date(int year, int month, int day);

Comment: Thanks for the Reply onDateSet() method has to be void (it does not allow me to change ). Therefore I can not return anything from it
Comment: @user1855222 Declare a variable with a public scope in your main activity class. Assign the value inside the onDateSet().
Comment: I did it . But when I am calling it still gives NULL  I ve included the relevant code from MainActivity in my question after making the change  . According to logcat onDateset() executing after , my call for public variable . I don't know the reason
Answer: Declare a public string varibale on the class extnded from the DatePickerDialog class and set the selected date to that public string variable inside th onDataSet method so you can access from your MainActivity through the instance of the DatePickerDialog you created
Answer: private void openCalendar() {
DatePickerDialog dialog = new DatePickerDialog(getContext(), (view, year, month, dayOfMonth) -> {

    date = getDateString(year, month, dayOfMonth);

}, mYear, mMonth, mDay);
dialog.show();

}
private String getDateString(int year, int mMonth, int mDay) {
Calendar calendar = Calendar.getInstance();
calendar.set(year, mMonth, mDay);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
return dateFormat.format(calendar.getTime());

}
Comment: Please don't teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. Today we have so much better in [`java.time`, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. Yes, you can use it on Android. For older Android see [How to use ThreeTenABP in Android Project](https://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project).


Diffeomorphism $\varphi:(0,1)^2\rightarrow U$. $U$ is a parallelogram

Question:
Let $U\subseteq\mathbb R^2$ be a open parallelogram with vertices $(2,3), (6,4), (8,6), (4,5)$. Find a diffeomorphism $\varphi:(0,1)\times (0,1)\rightarrow U$.

How can I find such an Diffeomorphism? I tried to do it with polar coordinates but I think it is wrong.
Comment: What did you try, exactly? Please share in an [edit].
Answer: Hint: look at the coefficients in a linear combination of the vectors spanning the parallelogram.
Comment: Thanks. I got $\varphi(x,y)=(4,1)^Tx+(2,2)^Ty+(2,3)$. Is this correct?
Comment: Moritz, yep. (:


Django: class based view logout user if not staff

Question: I'm new to Django and I'm trying to use the PermissionRequiredMixin to verify if the authenticated user is staff before access to page, if he isn't authenticated the view redirects the user to the login page, on this page is loaded a form from django.contrib.auth.views.login, ok. But if the user is authenticated and he isn't staff, he will not have any form on the login page when redirected.
What should I do? Logout the user if he is not staff when he try to access the staff only page? If yes, how can I do that using the CBV with TemplateView?
View
from django.contrib.auth.mixins import PermissionRequiredMixin
# ...
class AdminView(PermissionRequiredMixin, TemplateView):
    permission_required = 'is_staff'
    template_name = 'checkout/admin.html'

login URL
from django.contrib.auth.views import login
# ...
url(r'^entrar/$', login, {'template_name': 'accounts/login.html'}, name='login')

Comment: Does the permission_required should have the value in the format ``.``??
Comment: @FazilZaid yeah, I was wondering about how to do that permission and i tried this way, just later I saw on the documentation the right way, but I don't know how `'is_staff'` is working well.
Comment: could you show the login view?
Comment: @FazilZaid it's a django built-in view, you can check it here https://github.com/django/django/blob/master/django/contrib/auth/views.py#L42
Answer: Try this mixin:
from django.contrib.auth.mixins import LoginRequiredMixin, AccessMixin
from django.contrib.auth import logout

class LogoutIfNotStaffMixin(AccessMixin):
        def dispatch(self, request, *args, **kwargs):
            if not request.user.is_staff:
                logout(request)
                return self.handle_no_permission()
            return super(LogoutIfNotStaffMixin, self).dispatch(request, *args, **kwargs)

For use it, do as follow:
class AdminView(PermissionRequiredMixin, LogoutIfNotStaffMixin, TemplateView):
    permission_required = 'is_staff'
    template_name = 'checkout/admin.html'

This mixin verifies the is_staff property (User class) in dispatch method (works for POST, GET and other request methods).


Claim that a distribution is almost Gaussian

Question: I prove a some theorem under the assumption that some random variable X is Gaussian. Now in practice, in my experiments section I have real-world samples from X, and I want to claim that indeed these samples form approximately a Gaussian distribution, therefore the conditions of the theorem approximately hold. Of course in real life nothing is exactly a Gaussian, only approximately.
Now there are some normality tests such as [link], but they all have the null hypothesis that the samples were drawn from a Gaussian distribution, therefore I can at most fail to reject this hypothesis (when p>0.05), but it still doesn't mean that my samples were drawn from an almost Gaussian distribution.
Any ideas what is the standard way to quantitatively show that my samples were drawn from an approximately Gaussian distribution?
Comment: *All* distributions are "approximately Gaussian"!
Answer: This is not a full answer to the question, because it denies the premise of the question.
Some things can be very close to Gaussian without basic properties that follow from normality holding. For example, consider a mixture that's $(1-\varepsilon)$ from a standard normal and $\varepsilon$ from a standard Cauchy, for arbitrarily small but fixed $\varepsilon>0$.
Then (for example) our distribution has no finite positive integer moments (i.e. none of the usual moments are finite). So while it may often be the case that for a wide class of distribution functions more or less similar to the normal some property may hold approximately, you may be able to get arbitrarily close (in a particular sense, such as in terms of the cdf) and not have a good many simple properties that hold for the normal. Here's an example showing population distribution and density functions for a normal and a normal mixed with a little bit of Cauchy:

NB: the $\epsilon$ on the plot - the bound on the supremum of the absolute difference in cdfs - is a smaller value that $\varepsilon$, the mixture weight on the contaminating distribution.

They're pretty hard to distinguish visually at the population level.
Some properties will hold just fine in a situation like this, but others will not.
This suggests that you have to be very careful about how sensitive the properties are to the particular kinds of non-normality you might have.
Comment: My eye kept seeing $\varepsilon$ on the plot for some reason but I probably should have chosen $\delta$ for that. I've swapped the initial $\epsilon$ to $\varepsilon$ which is not ideal but it saves me redoing the plot and at least they're not the exact same symbol now. I'll ponder a bigger edit. I appreciate the helpful question there.
Comment: Does the $\varepsilon$ on your plots have the same value as your $\epsilon$ in the text, or do you just mean two small numbers?
Comment: Thank you for pointing that out. They're not meant to be the same though the statement is plainly true if they were the same. I should have used distinct symbols. The epsilon ($\epsilon$) in the text is an unspecified small constant. The epsilon I had intended to use ($\varepsilon$) in the plot is a distinct value from that. The $\epsilon$ in the plotted example is $0.01$ for the contaminating mixture weight for illustration and the resulting bound on the supremum on the absolute difference in cdfs ($\varepsilon$) is a different, much smaller number than $\epsilon=0.01$. I will need to edit.
Answer: A normal QQ plot is always a good idea in view of the problematic nature of normality tests. The QQ plot compares sample quantiles with theoretical quantiles and so if your data lie on a straight line or approximately a straight line then you can claim approximate normality. See also How to interpret a QQ plot.
Comment: But this is not a test, and can't actually quantitatively show the Gaussian assumption. It's more like a visual check.
Comment: @StudentT The OP is well aware of the normality tests but is looking for something different, at least according to my reading of his second paragraph.
Comment: Is there any systematic research/reference that shows that people do better with a QQ plot than with any formal normality test? I doubt it. (For sure it will strongly depend on who the people are.)
Answer: The question is a very good one as you realise that not rejecting normality in a normality test does not guarantee you that the "true" distribution is "approximately Gaussian".
Unfortunately my answer to your question will be disappointing and to some extent worrying.
If you wanted to show convincingly, backed up by theory, that anything is truly "approximately Gaussian", you'd need to define formally what that means. Such a definition would normally state that the data come from some true distribution $P$ and involve a distance measure $d$ between distributions. Then it would state that there exists a normal distribution $Q$ with appropriate parameters so that $d(P,Q)$ is small enough.
Unfortunately, regardless of what $d$ is, no such thing can be shown for real data, because for starters the existence of a true underlying distribution $P$ is an idealisation, and cannot be secured to be true in reality. With the usual frequentist interpretation of probability, "real existence" of any probability would require infinite repetition of the data generation (in fact not only infinite but also "random" in a certain sense, which is hard to define as has been discussed in the literature on foundations of probability for a long time), which in reality does not happen. Any repetition is finite, and it cannot be guaranteed to be "random". So the very existence of a true probability distribution cannot be guaranteed, which would be a requirement for making sure that this distribution is "approximately something".
What you can do is to make sure that $d(P_n,Q)$ is small enough, where $P_n$ is the empirical distribution of your observed data points. This is in fact what some normality tests do. For example, Kolmogorov-Smirnov will reject normality if $d(P_n,Q)$ is too large, where $d$ is the Kolmogorov distance.
This unfortunately is weaker than what you want, because it does not imply that theory for a Gaussian random variable (i.i.d. draws from it) will approximately apply. See the answer of @Glen_b for an example; also you cannot secure independence (see https://doi.org/10.1007/s00362-023-01414-3 ), but any theory will fail if independence is critically violated (the very concept that $P_n$ represents $P$ well relies on i.i.d. sampling through Glivenko-Cantelli's Theorem). "Everything depends on everything else" in the real world said Thich Nhat Hanh, and I think he was right about this.
Unfortunately, despite the limitations of normality tests, you can therefore hardly come closer to what you want.
Ultimately we need to resort to Popper's idea of falsification. We cannot positively make sure that our theory holds, we can only put it to certain tests and see whether it is rejected.
As a side remark, it is good to have in mind also that for much theory that is based on normality, only certain deviations from normality (such as gross outliers, strong skewness, issues with independence) are problematic, whereas other deviations don't destroy results, at least not with reasonably large samples, due to the Central Limit Theorem. Standard tests of normality are not necessarily sensitive to detect the right issues, namely those that really cause trouble.
Furthermore, there is what I call "misspecification paradox", which says that if you do anything based on your data in order to decide whether data are "normal enough" or not, and then only if data look normal enough you do something that assumes normality in theory, this adds an additional problem. This is because standard theory does not take into account that there has been data based selection of what you do, and that in itself constitutes a violation of i.i.d. normality. See https://doi.org/10.52933/jdssv.v3i3.73
So the situation is a mess really, but of course still probability modelling helps as long as it helps...
Answer: "Approximately" is an essential part of any assumption because a Gaussian distribution extends from negative infinity to positive infinity. Most variables in most scientific fields have logical or physical limits, so can't possible be exactly Gaussian.
As you point out, normality tests don't ask if a distribution is close enough to Gaussian. I think this is a real gap in the statistical toolchest, so is an opportunity for someone to develop new tests or guidelines.


Angular ui-grid unable to set column width and doesn't show horizontal scrollbar

Question: I'm a newbie with AngularJS and ui-grid.
I want to show horizontal scrollbar, but it doesn't show and unable to change column width.
The width of the grid is not altered and all the columns are shrinked to fit the grid.
1st. I did copy-paste from horizontal_scrolling tutorial to my Plunker. OK. It works.
It defines column width like below code.
$timeout( function() {
  // colCount=10;
  for (var colIndex = 0; colIndex < colCount; colIndex++) {
    $scope.gridOptions.columnDefs.push({
      name: 'col' + colIndex,
      width: 200
    });
  }
});

2nd. I changed a little. But it doen't work.... 2nd example Plunker
var arr = [{name:'col0', wigth: 200},
          {name:'col1', wigth: 200},
          {name:'col2', wigth: 200},
          {name:'col3', wigth: 200},
          {name:'col4', wigth: 200},
          {name:'col5', wigth: 200},
          {name:'col6', wigth: 200},
          {name:'col7', wigth: 200},
          {name:'col8', wigth: 200},
          {name:'col9', wigth: 200}];
$timeout( function() {
  // arr.length=10;
  for (var i = 0; i < arr.length; i++) {
    $scope.gridOptions.columnDefs.push(arr[i]);
  }
});

Why 2nd example doesn't alter column width and doesn't show horizontal scrollbar?
What's the difference between 1st and 2nd?
Answer: typo wigth
change all
var arr = [{name:'col0', wigth: 200},

to
var arr = [{name:'col0', width: 200},


How to increment a cell in AG Grid React tabel?

Question: Pretty new with AG Grid library and stuck on updating the cells.
In reality, I need to do the task with dates, but just to keep it simple, I'll explain my problem with simple numbers.
I have

Start, which is 1.
Stop, which is already defined
End
Duration, which is already defined

My goal

Start = Duration + End
End = Start + Stop

Here is what I have so far

Desired result

Sandbox Link and code below
import React from "react";
import { AgGridReact } from "ag-grid-react";
import "./styles.css";
import "ag-grid-community/dist/styles/ag-grid.css";
import "ag-grid-community/dist/styles/ag-theme-alpine.css";
function App() {
  const start = 1;
  const [gridApi, setGridApi] = React.useState(null);
  const [gridColumnApi, setGridColumnApi] = React.useState(null);

  const columnDefs = [
    {
      headerName: "Name",
      field: "name"
      //valueGetter: (params) => console.log(params)
    },
    {
      headerName: "start",
      field: "start",
      valueGetter: (params) => {
        if (params.node.rowIndex !== 0) {
          return params.getValue("end") + params.data.duration;
        } else {
          return start;
        }
      }
    },
    { headerName: "stop", field: "stop" },
    {
      headerName: "end",
      colId: "end",
      valueGetter: (params) => {
        return params.data.start + params.data.stop;
      }
    },
    {
      headerName: "duration",
      field: "duration",
      colId: "duration"
    }
  ];
  const rowData = React.useMemo(
    () => [
      {
        name: "John",
        stop: 10
      },
      {
        name: "David",
        stop: 15
      },
      {
        name: "Dan",
        stop: 20
      }
    ],
    []
  );

  const durationArray = [5, 8, 6];
  const rowDataWithStart = React.useMemo(() => {
    if (durationArray) {
      return (
        rowData &&
        rowData.map((row, i) => ({
          ...row,
          start: start,
          duration: durationArray[i]
        }))
      );
    }
  }, [start, rowData, durationArray]);

  const defaultColDef = {
    flex: 1,
    editable: true
  };
  const onGridReady = (params) => {
    setGridApi(params.api);
    setGridColumnApi(params.columnApi);
  };

  return (

React-App

        <AgGridReact
          columnDefs={columnDefs}
          rowData={rowDataWithStart}
          defaultColDef={defaultColDef}
          domLayout={"autoHeight"}
          onGridReady={onGridReady}
        ></AgGridReact>

  );
}

export default App;

Any help will be appreciated
Answer: you can use valueGetter for this. I have modified the valueGetter in you code
  const columnDefs = [
    {
      headerName: "Name",
      field: "name"
      //valueGetter: (params) => console.log(params)
    },
    {
      field: "start",
      valueGetter: ({ data }) => {
        const end = data.stop + data.start
        return data.duration + end;
      }
    },
    { field: "stop" },
    {
      field: "end",
      valueGetter: ({ data }) => {
        return data.start + data.stop
      }
    },
    {
      headerName: "duration",
      field: "duration"
    }
  ];

Comment: Hey @NITHIN PB thanks for the answer. It seems not to work for me, can you update the codesandbox. please?
Comment: I updated the sandbox with your code and here is the result https://codesandbox.io/s/ag-grid-e3mge?file=/src/App.js
Comment: my bad. something wrong with your logic, it creates an endless recursion, since start and end have circular kind of dependency


Reading/editing a file from a certain point

Question: I am currently attempting to write a small piece of Java that needs to read through a file, searching for a certain line to change. The issue is that the line to change is not unique in the file as it is part of an XML-like structure so is nested inside another tag.
For example:
<tag1>Tag Text</tag1>
    <example>Value</example>

<tag2>Tag Text</tag2>
    <example>Value</example> //Want to change only this Value.

<tag3>Tag Text</tag3>
    <example>Value</example>

In this example, I want to change only the Value in the example tag under <tag2> without changing the other values.
So I am trying to search for <tag2> first, once that is found I search for <value>, edit that value and then leave the rest of the file as is.
Currently I am using a BufferedReader/Writer to copy the file to a temp file, changing a value, and then deleting the old file, replacing it with the new one.
See code below:
public class Replace {
   public static void main(String[] args) {
     new Replace().replace();
   }

   public void replace() {

    //All input data to be changed, testing purposes.
    String rootFolder = "Some root";
    String fileName = "some filename";
    String newValue = "<Value>New Value</Value>";

    //Strings to find location in the file that needs to be amended.
    String firstFileLine = "<tag2>";
    String secondFileLine = "<Value>";

    String oldFileName = rootFolder + fileName;
    String tmpFileName = "temp.txt";

      BufferedReader br = null;
      BufferedWriter bw = null;
      try {
         br = new BufferedReader(new FileReader(oldFileName));
         bw = new BufferedWriter(new FileWriter(tmpFileName));
         String line, secondLine;
         while ((line = br.readLine()) != null) {
            if (line.contains(firstFileLine)){
            //This is an attempt to try solve it, but this still replaced all <Value> tags in the file
               while ((secondLine = br.readLine()) != null) {
                    if (secondLine.contains(secondFileLine))
                        secondLine = secondLine.replace(secondFileLine, newValue);
                    bw.write(secondLine+"\n");
                }
            }
            bw.write(line+"\n");
         }
      } catch (Exception e) {
         return;
      } finally {
         try {
            if(br != null)
               br.close();
         } catch (IOException e) {
            //
         }
         try {
            if(bw != null)
               bw.close();
         } catch (IOException e) {
            //
         }
      }
      // Once everything is complete, delete old file..
      File oldFile = new File(oldFileName);
      oldFile.delete();

      // And rename tmp file's name to old file name
      File newFile = new File(tmpFileName);
      newFile.renameTo(oldFile);

   }
}

Is this the best way to be going about this issue? Any other suggestions also welcomed!
Thanks everyone in advance!
W
Answer: Your approach is correct, you need to read the old file, do the replacement and write it back. The piece that is incorrect in your current algorithm is that in the while loop you need to stop when you reach the end of tag2.
Also if the content is XML you should consider using an XML parser to do this operation.
    while ((secondLine = br.readLine()) != null) {

        if (secondLine.contains(endOfFirstLine)) {
            bw.write(secondLine+"\n");
            break;
        }

        if (secondLine.contains(secondFileLine))
            secondLine = secondLine.replace(secondFileLine, newValue);
        bw.write(secondLine+"\n");
    }

Comment: Thanks for the quick response! I'm not sure I fully understand though. Will I still need to nest this new `while` loop within the original `while` and `if` statement? Or replace the two? Also, I'm assuming `endOfFirstLine` just needs to equal the last few characters of that first tag I'm searching for?
Comment: Looking back in the file at more detail, I haven't described the tag system properly. I have now edited the tag structure to represent the file a bit better.
Comment: I have only added a condition in your original loop to stop the processing when you encounter the end of the first tag that you wanted and not continue to replace all values till the end. This is because your original code will replace all values till the end of the file after encountering the first tag1 element.


Limit Connections Per IP Windows 2008 R2 x64

Question: Hello I have been searching for a solution to this, what I want to accomplish is the ability for me to define firewall rules that will limit the amount of connections to certain ports from the same source IP address, I looked into WIPFW but it is no longer supported and the newest build for x86 will not work on my x64 Windows server (after trying numerous amount of times and installing the new sources on Dummy Net IPFW).
An external firewall solution is not an option unfortunately, nor is the option to run a virtual machine running a Linux OS that would handle iptable rules on the server.
Is there any solutions that you know of that would be able to do the things I'm asking for and it being compatible with my current configuration and limitations?
I've seen a few questions that ask the same thing and they have received lackluster responses or no responses at all, surely there must be a solution to such a simple firewall feature?
Comment: "An external firewall / linux is not an option..."  Well they are options, you've just chosen to exclude them without explaining why you can't use them.  "Surely there must be a solution.." Yes, use an external firewall / linux.  You know the answer.
Comment: @BlueCompute The point of me explaining that they aren't options is important criteria for answering the question, I'm not entitled nor do I see the point in needing to explain why they aren't, I gave the bounds with which to answer the question, questioning why these are the bounds is not helpful nor is it answering the main question directly. Thanks for the input though.
Comment: Yeah, cool, I'm just pointing out that the correct answer may well be 'This isn't a supported feature; use an external firewall.'
Answer: For IIS at least one option is Dynamic IP Restrictions which is a supported addon for IIS 7 from Microsoft. It's features include:

Dynamically blocking of requests from IP address based on either of
  the following criteria:

The number of concurrent requests.
The number of requests over a period of time.

It can be installed with the Web Platform Installer and integrates fully with IIS 7.0 Manager.

For other services/ports it is usually better to also use a solution or technique specific to it. A common one is banning an ipaddress for a while after several failed login attempts within a short period of time (like denyhosts or fail2ban on Linux/Unix systems) for services like SSH and RDP. An example for Windows would be ts_block which does it for Terminal Server connections.
Comment: Thanks Brian, I did have a look at this and all the implementations seem to be protocol specific, unfortunately I won't be using either IIS or Terminal Server connections.


How to bring animated effects in background in Android app?

Question: I am trying to add an animation ( not sure if that would be an appropriate word ) of beach waves when my app loads with its first screen.I am developing a holiday app and  have already set an image (a static image of sand ) as the background.I am expecting to have the sand image as background and have an effect of the waves hitting the shore.How should  go about achieving this? I want the waves in this pic in motion--> http://www.wallpapervortex.com/wallpaper-23493_beach_sand_sand_beach.html#.U9Rr2fldW8A
Comment: have you thought of using videoview?
Comment: @harvey_slash After going through VideoView class, I believe that is not apt to my requirement. From my understanding , VideoView along with MediaController gives option to pause while I do not require those features.
Answer: Have each frame as a seperate image in the drawable folder. After that, use an xml to define the frames(eg, ANIMATED.xml)
<code><animation-list android:id="@+id/selected" android:oneshot="false">
    <item android:drawable="@drawable/0" android:duration="50" />
    <item android:drawable="@drawable/1" android:duration="50" />
    <item android:drawable="@drawable/2" android:duration="50" />
    <item android:drawable="@drawable/3" android:duration="50" />
    <item android:drawable="@drawable/4" android:duration="50" />
    <item android:drawable="@drawable/5" android:duration="50" />
 </animation-list>
</code>
And to make it animate, use this:
<code>// Load the ImageView that will host the animation and
 // set its background to our AnimationDrawable XML resource.
 ImageView img = (ImageView)findViewById(R.id.moving_image);
 img.setBackgroundResource(R.drawable.ANIMATED.xml);

 // Get the background, which has been compiled to an AnimationDrawable object.
 AnimationDrawable frameAnimation = (AnimationDrawable) img.getBackground();

 // Start the animation (looped playback by default).
 frameAnimation.start();
</code>


Is $\lceil x \rceil=\frac{1}{2}(1+ \sum_{n=-\infty}^{+\infty}(\operatorname{sgn}(x-n)-|\operatorname{sgn}(x-n)|+1+\operatorname{sgn}(n)))$ true?

Question: I'm looking for a function that defines $\lceil x \rceil$ and I found the following:
$$\lceil x \rceil=\frac{1}{2}(1+ \sum_{n=-\infty}^{+\infty}(\operatorname{sgn}(x-n)-|\operatorname{sgn}(x-n)|+1+\operatorname{sgn}(n)))$$
Explanation:
first I noticed that plotting $\lceil x \rceil$ yields a graph that looks like a staircase, so I started combining "steps" and offsetting them by $n$
($a$ and $b$ are the upper and lower bounds of the stairs; $a\le 0$)
$$\frac{1}{2}\sum_{n=a}^{b}(\operatorname{sgn}(x-n)+1)$$
but because of the $\operatorname{sgn}$ function, all integers are lowered by $0.5$. So I adjust it with $-\left|\operatorname{sgn}\left(x-n\right)\right|$
$$\frac{1}{2}\sum_{n=a}^{b}\left(\operatorname{sgn}\left(x-n\right)-\left|\operatorname{sgn}\left(x-n\right)\right|\right)$$
and finally, I make both functions coincide:
$$\lceil x \rceil=\frac{1}{2}(1+ \sum_{n=-\infty}^{+\infty}(\operatorname{sgn}(x-n)-|\operatorname{sgn}(x-n)|+1+\operatorname{sgn}(n)))$$
Unfortunately Wolfram Alpha doesn't seem to like this function; I would greatly appreciate it if you could prove this/simplify it  or find a way to rewrite it without the sum
Comment: $|\text{sgn}(x-n)|$ is simply just $1$ so you can simplify your series as $\sum_{n=-\infty}^\infty(\text{sgn}(x-n)+\text{sgn}(n))$
Comment: I can't edit my comment but the sum should be $\sum_{n\in\mathbb{Z}\backslash\{x\}}(\text{sgn}(x-n)+\text{sgn}(n))+\text{sgn}(x)$
Comment: Is $sgn(0) = 0$ or is $sgn(0) = 1$?
Comment: Seems to work.  You should trust yourself to verify it.
Comment: It works so long as $x$ is not an integer.  It's off by 1 or 1/2 if $x$ is an integer.
Answer: We can do it in cases:
1a) $x < 0; x\not \in \mathbb Z$.
Then
$\frac{1}{2}(1+ \sum_{n=-\infty}^{+\infty}(\operatorname{sgn}(x-n)-|\operatorname{sgn}(x-n)|+1+\operatorname{sgn}(n)))=$
$\frac 12(1 + \sum_{n< x< 0}(\operatorname{sgn}(x-n)-|\operatorname{sgn}(x-n)|+1+\operatorname{sgn}(n)) + \sum_{x< n< 0}(\operatorname{sgn}(x-n)-|\operatorname{sgn}(x-n)|+1+\operatorname{sgn}(n)) + (\operatorname{sgn}(x-n)-|\operatorname{sgn}(x-n)|+1+\operatorname{sgn}(n))_{n=0} + \sum_{n=1}^{\infty}(\operatorname{sgn}(x-n)-|\operatorname{sgn}(x-n)|+1+\operatorname{sgn}(n))=$
$\frac 12(1 + \sum_{n< x< 0}(1-1+1+-1) + \sum_{x< n< 0}(-1-1+1+-1) + (-1-1+1+0)_{n=0} + \sum_{n=1}^{\infty}(-1-1+1+1)=$
$\frac 12(1 + \sum_{n< x< 0}0 + \sum_{x< n< 0}(-2) + (-1) + \sum_{n=1}^{\infty}(0)=$
$\sum_{x<n<0} (-1)=\sum_{n=-1;n--}^{\lceil x\rceil}(-1)=-\sum_{n=1}^{|\lceil x\rceil|}1= -|\lceil x\rceil|$ and as $\lceil x\rceil \le 0$ this is equal to $\lceil x\rceil$ (maybe I should note that if $-1 < x < 0$ then $\sum_{n=-1;n--}^{\lceil x\rceil}(-1)$ is $0$ as the condition for the summand is never met so this is a sum with zero terms.)
1b) $x < 0; x\in \mathbb Z$.
This is much as above but we have an addition term $(sgn(x-n)-|sgn(x-n)| +1 sgn(n))_{n=x}= 0-0+1-1= 0$.
Hmmm this doesn't seem to work as in this case: $\sum_{x<n<0} (-1)=\sum_{n=-1;n--}^{x+1}(-1)=x+1\ne \lceil x\rceil$
Case 2: $x=0$ then
$\frac{1}{2}(1+ \sum_{n=-\infty}^{+\infty}(\operatorname{sgn}(x-n)-|\operatorname{sgn}(x-n)|+1+\operatorname{sgn}(n)))=$
$\frac{1}{2}(1+ \sum_{n=-\infty}^{1}(\operatorname{sgn}(x-n)-|\operatorname{sgn}(x-n)|+1+\operatorname{sgn}(n))+(\operatorname{sgn}(x-n)-|\operatorname{sgn}(x-n)|+1+\operatorname{sgn}(n))_{n=0=x} + \sum_{n=1}^{\infty}(\operatorname{sgn}(x-n)-|\operatorname{sgn}(x-n)|+1+\operatorname{sgn}(n)))=$
$\frac{1}{2}(1+ \sum_{n=-\infty}^{1}(1-1+1+1)+(0-0+1+0) + \sum_{n=1}^{\infty}(-1-1+1+1)=\frac 12$
Hmm, doesn't seem to work.  If $sgn(0) =1$ (it might, I never know what the conventions is) we still get the error that this is equal to $ 1$.
Case 3:  $x > 0; x\not \in \mathbb Z$.
This is similar to the above.  For $n> x$ we have $(\operatorname{sgn}(x-n)-|\operatorname{sgn}(x-n)|+1+\operatorname{sgn}(n))= -1-1 + 1 +1 =0$ and for $n<0$ we have $(\operatorname{sgn}(x-n)-|\operatorname{sgn}(x-n)|+1+\operatorname{sgn}(n))=1-1+1-1=0$ so
$\frac{1}{2}(1+ \sum_{n=-\infty}^{+\infty}(\operatorname{sgn}(x-n)-|\operatorname{sgn}(x-n)|+1+\operatorname{sgn}(n)))=$
$\frac{1}{2}(1+(\operatorname{sgn}(x-n)-|\operatorname{sgn}(x-n)|+1+\operatorname{sgn}(n))_{n=0}+ \sum_{n=1}^{\lfloor x \rfloor}(\operatorname{sgn}(x-n)-|\operatorname{sgn}(x-n)|+1+\operatorname{sgn}(n)))=$
$\frac{1}{2}(1+(1-1+1+0)+ \sum_{n=1}^{\lfloor x \rfloor}(1-1+1+1)=$
$1 + \sum_{n=1}^{\lfloor x \rfloor}1 = 1 +\lfloor x \rfloor= \lceil x \rceil$.
And finally.
2b.  $x > 0; x\in \mathbb Z$.
This gives us
$\frac{1}{2}(1+(\operatorname{sgn}(x-n)-|\operatorname{sgn}(x-n)|+1+\operatorname{sgn}(n))_{n=0}+ \sum_{n=1}^{x-1}(\operatorname{sgn}(x-n)-|\operatorname{sgn}(x-n)|+1+\operatorname{sgn}(n)))+ (\operatorname{sgn}(x-n)-|\operatorname{sgn}(x-n)|+1+\operatorname{sgn}(n))_{x=0}=$
$\frac 12(1 + 1 + 2(x-1) + (0-0+1+1)= x + \frac 12$.
So
You're formula does work if $x$ is not an integer.


P-value adjustment for a single test with low sample size

Question: I have a dataset of 2 conditions. Each condition has 15 measurements. I tested them using paired t-test to find if the difference is statistically significant. Should I use a p-value correction method for such a single test with a small sample size? If I should, which methods are suitable for this case (except Bonferroni)?
Comment: Bonferroni "correction" with m=1 returns the same p-value that you input. With just one hypothesis test, you don't have multiple comparisons to correct for, so it doesn't do anything at all. The formula still "works" for m=1, so you can apply Bonferroni correction, but it's pointless.
Answer: No, for a single test you have a single p-value, thus no correction method is needed. Indeed, multiple comparisons problem arises when you perform many statistical tests or when you build many confidence intervals on the same data. Also, the small sample size issue is irrelevant to the multiplicity issue.
If you are worried about the validity of the p-value in light of the small sample size, then you may try a test via Bootstrap or permutation.
Comment: Are you sure that bootstrapping is a good idea with small samples?
Comment: @usεr11852 Do you mean to state that all techniques are equally robust to small sample size? Personally I don't think this is great advice.
Comment: @dipetkov Why wouldn't it be? A small sample is an issue irrespective of the technique. https://stats.stackexchange.com/questions/112147 has a good discussion on this (+1 to the answer).
Comment: @dipetkov reading Chapter 2 of Davison and Hinkley's book on the Bootstrap couldn't find any contraindications. Indeed, scholars such as https://www3.stat.sinica.edu.tw/statistica/j33n2/j33n222/j33n222.html, use the bootstrap to improve inference in problems with low n/p.
Comment: @dipetkov: Start with $n=2$. :) (Of course, bootstrap is not a panacea but on the other hand, it is a reasonable suggestion in the context of this answer and an unreasonable point to critique it without context. The smaller the sample size, the smaller our power as a general principle, bootstrap or our favourite technique doesn't change that.)
Comment: @usεr11852 One thing I've learned about bootstrapping from reading about bootstrapping is that testing hypotheses is not exactly where it shines. Why mention all kinds of statistical procedures in an answer and not attempt to suggest to the OP what might work best for their situation?
Comment: @usεr11852 My suggestion, which should be quite obvious by now, is that bootstrapping a p-value when there not one but two small samples is bad advice. (Though I acknowledge you disagree.) I suggest that a permutation test is a better choice, if the OP wants to consider a non-parametric approach.
Comment: @usεr11852 I have no idea why you felt compelled to jump in. I thought utobi's answer was appropriate, except for the bootstrap suggestion. So I asked about it. I didn't do it in a disrespectful manner. That's probably a good enough reason to not be having this discussion.
Comment: I thought your comment was appropriate but asked you to elaborate on your comment cause I couldn't understand where you were coming from as it gave no alternative suggestions. Small sample sizes are primarily affected by power, not significance issues in my view so I saw bootstrapping as a reasonable suggestion in the answer.
Comment: @dipetkov How are permutations gonna work with a paired t-test which is effectively a one sample t-test. What are you gonna permute in this single sample? I guess that resampling by means of bootstrapping is the only resampling that can be done here.
Comment: @dipetkov Are you sure that permutations are a good idea with paired data? Personally I don't think this is great advice and even worse than bootstrapping (which is more or less fine for n=15).
Comment: Also related: https://stats.stackexchange.com/questions/482654/is-bootstrap-problematic-in-small-samples
Comment: @usεr11852 The paper you link to, isn't it about parametric bootstrapping? I wonder if that has something to do with small sample sizes?
Comment: 1. I didn't link any paper. 2. You haven't made any suggestions. (which is actually the main reason I commented in the first place.)
Comment: Thank you for being constructive. (+1) 1. I also think that permutation tests are preferable to bootstrapping when it comes to testing. (That doesn't mean though that bootstrapping is an unreasonable suggestion for this ask.) 2. If you had mentioned permutation tests in your initial comment we wouldn't need this discussion.
Comment: @dipetkov More generally: I personally believe, that if one has a critique, they should give an alternative too. I have come across quite a few occasioons where people will undermine a half-reasonable suggestion without an alternative suggestion as to simply "show off" while being lazy to put their money where their mouth is. Academic debates are often rife with that.
Comment: @SextusEmpiricus I find this is a somewhat bizarre hill to die on (ie, write comments that are not as well thought out as they might have been). For the OP here is how to do a permutation test on paired data: [Randomisation/permutation test for paired vectors in R](https://stats.stackexchange.com/q/64212/237901).
Comment: @SextusEmpiricus This entire thread of comments started with me wondering whether utobi is giving out good advice... So I won't disagree. (Also I'm worried about the pile on continuing.) I find Dave wrote a better answer so that's the answer I upvoted.
Comment: @usεr11852 While this issue is not black-and-white, I have been going over some of my reading: Tim Hesterberg. *What Teachers Should Know about the Bootstrap: Resampling in the Undergraduate Statistics Curriculum.*
https://doi.org/10.48550/arXiv.1411.5279. "Bootstrap hypothesis testing is relative undeveloped, and is generally not as accurate as permutation testing. For example, we noted earlier that it is better to do a permutation test to compare two samples, than to pool the two samples and draw bootstrap samples." [NB: the statement is not about paired data.]
Answer: With a small sample size, there are legitimate concerns.

What kind of power do you have to reject a false null hypothesis?

If your data lack normality, do you have enough data for the t-test to be robust to the deviation to the assumed normality?

The latter feeds into the second, as deviations from normality tend to affect t-test power, rather than t-test size. That is, such deviations from the assumed normality make it more difficult to reject false null hypotheses, rather than making it easier to reject true null hypotheses.
However, having a small sample size does not make it so your test statistic lacks the claimed distribution. The small sample size is accounted for by using a low number of degrees of freedom. What could be concerning is that, when the sample size is low, the true distribution of the t-stat might differ to a meaningful extent from the claimed distribution, meaning that your p-values are not really telling you what they are supposed to tell you, since they are calculated from incorrect distributions.
Since you only have one test, no p-value adjustment is needed to account for multiple tests.
Answer: (This answer ignores the issue with low sample size.)
I'd like to add a bit of nuance to the answers here, as it's tempting to read them and come away with this rule:

If a single p-value is observed, then correction is unnecessary; the type I error of the testing procedure is not inflated.

Type I error is inflated if any part of the testing procedure, i.e., any part of the pipeline from dataset -> p-value, depends on the data. Read The garden of forking paths1 paper for more info.
For example, if—

(in another universe) the observations turn out to be so skewed that after plotting them you opt to test for the equality of medians rather than means, and
you do not want to inflate the type I error

—then a p-value adjustment needs to be made. For example, if you were to use a Bonferroni correction, then the number of null hypotheses here is 2: one for the mean test, and one for the median test. Note that you did not have to observe 2 p-values; you just had to use a testing procedure which allowed for 2 different hypotheses (whether you knew it or not!).
Adjustment is unnecessary if universes like (1) don't exist, or you don't care about inflating type I error. To destroy universes like (1), the entire testing procedure needs to be pre-specified, e.g., force yourself to test for the equality of means regardless of the observed distribution (such a decision should usually be based on the science—not the data—anyway). In practical terms, this means implementing the entire data analysis code without looking at any data from your experiment.
References

Gelman, Andrew, and Eric Loken. "The garden of forking paths: Why multiple comparisons can be a problem, even when there is no "fishing expedition" or "p-hacking" and the research hypothesis was posited ahead of time." Department of Statistics, Columbia University 348 (2013): 1-17.


How to use the verbose name of a language choice in Django-Countries with Django Filter

Question: I have this Django Filter:
from django_countries.data import COUNTRIES

owner__nationality = filters.MultipleChoiceFilter(choices=COUNTRIES, widget=Select2MultipleWidget)

So I guessed I just use the original choices field to filter on nationality (for which I used Django Countries to fill the data)
As you can see in the source code here, the import is correct:
https://github.com/SmileyChris/django-countries/blob/master/django_countries/data.py
However on the front end the dropdown looks like this:

How can I get full countries to be displayed there? I also don't quite understand why there is only one letter there. Can somebody clarify?
By the way I know about get_FOO_display()
Comment: you just need to add in models.py **`    Country                 = CountryField(blank_label='Select Country')
`** why you want select multiple country
Comment: I try to pull the hard-coded choice data, so I can use it with `Django-Filter` Not the `CountryField`.
Comment: The models are already declared and populated with the `CountryField`. Right now I try to get the choice data so I can run it against a Queryset.
Answer: MultipleChoiceFilter takes iterable of tuples as as choices. Package you mentioned provides COUNTRIES as dictionary. Try doing
from django_countries.data import COUNTRIES

owner__nationality = filters.MultipleChoiceFilter(
    choices=[(k, v) for k, v in COUNTRIES.items()],
    widget=Select2MultipleWidget
)


How many images with bounding boxes are in the ImageNet object detection dataset?

Question: I am trying to understand how many images with object-detection bounding boxes are in ImageNet dataset, and how many objects are there in these images.
In MS-COCO paper, it says:

"Recently, a detection challenge has been created from 200 object
categories using a subset of 400,000 images from ImageNet. An
impressive 350,000 objects have been labeled using bounding boxes."

Are there less objects than images? Later in the paper it says:

MS COCO contains considerably more object instances per image (7.7) as
compared to ImageNet (3.0) and PASCAL (2.3)

In the ImageNet website it says 1,034,908 images with bounding boxes.
These numbers seem to conflict.
What am I missing? Does anyone know the correct image and object numbers?
Note: I'm not looking for the number of images with classification annotations, just the object detection annotations.
Answer: From the ILSVRC 2014 website that in the image detection dataset there are 476,688 images with 534,309 objects


How to calculate $\int xe^{1/x^2} \ dx$

Question: How would I go about integrating $\int xe^{1/x^2} \ dx$?
I attempted a u-substitution and integration by parts already, but that didn't get me anywhere.
Comment: Is there a reason you expect that there is a closed form for this integral?
Comment: According to [wolframalpha](http://www.wolframalpha.com/input/?i=integrate+x+*+e%5E%28x%5E%28-2%29%29), there are no closed form solutions.
Comment: Complementing Henry: http://www.wolframalpha.com/input/?i=integrate+xe%5E%7B1%2Fx%5E2%7D+dx
Answer: Even if the result is not the most simple, it corresponds to a closed form (even if the final result does not involve only elementary terms).
You want to compute
$$I=\int x\, e^{\frac{1}{x^2}}\,dx$$ Let us perform one integration by parts $$du=x\,dx \implies u=\frac{x^2}{2}$$ $$v=e^{\frac{1}{x^2}}\implies dv=-\frac{2 e^{\frac{1}{x^2}}}{x^3}\, dx$$ So $$I=\int x\, e^{\frac{1}{x^2}}\,dx=\frac{1}{2} e^{\frac{1}{x^2}} x^2+\int\frac{e^{\frac{1}{x^2}}}{x}\,dx$$ Now, consider $$J=\int\frac{e^{\frac{1}{x^2}}}{x}\,dx$$ and change variable $x=\frac{1}{\sqrt{y}}$, $dx=-\frac{1}{2 y^{3/2}}\,dy$.
So $$J=\int\frac{e^{\frac{1}{x^2}}}{x}\,dx=-\frac 12 \int\frac{e^y}{ y}\,dy$$ The last integral is the definition of $\text{Ei}(y)$, the exponential integral. Back to $x$, we then get the result given by Wolfram Alpha $$I=\frac{1}{2} \left(e^{\frac{1}{x^2}} x^2-\text{Ei}\left(\frac{1}{x^2}\right)\right)$$ If you have to compute the value of this integral between bounds, for large values of $x$, you could use as an approximation $$\text{Ei}\left(\frac{1}{x^2}\right)=\gamma-2\log(x)
  +\frac{1}{x^2}+\frac{1}{4 x^4}+\frac{1}{18 x^6}+\frac{1}{96
   x^8}+O\left(\left(\frac{1}{x}\right)^9\right)$$
Answer: $\int xe^\frac{1}{x^2}~dx$
$=\int x\sum\limits_{n=0}^\infty\dfrac{x^{-2n}}{n!}dx$
$=\int\sum\limits_{n=0}^\infty\dfrac{x^{1-2n}}{n!}dx$
$=\int\left(x+\dfrac{1}{x}+\sum\limits_{n=2}^\infty\dfrac{x^{1-2n}}{n!}\right)dx$
$=\int\left(x+\dfrac{1}{x}+\sum\limits_{n=0}^\infty\dfrac{x^{-2n-3}}{(n+2)!}\right)dx$
$=\dfrac{x^2}{2}+\ln x+\sum\limits_{n=0}^\infty\dfrac{x^{-2n-2}}{(n+2)!(-2n-2)}+C$
$=\ln x+\dfrac{x^2}{2}-\sum\limits_{n=0}^\infty\dfrac{1}{2(n+2)!(n+1)x^{2n+2}}+C$

How to calculate $\int xe^{1/x^2} \ dx$