How to calculate error when $\sigma=0$ in a test sample?

Question: A test has probability $P_f$ of failure where it is expected that $.0001 <P_f < .01$.
Given $N$ test samples where all tests succeed and there were no failures (thus $\sigma=0$), what is the best way to estimate the approximate value of $P_f$  assuming that is nonzero? What would be the most appropriate method to calculate error bars for this test?
Comment: Might be relevant: https://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval
Comment: Your description is not clear. What meaning have error bars in this situation? $\sigma$ does not make sense. A look at binomial tests (in Wiki) may be helpful.
Comment: There is no correct answer. My simplified rule of thumb would be to use $\frac1{2N}$ with an interval of $\left[0,\frac{2.5}{N}\right]$
Answer: From the help in the comments it looks like the rule of three is applicable here where the probability of failure would be $\approx \frac3N$ with 95% confidence.
Answer: BEGINING OF EDIT

When I wrote this, I misread your post.  I treated success as rare rather than failures.  The answer is the same, however.

END OF EDIT
There is a good first principles solution to this problem.  You know that $$.0001<\theta<.01.$$  It appears you have no further information regarding the content so that $\theta$ can be treated as being drawn from a uniform distribution over the interval.  Since probability density functions must sum to one, $$\Pr(\theta)=10000/99,\theta\in(.0001,.01).$$
This is a binary process so the likelihood, given no other information, is the binomial distribution.  For illustration purposes, let us assume you have not observed "success" in the rare event, but you have seen 500 failures.  The likelihood of seeing this is $$\theta^0(1-\theta)^{500}.$$  The posterior density is $$\Pr(\theta|500 failures)=530.368(1-\theta)^{500}.$$
The highest density region is on the left side of this interval.  The 95% highest density region will solve $$\int_{.0001}^a 530.368(1-\theta)^{500}=.95$$
The result is that $a=.00596166$ so your interval is $(.0001,.00596166)$.
This is not a confidence interval, it is a Bayesian credible interval.  Its interpretation is not that if you repeated this same experiment, then the true value of the parameters will be in at least 95% of the intervals. Instead, it is that there is a 95% chance the true value of the parameter is in the interval.
Abstractly, your solution is, for an $\alpha$% highest density region solution, $$\text{If }\Pr(.0001<\theta<\gamma|n=N;k=0)=\alpha\text{ then}\int_{.0001}^\gamma\frac{\frac{10000}{99}(1-\theta)^{(n-k)}}{\int_{.0001}^{.01}\frac{10000}{99}(1-\theta)^{(n-k)}\mathrm{d}\theta}\mathrm{d}\theta=\alpha,$$  where $n$ is the total number of observations and $k=0$, the successes.
Because of the prior, your variance can be estimated.  The variance of the example posterior is $$\frac{500}{501^2\times502}=\frac{250}{63001251}.$$


How to change category for Panels IPE

Question: How would I change the category from "Fielded panes" in Panels IPE to something else?
I can accomplish this through the following code:
function template_preprocess_panels_add_content_modal(&$vars) {
  $i = 0;
  foreach($vars['categories_array'] as $item) {
    $new_item = str_replace("Fielded panes", "New Content", $item);
    $vars['categories_array'][$i] = $new_item;
    $i++;
  }
}

However, I'd like to find a more elegant solution by altering the category name in a function that runs before template_preprocess_panels_add_content_modal().
Answer: Have a look at template_preprocess_panels_add_content_modal() and $vars['categories']. You should be able to override the category names there.
Edit:
Ahh, yes, I forgot about hook_ctools_content_subtype_alter(). That's more elegant :)
From the documentation:

This hook can be used to add things like 'render last' or change icons
  or categories or to rename content on specific sites.

In the example below the category "Fielded panes" is changed to "New category name".
/**
 * Implements hook_ctools_content_subtype_alter().
 */
function MYMODULE_ctools_content_subtype_alter(&$subtype, &$plugin) {
  if ($subtype['category'] == 'Fielded panes') {
    $subtype['category'] = 'New category name';
  }
}

Comment: By the time that function runs, $vars['categories_array'] has already been built, and so overriding $vars['categories'] doesn't do anything.
Answer: After some research, I discovered that this can easily be accomplished via hook_ctools_content_subtype_alter().
  /**
  * Implements hook_ctools_content_subtype_alter().
  */
  function MYMODULE_ctools_content_subtype_alter(&$subtype, &$plugin) {
    if ($subtype['category'] == 'Fielded panes') {
      $subtype['category'] = 'New category name';
    }
  }

I also discovered that I can alter the title and the icon by doing something like this:
/**
* Implements hook_ctools_content_subtype_alter().
*/
function MYMODULE_ctools_content_subtype_alter(&$subtype, &$plugin) {
  // Change title and icon for rich_text Fielded panel pane content
  if (isset($subtype['bundle']) && $subtype['bundle'] == 'rich_text') {
    $subtype['title'] = 'Custom Content';
    $subtype['path'] = 'sites/default/files/ctools/icons';
    $subtype['icon'] = 'content.png';
  }
}

How to change category for Panels IPE


Receber e converter stream de server remoto para string

Question: Estou fazendo um script que recebe um stream, em formato hexadecimal,de um servidor remoto via conexão TCP, afim de quebrar a sua criptografia e ler uma mensagem ASCII que se encontra nele. Meu objetivo e ler esse stream, e converte-lo para string, a fim de rodar o script que fiz (que considera como input somente strings).
Eu sou novo em Ruby. Não estou conseguindo nem ao menos ler o stream que chega ao meu programa. Eu posso, através de um site provido para esse desafio, visualizar os packets que saem do servidor. Eles são assim:
003B60558EB661BC55D2305E4A8AC07E6D518ABEE7A2BFE7B7B2A5E7B6B2AEBDE7A4B5A8B0A3E7A0A6B1A2E7ADA8BEA1B2ABE7B3AFA6A9ACB4E901

E tenho recebido isso no meu terminal (em tentativas pífias de ao menos ler o stream):
7�����焉(��hX@FB^T\[NSVQC]BZG^YPMRUEVDARO

Como ler esse stream, converte-lo para o seu formato normal normal e , finalmente, o converter para string?
Answer: Para converter o stream para string você pode utilizar o seguinte one-liner:
"<seu stream hex>".split('').each_slice(2).map {|char| char.join.hex.chr }.join

é não é uma solução elegante, mas é suficiente pra suprir sua necessidade.
Quanto a parte de conexão com o socket TCP e leitura dos pacotes vindos do servidor, dê uma olhada na classe TCPSocket da biblioteca-padrão do Ruby (a última versão, 2.2.1, pode ser encontrada aqui: http://ruby-doc.org/stdlib-2.2.1/libdoc/socket/rdoc/TCPSocket.html).


De que forma destacar um item do menu ao clicar Voltar ou Avançar

Question: Isso é possível, sei que estou no caminho, mas antes resolvi ver com a comunidade o que pode ser feito nesse caso, e aí sim tomar o rumo certo.
Código

function Selecionado(tag){
var item = document.getElementById('menu');

var link = item.getElementsByTagName('a');

for ( var i = 0; i < link.length; i++ ){

 link[i].style.backgroundColor = "";
 link[i].style.color = "";
}
   tag.style.backgroundColor = "#ff0000"; // Cor de fundo do link
   tag.style.color = "#ffffff"; // Cor atual do link
}
* { margin: 0; padding: 0; list-style: none; }

button { float: left }

#menu li {
 float: left;
 margin: 5 10px;
 position: relative;
}

a {
  cursor: pointer; padding: 3px; text-decoration: none; color: #111;
}
a.ativo {
  font-weight: bolder;
  background-color: #333;
  color: #fff;
}
<button id="menos">&#171 Voltar</button>

1

2

3

4

5

<button id="mais">Avançar &#187</button>

Tem a lógica toda numa só função e o item de menu que ficará em destaque, terá a sua cor de fonte alterada assim como o fundo
Para isso, só preciso ler o id menos/mais para saber que direção tomar.

Na prática é preciso dar o movimento a esses botões de um modo que fique selecionado um item menu por vez, conforme cada clique
Vide um exemplo - Cabeçalho Paginação
Detalhe
Preciso de Exemplos numa linguagem simples sem: APIs, DOM4 e ECMAScript 5
Não são amplamente compatível com diversos navegadores(obsoleto)
Answer: Podes fazer assim, usas a função muda(num), que recebe 1 ou -1.

var id;
function Selecionado(tag,thisid){
  id=thisid;
var item = document.getElementById('menu');

var link = item.getElementsByTagName('a');

for ( var i = 0; i < link.length; i++ ){

 link[i].style.backgroundColor = "";
 link[i].style.color = "";
}
   tag.style.backgroundColor = "#ff0000"; // Cor de fundo do link
   tag.style.color = "#ffffff"; // Cor atual do link
}

function muda(num){
  id+=num;
  var item = document.getElementById('menu');

var link = item.getElementsByTagName('a');

for ( var i = 0; i < link.length; i++ ){

 link[i].style.backgroundColor = "";
 link[i].style.color = "";
}

  document.getElementById(id).style.backgroundColor = "#ff0000"; // Cor de fundo do link
  document.getElementById(id).style.color = "#ffffff"; // Cor atual do link
}
<button id="menos" onclick="muda(-1);">&#171 Voltar</button>

1

2

3

4

5

<button id="mais" onclick="muda(1);">Avançar &#187</button>


Using "String" in openCl Kernel

Question: I have a question about OpenCl programming. The scenario is : I have a list of words taken from a file with different length and I have to pass this list to OpenCl Kernel. I've tried to use a struct compposed by an array of char that contains the word and an int that contains the size. But this kind of solution doesn't work because, in the Kernel, I must create a new array with the size indicated in the struct, but the Kernel doesn't like arrays of variable size. There is a way to implement this solution (I mean creating one array per thread of different size)? If there is no solution in this way, how can I do?
Thank you :)
EDIT : This is the example code.. I hope it clarify the things
typedef struct word{
    char word[100];
    int len;
}word_t;
__kernel void test(__global word_t *data,  __global res_t *result)
{
   size_t id=get_global_id(0);
   int size=0;
   size=data[id].len;
   char word[size];
   //working with the word

}

But the clBuildProgram says that I cannot have an array with variable size..
Comment: Please provide some code, it's difficult to see what you're attempting to do.
Answer: You can't use variable length arrays like this in OpenCL so you could use a fixed maximum length array if you can limit your word length as an easy solution.
#define MAX_WORD_LEN 100
#define WORK_GROUP_SIZE 128

typedef struct word{
    char word[MAX_WORD_LEN];
    int len;
}word_t;

__kernel void test(__global word_t *data,  __global res_t *result)
{
   size_t id=get_global_id(0);
   int size=0;
   size=data[id].len;
   __local char word[MAX_WORD_LEN * WORK_GROUP_SIZE];
   //working with the word
   __local char* pThreadWord = &word[ MAX_WORD_LEN * id];
}

I've put the array in local memory as if you do char word[MAX_WORD_LENGTH] you will almost certainly use up all your registers and spill (i.e. super slow).
If you do have to cope with very long variable length words then you will have to dynamically "allocate" memory in your local memory for each thread with an atomic
__kernel void test(__global word_t *data,  __global res_t *result)
{
   size_t id=get_global_id(0);
   int size=0;
   int size=data[id].len;
   // local memory "allocator"
   __local int offset = 0;
   volatile __local int* pOffset = &offset;
   __local char wordBuffer[BUFFER_SIZE];
   // "allocate" memory
   int myOffset = atomic_add( pOffset, size );
   //working with the word
   __local char* pThreadWord = &wordBuffer[ myOffset ];
}

Comment: Thank you for this possible solution. As soon as possible I will try them. Thank you so much, really!

Using "String" in openCl Kernel


Cakephp querying Model by strict associated data

Question: I have a model X which is associated with Model Y.
X hasMany Y.
Y has an attribute "status".
I want to find all X such that the status of ALL Ys associated to X is equal to "active", i.e all Y.status =="active".
Here's a simplified schema:
X
id....name
0.....test
1.....two
Y
id....status....x_id
0.....active.....0
1.....inactive..0
2.....active....1
3.....active....1
I Want my query to return x with the ID 1, since both its associated Y records are active. I don't want it to return x with ID 0 since both its Y records aren't active.
I have tried using join queries, but they keep returning the unexpected result by returning both X.
I'm using Cakephp 2.2.
Answer: <code>$data = TableRegistry::get('Y')->find()->where(['x_id' => 1);

//with assosiation
$data = TableRegistry::get('Y')->find()->where(['x_id' => 1])->contain(['X']);
</code>
full documentation here http://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html
EDIT
to search by status you can add search parameter in where()
<code>$data = TableRegistry::get('Y')
                ->find()
                ->where(['x_id' => 1, 'status' => 'active'])
                ->contain(['X']);
</code>
Using CakePHP 2.x
<code>$data = $this->Y->find('all',
        array(
            'conditions'=>array('x_id'=>1,'status'=>'active'),
            'contain' => array('X')
        ));
</code>
Comment: I'm using cakephp 2.2. Is there a way in it?

Also, I want to query by "status" of Y.
Comment: Do you know of doing this in CakePhp 2.0 ?
The query should not include the ID. It should be returned in a manner that if X has all Ys with status "active", it should return. In the example, only x with id=1 had all Ys with "active" status.
I shouldn't need to explicitly tell that I need x.id = 1.
Comment: But this doesn't solve it.
Can you please look into the problem again?
I want all Xs such that the status of ALL Ys associated with it is "active"
Comment: you can add contain parameter
Comment: That doesn't work. I want ONLY those Xs with which all Ys have an active status.
I think a NOT IN (where Y has other than active status) query would do.
Comment: then remove 'x_id' => 1
Comment: That doesn't work in helping achieve the exact result. It brings back all Xs where even one Y is active.


Configure options MySQL server was compiled with?

Question: I have MySQL server 5.0.67 running on a Linux machine.
How can I know what configure options were used to compile it??
I'm interested in the option --with-mysqld-ldflags in order to know whether mysql was linked statically or dynamically.
Answer: You can see the configure options using the mysqlbug command-line utility.
In your shell type mysqlbug and you'll see a template e-mail for bug submission.
At the bottom end of that e-mail you can see the configure line with all the options your copy of MySQL was compiled with.
The --with-mysqld-ldflags is omitted by default and it means the server will be compiled dynamically.
http://dev.mysql.com/doc/refman/5.0/en/configure-options.html
Answer: It won't get you exactly what you asked for, but you can check if a binary is statically linked or not (and if it is dynamically linked, what libraries it is linked against) with ldd.
When the binary is dynamically linked, the output looks similar to this:
$ ldd test-dyn
        linux-vdso.so.1 =>  (0x00007fffce7fe000)
        libc.so.6 => /lib64/libc.so.6 (0x000000391f000000)
        /lib64/ld-linux-x86-64.so.2 (0x000000391ec00000)

... and on a statically linked binary, like this:
$ ldd test-stat
        not a dynamic executable

Answer: Which version of Linux?  The details will be in the source package.
For Debian/Ubuntu based you can get the source package with apt-get source packagename.  Then look at the debian/rules script that runs the build.
Answer: When I run ldd I get this:

root@hostname3 [~]# ldd /usr/sbin/mysqld
        linux-gate.so.1 =>  (0x00139000)
        librt.so.1 => /lib/librt.so.1 (0x00ba2000)
        libdl.so.2 => /lib/libdl.so.2 (0x00ae3000)
        libpthread.so.0 => /lib/libpthread.so.0 (0x00b12000)
        libcrypt.so.1 => /lib/libcrypt.so.1 (0x00bad000)
        libnsl.so.1 => /lib/libnsl.so.1 (0x00be1000)
        libm.so.6 => /lib/libm.so.6 (0x00ae9000)
        libc.so.6 => /lib/libc.so.6 (0x0099d000)
        /lib/ld-linux.so.2 (0x0097f000)

Does it mean mysqld is statically linked??
Comment: Nope, this means it's dynamically linked against the libraries listed there.
Comment: Oh, great. That's what I need because I have to add some UDFs to the server.
In the case a server is statically linked, how would the output of ldd look like?? (I need to check this on other machines too)
Comment: I've edited my original post with details about that.


SQL: how to filter by columns that are in different tables?

Question: Let's assume we have some table A which we want to query and that is related to another table, B, through a one to many relationship, so, A can have several B objects, and each B object can have only one A object. The problem is that when querying A, I need to filter by a column on table B. What is the best approach to do that?
If I use JOIN, then I end up with repeated A rows in the result. It is logical as an A object can have many B objects. In MySQL I can avoid duplicates by using GROUP BY but that is not possible on other database systems, they force you to use aggregated functions.
If I use subqueries, then I don't think that the performance is good because the most nested subquery could return a very high number of rows:
SELECT * FROM A WHERE ID IN (SELECT A_ID FROM B WHERE B.some_column = 'my-filter');

That subquery looks bad, if B had a huge number of rows it could be painful in terms of time/performance.
*A_ID is a foreign key on this example which points to the ID field in the table A.
So, what's the good way for doing this?
Comment: Depends on the dbms used. Some products optimize sub-queries better than others.
Comment: I don't understand what you mean by repeat. If you want to return all students in a class with a last name starting with 'S', you don't want the class name to repeat?
Comment: `GROUP BY` is not intended for duplicate elimination, use SELECT DISTINCT instead. Newer MySQL versions don't allow invalid group by's (unless in compatibility mode.)
Comment: Referring to the class and students example, what I would want is to get all classes which have at least 1 student with a last name starting with 'S'. If a class has 2 students meeting that filter, then it appears 2 times. That's what I mean with the repeated rows. I want to avoid that.
Answer: Use a join and a distinct
selct distinct A.*
from A
inner join B
    on B.ID = A.ID
where B.ColumnB = 'Filter'

Answer: There is no problem with GROUP BY on other database systems! They are just forcing you to write the entire columns in the GROUP BY clause or with aggregate functions as it should be as opposed to MySQL that allows this stupid thing  . So:
SELECT a.Col1,a.Col2,a.Col3...
FROM A
JOIN B
 ON(a.id = b.id)
WHERE B.some_column = 'my-filter'
GROUP BY a.Col1,a.Col2,a.Col3...

Comment: This makes sense. The only problem I could have is that I am modifying a layer of a Java application which manages accesses to database and it would be difficult to guess all the column names of the table which I am querying at each moment. Although I think it could be possible by reflection, as column names are methods on entity classes that are converted into tables by the ORM tool.


not all arguments converted during string formatting error with modulus

Question: i was making a clock in python and tested it, it wasent working. In the shell, it says ''not all arguments converted during string formatting'' i dont really know what to do to repare this cause i just know that a string is a series of numbers i think. Any ways, i was trying to make the turtle orientate to the good spot for the hours hour pointer. So, i think its with the modulus. Here is the code for now (dont look at the unfinished part, its not finished)
import turtle
import datetime
from datetime import datetime
from turtle import *

def DRAW ():
    turtle.clear()
    DRAW2()
    DRAW4()
    turtle.pensize(4)
    DRAW1()
    DRAW5()
    DRAW3()
    DRAW7()

def DRAW1 ():
    turtle.penup()
    turtle.setx(0)
    turtle.sety(-50)
    turtle.pendown()
    now = datetime.now()
    current_minute = now.strftime('%M')
    current_sec = now.strftime('%S')
    current_hour = now.strftime('%H')
    print((((current_hour % 12) * 30) + (current_minute / 2)))    <---

def DRAW2 ():
    hello = 2

def DRAW3 ():
    hello = 8

def DRAW4 ():
    hello = 3

def DRAW5 ():
    hello = 89

def DRAW7 ():
    je = 3

DRAW()

Comment: `current_hour` and `current_minute` are strings, not numbers, you can't perform arithmetic on them.
Answer: current_hour is a string, not an integer, because strftime() is for formatting dates and times as strings. So % is the string formatting operator, not modulus.
There's no need to use strftime. The datetime object has attributes with the components. So use
current_hour = now.hour
current_minute = now.minute
current_sec = now.second


I can not run any query on BigQuery in region europe-west2 anymore (transient error n°4233314)

Question: I can no longer query nor preview any table nor run any job in my BigQuery (region europe-west2). When I run a query in an other region, I don't get the error so it's specific to my region.
When trying to run any query, I get the following error in the GCP Console:

An internal error occurred and the request could not be completed.
This is usually caused by a transient issue. Retrying the job with
back-off as described in the BigQuery SLA should solve the problem:
https://cloud.google.com/bigquery/sla. If the error continues to occur
please contact support at https://cloud.google.com/support. Error:
4233314
Answer: I confirm that the europe-west2 Google Cloud services like App Engine or Firestore are down...


Show $2x - 1 - \sin (x)$ has exactly one real root.

Question: I have the following solution to the above problem:
Let $f(x)=2x-1-\sin(x)$
Observe, $2x-1, \sin(x)$ are continuous functions, hence by arithmetic of continuous functions $f(x)$ is continuous $\forall x$.
$f'(x)=2-\cos(x)$, hence $f'(x)>0$, $\forall x$ and hence $f(x)$ is increasing $\forall x$.
Observe $f(0)=-1<0$ and $f(\pi)=2\pi-1>0$ hence since $f(x)$ is continuous and increasing $\forall x$ there is exactly one real root.
I'm wondering if my solution would be considered acceptable and if there is an alternative way to go about solving this problem. Thanks!
Comment: Your proof looks good. One thing to note, is that you can make $cos(x)$ into $\cos(x)$ by adding \ before the cos in LaTex. Also, depending on how in depth you want to get, you could always put in $f(2)=3-\sin(2)\geq 2>0$ so that you don't have to compare $2\pi$ and $1$. Of course, this is a minor quibble and your overall proof is excellent.
Comment: Thanks for the help!
Answer:
Υοur solution is perfect.

As a slightly different proof, you can prove that $f$ has at least one root, and if you assume that has more than one roots, then by Rolle's s theorem, would exist $y\in \Bbb{R}$ such that $f'(y)=0$
Thus $\cos{y}=2$ which is a contradiction.
Comment: Thanks for your help!
Answer: Your solution is not perfect. A function is not an expression. You can say that $2x-1,\sin(x)$ are continuous in $x∈\mathbb{R}$, but they are not functions. And $f(x)$ is not a function either. You should also have defined the domain of $f$. You can either say that $f$ is continuous on its entire domain (presumably $\mathbb{R}$), in which case you can just say "$f$ is continuous", or you can say that $f$ is continuous at every $x∈\mathbb{R}$. Do not use "$∀$" in the manner you are using it, because it is wrong. Either write the intended meaning in proper words, or use the proper syntax of first-order logic if you still want to use the symbolic form. These errors aside, your idea of using IVT is correct.


Triangle Inequality about complex numbers, special case

Question: At Spivak's calculus he treats the triangle inequality about complex numbers dividing into cases. Let $z$ and $w$ complex numbers, the inequality is clear if $z$ or $w$ are $0$.
$\lvert z+w \rvert$$\leq \lvert z \rvert + \lvert w \rvert$
Suppose that $z=\lambda w$, then it is straightforward to prove the inequality but divide in cases :
$\lambda<0$  and $\lambda>0$.
I can't see how is this straightforward and why do we need to divide into cases for $\lambda$.
After I do the algebraic manipulations it seems that it doesn't matter how $\lambda$ is.
My guess is that my approach is wrong, so if someone can give me a hint on how to initiate the proof would be a great help. Thank you
Comment: Please state  completely what the inequality is that you are talking about. And what exactly the cases are discusing. As it is, no one can understand .
Comment: what about now?
Answer: A general approach : For real $a_1,a_2,b_1,b_2$: We have $$ \bullet \quad (a_1^2+b_1^2)(a_2^2+b_2^2)=(a_1b_2-a_2 b_1)^2+(a_1 a_2+b_1 b_2)^2\geq (a_1 a_2+b_1 b_2)^2.$$
For $z=a_1+i b_1$ and $w=a_2+i b_2$ we have $$|z+w|\leq |z|+|w|\iff |z+w|^2\leq (|z|+|w|)^2\iff $$  $$\iff  (a_1+a_2)^2+(b_1+b_2)^2\leq a_1^2+b_1^2+a_2^2+b_2^2 +2\sqrt {(a_1^2+b_1^2)(a_2^2+b_2^2)} \iff$$  $$ \iff 2 (a_1a_2+b_1b_2)\leq 2\sqrt {(a_1^2+b_1^2)(a_2^2+b^2)}.$$From $\bullet$ we have $$\sqrt {(a_1^2+b_1^2)(a_2^2+b_2^2)}\geq \sqrt {(a_1 a_2+b_1 b_2)^2}=|a_1a_2+b_1b_2|\geq a_1a_2+b_1b_2.$$
Remarks: The significance of the values $a_1b_2-a_2b_1$ and $a_1a_2+b_1b_2$ can be seen if we put $z$ and $w$ in polar form :$z=r_1(\cos t_1+i\sin t_1),\;w=r_2(\cos t_2+i\sin t_2)$ with real $t_1,t_2$ and non-negative real $r_1,r_2$. Then $a_1 b_2-a_2 b_1= r_1 r_2 \sin (t_2-t_1)$ and $a_1 a_2+b_1 b_2=r_1 r_2\cos (t_2-t_1).$ So  if $z\ne 0\ne w$  then $|z+w|=|z|+|w| \iff (\sin (t_2-t_1)=0\land \cos (t_2-t_1)=1) \iff z/w\in R^+.$
Comment: If we put $z,w$ in polar form to begin, we get $|z+w|^2\leq (|z|+|w|)^2\iff  r_1 r_2 (\cos t_1 \cos t_2+\sin t_1 \sin t_2) \leq r_1 r_2$ .  Observe that the LHS is $r_1 r_2 \cos (t_2-t_1).$
Comment: The equation $\bullet$ in my answer expresses $|z|^2 |w|^2=|z w|^2$.
Comment: can you explain about the case when $z=\lambda w$  @user254665
Comment: When $z=lw$ and $ l$ is real, we have $a_1b_2-a_2b_1=0.$ We can directly calculate  that $|z+w|=|z|+|w|$ when $ l\geq 0$ and $|z+w|= |\;|z|-|w|\;|$  when $ l<0.$ Represent $ a+bi$ (with real $a.b$) as the point $(a,b)$ in the real plane $ R\times R .$ Then $|a+bi|$ is the distance from $(a,b)$ to $(0,0).$ When $z/w$ is real then $z,w,$ and the origin are co-linear.  In polar form $z=r (\cos t+i\sin t)$, where $ r=|z|,$ and for $z\ne 0,$  the angle $t$ is  between the $x$-axis  (which represents the reals) and the segment joining $z$ to the origin $(0,0)$ (measured  from the $x$-axis ).
Answer: Let $z=(a_1,b_1), w=(a_2,b_2)$, suppose $z=lw$, then $z=(la_1,la_2)$
I want to prove $\lvert z+w \rvert \leq\lvert z\rvert+\lvert w\rvert$
calculate $\lvert z+w \rvert$ = $\bullet$:
$\bullet$=$\lvert (la_2,lb_2)+(a_2,b_2) \rvert$=$\lvert (la_2+a_2,lb_2+b_2)\rvert$= $\sqrt{(1+l)^2a^2+(1+l)^2b^2)}$=$\lvert 1+l \rvert$ $\sqrt{a^2+b^2}$
calculate $\lvert z \rvert+\lvert w \rvert$= $\star$ :
$\star$ =$\lvert (la_2,lb_2)\rvert$ + $\lvert (a_2,b_2) \rvert$= $\sqrt{l^2a^2+l^2b^2}$+$\sqrt{a^2+b^2}$=$\rvert l \lvert$ + 1 $\sqrt{a^2+b^2}$
if l>$0$ then $\lvert 1+l \rvert$=$\rvert l \lvert$ + 1 then $\lvert z+w \rvert =\lvert z\rvert+\lvert w\rvert$
if l


Can't trigger system debugger to dump core when Cygwin's Perl launches program with backticks

Question: I have scripts that launch arbitrary processes using backticks.  Occasionally, a crash will occur (zero divide, for example) and need to get a core dump for analysis when that happens.
I have registered a perl script as crash handler with the operating system (this in Windows 7 – I knew you wanted to know) which gets called with the PID of the crash; the handler attaches Microsoft's 'cdb' debugger which creates the needed dump.  My test 'crasher' program is a C++ executable that does a divide-by-zero (Crasher.exe).
The problem:  When I use Cygwin's Perl implementation, the program crash never triggers the crash handler.  My suspicion is that Perl is catching the problem and silently dropping it.  All works fine with a Perl from ActiveState.
The Question:  How can I get Cygwin's Perl to get out of the way and let the error propagate all the way back to the system.
Here's an example that uses ActiveState perl that triggers the crash handler and produces a core dump
<code>  C:>     \tools\Perl\bin\perl.exe  -e "`Crasher.exe`;"
</code>
But using Cygwin does not
<code>  C:>     \cygwin\bin\perl.exe  -e "`Crasher.exe`;"
</code>
Also, if I start Crasher.exe directly in Cygwin's shell, the crash handler is not called; neither is it called if started via backticks in either Cygwin or ActiveState Perl.
Answer: Let me cite Hans Passant:

The basic problem is that SAP calls SetUnhandledExceptionFilter(). And does its own thing, all large programs do this. There is no boss override switch built into the operating system to stop it from doing this.

So no, you can't do it for Cygwin either. You can run it under the debugger and catch the first chance exceptions. Depending on how many exceptions are thrown, you might be able to find the interesting one.


Ler JSON com Delphi 6

Question: Tenho um arquivo JSON, porém gostaria lê-lo usando Delphi 6. Seria possível?
Segue um exemplo do JSON
<code>{
   "size":1,
   "response":[
      {
         "id_cliente":21,
         "nome":"DESENTUPIDORA ME",
         "endereco":"RUA J, Nº. 9",
         "complemento":"TÉRREO ",
         "bairro":"SANTOS",
         "cidade":"VITÓRIA",
         "estado":"ES",
         "cep":"29.000-000",
         "telefone":"28-18987677",
         "telefone_fax":"28-9878-08685",
         "email":"firstname.lastname@example.com",
         "cnpj":"098873.835/0033-87",
         "pesagem_livre":0,
         "nome_fantasia":"DESENTUPIDORA SJOE -ME",
         "tipo_cliente":"privado",
         "inscricao_estadual":"",
         "situacao":true,
         "inscricao_municipal":"",
         "periodo_medicao":"9931",
         "anotacoes":"",
         "data_inclusao":null
      }
   ]
}
</code>
Comment: Daniel, não consigo formular uma resposta por falta de tempo, mas pesquisa sobre SuperObject para Delphi6, é uma biblioteca que você conseguira fazer o que quer ;)
Answer: Pode utilizar o json4delphi, que possui as rotinas para Delphi 6 ou superior. No link do GitHub possui um exemplo de uso, mas vou replicá-lo aqui:
<code>var
  Json: TJson;
  Str: String
begin
  Json := TJson.Create();

  //put
  Json.Put('field1', null);
  Json.Put('field2', True);
  Json.Put('field3', 3.14);
  Json.Put('field4', 'hello world');

  //another way
  Json['field5'].AsBoolean := False;
  Json['field6'].AsString := 'hello world';

  //object
  with Json['field7'].AsObject do
  begin
    Put('subfield1', 2.7182818284);
    Put('subfield2', 'json4delphi');
  end;

  //array
  with Json['field8'].AsArray do
  begin
    Put(6.6260755e-34);
    Put('The magic words are squeamish ossifrage');
  end;

  //get
  Str := Json['field4'].AsString;

  //parse
  Json.Parse('{"a":1}');

  //stringify
  Str := Json.Stringify;
end;
</code>
Comment: Muito obrigado pela atenção vou tentar usar.

Ler JSON com Delphi 6


PyGObject, Looping buttons

Question: I'm tying to create a loop of buttons, and execute a command when they are pressed.
k=0
for row in list:

        delete_list.append("button_delete"+str(k))
        delete_list[k] = Gtk.Button(label="Delete")
        grid.attach(delete_list[k], columns+1, k, 1, 1)
        delete_list[k].connect("clicked",globals()["on_button"+str(k)+"_clicked"])

        k+=1

The buttons are displayed correctly, but i'm having problems to connect the "clicked" signal.
delete_list[k].connect("clicked",globals()["on_button"+str(k)+"_clicked"])
KeyError: 'on_button0_clicked'

I first tought that the error was because there is no method on_button0_clicked, but i create it and i stil getting the same error.
Also, if there is some good way/advice to dynamically create the methods for the response of the buttons it would be great. I actually need to create a method for each button that uses the "k" counter.
Comment: "I first tought that the error was because there is no method on_button0_clicked, but i create it and i stil getting the same error." - is the method on some class instead of the global scope?
Comment: Yeah, the method was in the same class, and putting it at the global scope fixes the error :)
Answer: To dynamically create a function which binds loop variables as locals, you need a factory function to generate them:
def callback_factory(num):
    def new_callback(widget):
        print(widget, num)
    return new_callback

for k, row in enumerate(somelist):
    button = Gtk.Button(label=str(k))
    button.connect('clicked', callback_factory(k))

This avoids a common pitfall which is to create a method or lambda within the loop body causing the same thing to be printed for each button click. This is due to the environment the function is created in being bound to the generated function in which the k variable is mutating and shared between all callbacks. The pitfall can be observed with the following code which does not work as you might expect:
for k, row in enumerate(somelist):
    def callback(widget):
        print(k)
    button = Gtk.Button(label=str(k))
    button.connect('clicked', callback)

PyGObject also supports unique user data per-connect call which is passed into the callback:
def callback(widget, num):
    print(widget, num)

for k, row in enumerate(somelist):
    button = Gtk.Button(label=str(k))
    button.connect('clicked', callback, k))

This allows using the same callback with a varying argument which can be cleaner in some cases.
Side note: It is probably not a good idea to mask the builtin "list" class by assigning it to your own list instance.
Comment: To be honest, i'm kinda lost with some of your comments, i need still reading about python and PyGobject. (i just started learning programming). The first solution works great, that's what i'm using. The second one it's always printing 67, and the last one is kinda strange to me, because   button.connect('clicked', k)) never calls the callback function. Anyways First solution works great, and i'll try to understand everthing you said, it seems pretty interesting
Comment: No worries, the middle example was supposed to demonstrate a problem case which you might expect to work but does not. The last example was missing the callback argument which I fixed.

PyGObject, Looping buttons


For $t\in(0,1/2),p_t(x)=(t-t^2)x^2-(1-t)x+t^2$ has the roots $\alpha_t,\beta_t$

Question: For $t\in(0,1/2),p_t(x)=(t-t^2)x^2-(1-t)x+t^2$ has the roots $\alpha_t,\beta_t$ then Could anyone tell me which of the following is true?
$A)\alpha_t,\beta_t\in\mathbb{C}$
$B)$ For infinitely many values of $t$ the corresponding root $\alpha_t$ is rational and $\beta_t$ is irrational.
$C)$ $\alpha_t,\beta_t$ are real and positive ,and one of them is $>1$ and another is $<1$
$D)\lim_{t\uparrow {1\over 2}}\Rightarrow|a_t-\beta_t|\to 0$
here is my thought
let for some $t\in(0,1/2),\alpha_t,\beta_t$ be real roots
then by Roles Theorem $p'_t(x)=0$ for some $c\in (\alpha_t,\beta_t)$
but  $p'_t(x)\ne 0$ so $A$ is true
Answer: Since $t \not \in \{0,1\}$ we may divide $p_t(x)$ by $t-t^2$.  At a root, $x$, this gives \begin{align*}0 &= \frac{p_t(x)}{t-t^2} \\ &= x^2 - \frac{1}{t}x + \frac{t}{1-t} \\
&= x^2 - \left(\alpha_t + \beta_t\right)x + \alpha_t \beta_t \\
&= \left(x-\alpha_t\right)\left(x-\beta_t\right) \end{align*}  Then we read off the matching coefficients: $\alpha_t + \beta_t = \frac{1}{t}$ and $\alpha_t \beta_t = \frac{t}{1-t}$.
The first is true, but over general.  You should have no trouble showing the discriminant of the polynomial is positive for $t \in (0,1)$.  The roots are actually in $\mathbb{R}$.
If $t$ is rational, then $\alpha_t$ and  $\beta_t$ are either both rational or both irrational (otherwise their product and sum can't simultaneously be rational).  If $\alpha_t$ is rational and $\beta_t$ is irrational, the linear coefficient gives that $t$ is irrational, but the converse isn't automatic, so good luck.  (Try eliminating $\alpha_t$ between the two coefficient equations.  If you're lucky, you'll get something that simplifies enough that $\beta_t$ irrational forces $t$ irrational, but I'm not convinced this works.)
You should have no trouble showing $\frac{t}{t-1} \in (0,1)$ for $t \in (0,1/2)$ so the roots have the same sign.  If their product is small, in $(0,1)$, but their sum is big ($\frac{1}{t} \in (2,\infty)$) one is big and one is very small.
In the form above, the limit as $t\rightarrow 1/2$ is trivial to find.  It's $x^2-2x+1$ which is easy to factor.
Comment: roots are actually in $\mathbb{R}$?


Question about number of features in a paper

Question: In this paper it states that there are 36,787 features, although in Table 3 it states there are clearly 32.
Also how are the words encoded? Is this a one hot encoding they are working with here?
Answer: For details, you should probably e-mail the authors, but notice that Table 3 just mentions the classes of the features. For example, Position in sentence has three categories, so after one-hot encoding, this makes three features, Polarity has over three categories, so few more features, Word are probably one-hot encoded unique words, so there could be thousands of them, same with Lemma. Easily this may go into thousands.
Comment: OK thats make sense. Didn't now that each of the one-hot encoding bits counts as a feature. Thank you! Actually I am just aware of Word2Vec models for encoding words. Is there a lexicon for one hot encodings of words that I am not aware of? Since back then there was no Word2Vec.
Comment: A vector that I get from the Word2Vec model is a single feature? Or is every bit a single feature actually?
Comment: @craaaft I don't understand your questions. If you want to use a particular implementation of a model (like Word2Vec) just look at the documentation of the format of the inputs. As about the definition of features, in general, "feature" is any column (in tabular data) of numbers, for example, if you one-hot encode words, it creates binary features to encode the words.


Which source of sensor readings are most prefered? IPMI, ACPI, or from sensor chip itself?

Question: When monitoring systems for their temperature, and fan speeds, what source of sensor readings is most preferred?
I can get all the motherboard readings from both,
IPMI and directly from the Winbond sensor driver itself. I can get CPU readings from ACPI, or from the CPU temp driver itself.   I also can get GPU readings from ACPI, and the GPU driver itself.
Answer: In re-reading your question I realize I made an assumption that is incorrect.
All of the things you list access the same hardware in different ways. You use the one that is best supported by whatever monitoring systems you have. On occasion something like a firmware update will affect how the device reports that  information, but it will affect how each technology interprets the data. You should sanity check the output to validate your method.
I initially answered how you would transfer that information to a monitoring solution. There, once again, you use the method that works with your monitoring solution.
I would say that the single most common, which includes devices without a BMC at all is SNMP. SNMP OID strings however are usually not active reporters, the device has to be actively queried to update status.
If you wanted a report with more active problem reporting, then many newer (~2015) management interfaces support sending problem alerts to a Syslog aggregation server. That can parse the inbound messages and generate alerts.
Another information access control is the i2c bus, but that needs software running as a client on each individual device to query it.
Comment: In the context of SNMP, my question would be how to implement it.
Comment: That question exceeds the scope of your original question by a large margin. The SNMP protocol. Your to be monitored device has an agent, and you would contact it with a manager. There are tools, both free and paid which operate as  managers and make queries of the agents. perhaps you should start with the Wikipedia for  (https://en.wikipedia.org/wiki/Simple_Network_Management_Protocol)
Comment: I have readings available in ACPI, and available directly from the motherboard sensor chip driver, as well as via IPMI.


Isomorphism $\phi:S_n\rightarrow S_A$.

Question: I'm working through a problem right now where, for $H,K\subset S_5$, $H$ is the group of permutations which fix $1$, and $K$ is the group of permutations which fix $2$. The problem says to show that $H\approx K$. From what I've seen, this involves showing that $H\approx S_4\approx K$, based on the fact that $H$ is the group of permutations of $\{2,3,4,5\}$ and $K$ is the group of permutations of $\{1,3,4,5\}$.
I have a general idea of an isomorphism I could use, but I think I'm just having trouble with the notation. Let's say we have a set $A=\{a_1,a_2,a_3,a_4\}$, and I want to define a function $\phi: S_4\rightarrow S_A$ (I hope I'm using correct notation for the symmetric group on $A$, but please correct me if not). The idea is that, for any $\alpha\in S_4$ and $\beta\in S_A$, $\phi(\alpha)=\beta$ if and only if $\alpha(x)=n$ and $\beta(a_x)=a_n$ for all $1\leq x,n\leq4$; for example, if $\alpha(1)=3$, then $\beta(a_1)=a_3$. If I can show $\phi$ is an isomorphism, it naturally follows that $H$ and $K$ are isomorphic to $S_4$.
I have two questions about this problem:

Is there a simpler or more formal notation for this function, or would the way I've presented it be suitable enough?

Is this even needed, considering both $S_4$ and $S_A$ are the groups of permutations on 4-element sets?

Any help is appreciated. Thanks!
Answer: Let $X$ and $Y$ be sets and $f\colon X\to Y$ a bijection. Then the map $\varphi\colon S_X \to S_Y$, defined by $\sigma\mapsto(y\mapsto (f\sigma f^{-1})(y))$, is an isomorphism. In particular, the symmetric groups of any two finite sets with the same number of elements are isomorphic, whence $S_A\cong S_n$ for every set $A$ of $n$ elements.
Answer: These subgroups are conjugate. Take the permutation $(12)$ then one of your subgroups conjugated by that permutation is the other subgroup.

Isomorphism $\phi:S_n\rightarrow S_A$.


Invoke the editor in the interactive mode

Question: When open an editor within Ipython, I usually issue commands
In [13]: subprocess.run('vim Person.py', shell=True)
Out[13]: CompletedProcess(args='vim Person.py', returncode=0)

How to do it in a straight-forwards method?
Answer: The %edit magic command is the canonical way offered by IPython. It invokes an editor specified by $EDITOR, optionally loading a specified file, and executes the code after it's closed.
Another common workflow is to have editor and console open in different windows and copy-paste between the two (the %paste magic is handy here).
Jupyter Notebook seems to offer experience similar to MATLAB console though I don't have any experience with it.


Possible to have Win32 application block until it exits?

Question: When I open a command line in Windows (cmd) and start a program, for example calc, the prompt immediately returns and the program is started (the calculator window is displayed).
This is contrary to how I know it from the Linux world: when I start a (possibly with GUI) application, the prompt does not return until I exit the started program.

Using the w32 api, is it possible to program it so that my app displays a window, but the prompt is only returned after the user closes the window?
Comment: Just saying you can use `start /wait` to wait for any application.
Comment: Start by looking at [`CreateProcess`](http://msdn.microsoft.com/en-us/library/windows/desktop/ms682425(v=vs.85).aspx) and [`WaitForSingleObject`](http://msdn.microsoft.com/en-us/library/windows/desktop/ms687032(v=vs.85).aspx).
Comment: Do you have a very good reason to do this? Linux and Windows are different. You shouldn't artificially force an application to behave in a way that is not usual for the system it runs on, unless there is a clear need for your application. Your users will be expecting the standard behaviour.
Comment: You need to mark it as a console application in the manifest.
Comment: Marking it as a console application is probably not what I want, because that would always open a console, even if the program is started from say the task bar, right?
Comment: Thanks for the tip, I didn't know about `start /wait`!
Comment: @JBentley I do find the Windows way strange (for example, if two programs are started from the same console window, their outputs will probably get mangled together), but you're right in that the app should behave as expected. If it is possible, I will not make it the default.
Comment: Related to [Is it possible to attach a non-console Win32 application to the invoking cmd shell?](http://stackoverflow.com/questions/13621542/is-it-possible-to-attach-a-non-console-win32-application-to-the-invoking-cmd-she?rq=1), although my question is not answered there, either.
Comment: A native Windows app creates its own window.  There is therefore no point at all in disabling the command interpreter, it is available to run another command.
Comment: @HansPassant: Well, in the *nix world you normally expect to have stdio available for all programs. For example a interactive plotter may expect its data to plot on stdin.
Comment: @datenwolf: if you need the standard I/O handles, there's no reason not to make it a console application.  (Console applications can still have GUIs.)  If you *don't* need the standard I/O handles, there's no reason for the parent console to wait.
Comment: The short answer is no, you can't make an application that the command shell will automatically wait for which doesn't also create a console window if launched via the GUI.  (Though you can hide the console window immediately if you don't need it, the user will still see it appear and disappear.)  Yes, there are times when this is inconvenient, but it isn't really ever a major problem; the conventional solution is to have two different executables, one for GUI use and one for command-line use.
Comment: @HarryJohnston: I know all of this, I'm not the OP. The problem is, that some programs may want to use stdio on demand but always have a GUI. It's a pretty common thing in *nix environments. If you start programs through some GUI menu no console window will pop up (even if the process writes something to stdio). But start the program from a terminal you can see the output. In Windows, as soon as your program needs stdio either a console window must be opened, or you spend a lot of time hacking the Console API to figure out if there's a console for your program and connect stdio in that case.
Comment: @datenwolf: yes, the "stdio on demand" scenario is one of the cases I alluded to in my comment to the OP, where the Windows approach is (mildly) inconvenient for the programmer.  Personally I still prefer that to the inconvenience of having to remember to background everything explicitly when I'm the user ... and of course *professional* GUI applications are expected to have proper log windows (or whatever) rather than using a console window, and for quick-and-dirty programming console mode is fine, so really this mostly only affects *nix ports, which tend to have bigger problems anyway. :-)
Comment: @datenwolf: note that the "separate GUI and console executable" approach also solves the "stdio on demand" scenario.
Comment: @HarryJohnston: personally I find those "proper log windows" infuriating; if they're optional and I can see errors on stderr, okay. But having only those? No, thank you! Because with this usually the output cannot be redirected conveniently into filter or search programs. The programs I write usually allow for vast amounts of diagnostics, and for that each line is prepended by some distinctive key, which allows to easily filter it. The powers of redirection and programs as `tee` allow to filter and display that in realtime with whatever program I see to fit best.
Comment: @datenwolf: interesting point.  Most Windows programs are written under the assumption that the user will not want to do that sort of troubleshooting themselves; I'm not saying that's necessarily a good thing, mind you, but it is the dominant paradigm.  FWIW, programs that do anticipate advanced troubleshooting from the end users do still have a number of options; a plugin model, for example, or named pipes - the simplest approach again being to have a separate executable for use in console mode.  (Or a shim that launches the GUI executable to do the real work.)
Comment: @HarryJohnston + datenwolf: Thanks a lot for these comments, those are the same problems I have struggled with (what if I sometimes want stderr, etc.). Could one of you (I'd suggest HarryJohnston, as he was first) write this into an answer (It can't be done, use two executables) so I can accept it?
Answer:
Using the w32 api, is it possible to program it so that my app displays a window, but the prompt is only returned after the user closes the window?

I think there are a few questions here.
First, how do you create a process in Windows? To create a process Windows, you use CreateProcess.
Second, how does CreateProcess work? CreateProcess obviously creates a new process (like calc.exe), and it offers a lot of options to create the process. It also returns a BOOL to let you know if the call failed or succeeded.
In the case the call fails, you get a failure immediately. That's a "synchronous" failure, and you can continue moving along in your procedures.
In the case the call succeeds, your process is "detached" from the child. Its more like an "asynchronous" call to the function. You can synchronize with the child process, and you can learn that it has exited by waiting on the hProcess member of the PROCESS_INFORMATION structure.
Third, not everyone starts processes from the command line. It might be started by clicking it on the desktop. This is true in the Linux/X11 (et al) world too.
Fourth, from the Windows command line, I believe you can use CALL for other batch files. But I don't recall if it applies to programs, too.
Answer:
Possible to have Win32 application block until it exits?

Call CreateProcess to create the process. This will yield a handle to the process in the PROCESSINFORMATION struct that is returned. Pass that process handle to WaitForSingleObject to wait until the process is signaled.

Based on the comments it seems that what you really want is an executable that will behave like a console app when its parent process is a console app. And behave like a GUI app otherwise. It's not possible to do both from a single executable. The target subsystem is determined by metadata in the executable file.
The standard way to handle this is to have two executables, each targeting the different subsystems. One a console app, the other a GUI app. The common examples of this are java.exe and javaw.exe, python.exe and pythonw.exe.
Comment: +1.  Note that if you object to having two fully-fledged copies of what is essentially the same executable (such an objection may even be sensible in a few rare edge cases!) the console version can be a small application that launches the GUI version and waits for it to exit, as per David's original answer.  You can pass a command line argument to tell the GUI app to hook up to the parent console - that's a bit fiddly, but not horrifically so.
Comment: But if my app is a console application, it will always display a console (even when started from the desktop), which I don't want. If it is a GUI application, starting it from within a console will detach it immediately, and if I then call `CreateProcess` in my application, I'm already detached. Or am I missing something here?
Comment: Ok, I think I understand what you are driving at now. See update. Windows is just different from *nix.
Comment: You can attach your Win32 application to console to provide stdout to the parent terminal application.


Convergence of a sequence of functions with different domains

Question: Consider the sequence $\{f_n\}_{n=1}^\infty$ of functions $f_n: (-\infty, n) \to \mathbb R$ given by
$$f_n(t) = \frac{1}{n-t}.$$
On an intuitive level it feels like this sequence should have a limit, and that that limit should be $f: \mathbb R \to \mathbb R$, $f(t) = 0$. But we cannot use the usual notions of convergence of sequences of functions, because the domain is different for each function. So what is a good notion of convergence here?
This sort of thing appears naturally in the context of differential equations (see for example Example 4.33 in the ODE book by Logemann and Ryan), so it seems like there should be a somewhat standard notion. But I have been unable to find one.
One idea I had was to consider the graphs $\psi_n = \{(t, f_n(t)) \in \mathbb R^2: t \in \mathrm{dom}(f_n)\}$ and use the Hausdorff distance, but even this is tricky when the prospective limit function has an unbounded domain (or if the functions $f_n$ have such domains). Maybe it can be saved by considering only $\psi_n \cap U$ for all closed subsets $U \in \mathbb R$, or something like that.
Comment: There is a similar question [here](https://math.stackexchange.com/questions/1063257/convergence-of-functions-with-different-domain), but the answer given seems a bit too niche, and is not very useful for me.
Comment: How about you transform all your functions from $f_n : (-\infty, n) \to \mathbb{R}$ to $f'_n : \mathbb{R} \to \overline{\mathbb{R}}$ where $f'_n(t) = \begin{cases}\frac{1}{n-t} & t < n \\ \infty & t \geq n\end{cases}$. Then all your functions will have the same domain (However, are not continuous but lower semicontinuous). This is how convex functions with a restricted domain are sometimes handled. Then prove what you need for the $f'$ function and then make a conclusion about the original $f$.
Answer: The weak-L1 space $L^{1, \infty}(\mathbb R)$ has been introduced precisely to deal with the power-like function $g(t)=1/\lvert t \rvert$. Since it is translation-invariant, it contains the functions
$$
f_n(t)=\begin{cases} \frac{1}{n-t}, & t<n, \\ 0&, t\ge n.\end{cases}$$
In $L^{1, \infty}(\mathbb R)$, the sequence $f_n$ is bounded and it has no limit.
Some details. The space $L^{1, \infty}(\mathbb R)$ consists of those measurable functions $f$ such that
$$
\lVert f \rVert_{1, \infty}:=\sup_{\lambda >0} \lambda\lvert\{ t: \lvert f(t)\rvert >\lambda\}\rvert <\infty.$$
(Here $\lvert \{\ldots\}\rvert$ denotes the Lebesgue measure of a set. Also, $\lVert \cdot \rVert_{1, \infty}$ is not a norm but a quasi-norm, which is a minor technical point here). Letting
$$
f_+(t)=\begin{cases} -\frac{1}{t}, & t<0, \\ 0,& t\ge 0,\end{cases}$$
it holds that
$$\tag{1}
\lVert f_n\rVert_{1, \infty}=\lVert f_+\rVert_{1, \infty}=1, $$
so $f_n$ is bounded. To see that $f_n$ has no limit, we refer to this Terry Tao blog on modes of convergence. First we note that convergence in $L^{1, \infty}(\mathbb R)$ implies convergence in measure, as it is immediate. Now, by Exercise 17 in the link, convergence in measure implies pointwise convergence at almost all points of a subsequence. Since $f_n(t)\to 0$ for all $t\in\mathbb R$, the candidate limit can only be the null function. But (1) shows that $f_n$ cannot converge to the null function, hence it cannot have a limit.

Remark. The space $L^{1, \infty}$ is a special case of a Lorentz space, which justifies the notation.


Does the send order of a track affect the effects on the track

Question: I tried to change the send order on a track in reaper; to put the reverb send before the delay but found out its not possible to switch the initial order. Does the order of sends on a track affects it or does the track treats each send separately?
Comment: This question is definitely about *sends* and not *inserts*, correct?
Comment: Yes. that's correct
Answer: TL;DR: sends are treated in parallel, so there is no concept of order as opposed to FX chains (inserts) which treat the audio signal in series.

Unfortunately I don't have a schema ready to show you, but I'll explain with words as best as possible, hoping I understood your question properly.
I could describe a very generic model of audio processing, made of processing (or "filter" to use a signal processing term) nodes having audio inputs and audio outputs. For the sake of simplicity, I will get closer to the reality, especially in Reaper, using the same terms.
Consider a track as a black box having audio inputs and audio outputs. You can have as many inputs and outputs as you want, and they are numbered starting from 1. Each input or output is called a channel. For instance, when you create a classic send from one track to another, you will use the output channels 1 and 2 from the source track, and connect them respectively to the input channels 1 and 2 of the destination track.
What happens with a track's FX chain though remains internal to the track (the box). Input channels are redirected to the FX chain, the FX chain processes audio in series, and the chain redirects back the audio to the output channels of the track. Since processing is done in series the order is indeed important.
However, when using sends/receives between tracks, you actually connect output channels of a track to input channels of another. When you create multiple connections using the same output channels or input channels, processing is done in parallel. In other words, two sends from the same output channels of a track will send the exact same audio signal to the two destinations, creating two independent audio connections (it splits the audio). Since they are parallel, the order doesn't matter. For information, two receives into the same input channels of a track will mix the two input audio signals (it merges the audio).

This was a brief introduction to audio routing applied to Reaper, and I didn't cover subtleties such as cyclic routing (which I think is just forbidden), mixing algorithm (to merge audio into input channels), latency compensation (for routing through multiple tracks in parallel), etc. In the case of your question, I already explained far more than necessary.


sprintf is outputting some strange data

Question: I am working an embedded project which involves reading/writing a struct into EEPROM.  I am using sprintf to make it easy to display some debugging information.
There are two problems with this code for some reason.  The first; sprintf is printing a very strange output.  When I print 'addr++' it will follow a pattern '0, 1, 2, 3, 4, 32, ...' which doesn't make sense.
void ee_read(char * buf, unsigned int addr, unsigned int len) {
    unsigned int i;

    sprintf(bf1, "Starting EEPROM read of %u bytes.\r\n", len); // Debug output
    debugr(bf1);

    IdleI2C1();
    StartI2C1();
    WriteI2C1(EE_ADDR | EE_W);
    IdleI2C1();
    WriteI2C1((unsigned char)addr>>8); // Address to start reading data from
    IdleI2C1();
    WriteI2C1((unsigned char)addr&0xFF);
    IdleI2C1();
    RestartI2C1();
    WriteI2C1(EE_ADDR | EE_R);
    IdleI2C1();
    for (i=0; i<len; i++) {
        buf[i] = ReadI2C1(); // Read a byte from EEPROM

        sprintf(bf1, "Addr: %u Byte: %c\r\n", addr, buf[i]); // Display the read byte and the address
        debugr(bf1);

        addr++; // Increment address

        IdleI2C1();
        if (i == len-1) { // This makes sure the last byte gets 'nAcked'
            NotAckI2C1();
        } else {
            AckI2C1();
        }
    }
    StopI2C1();
}

The output from the above is here: https://gist.github.com/3803316  Please note that the about output was taken with %x for the address value (so addr is hex)
The second problem, which you may have noticed with the output, is that it doesn't stop when  i > len.  It continues further than the output I have supplied, and doesn't stop until the microcontroller's watch dog restarts.
Edit:
Calling the function
Location loc;
ee_read(&loc, 0, sizeof(Location));

Declarations:
struct location_struct {
    char lat[12]; // ddmm.mmmmmm
    char latd[2]; // n/s
    char lon[13]; // dddmm.mmmmmm
    char lond[2]; // e/w
    char utc[11]; // hhmmss.sss
    char fix[2]; // a/v
};

typedef struct location_struct Location;

char bf1[BUFFER_SIZE];

I don't think it's a race condition.  I disable the interrupts which use bf1.  Even then, it would corrupt the whole debug string if that happened, and it certainly wouldn't be so repeatable.
Edit
The value of addr starts as zero, which can be seen here: https://gist.github.com/3803411
Edit
What this is supposed to do it copy the location structure byte by byte into the EEPROM, and then recall it when it is needed.
Closure
So I never did solve this problem.  The project moved away from the EEPROM, and I have since changed OS, compiler and IDE.  It's unlikely I will replicate this problem.
Comment: provide variable declaration of bf1
Comment: Comment out lines until it stops behaving strangely. Then figure out which line causes it.
Comment: Idea: EEPROM/I2C-related routines corrupt the contents of some registers (possibly system or I/O registers, not just general-purpose ones) or memory (possibly that of memory-mapped devices). Also, is it possible that you may have a race condition somewhere, sharing a global variable in unsafe ways between threads/ISRs/main()?
Comment: I commented all of the I2C stuff, and got the expected result (42 lines of: 'addr: 0 byte: .\r\n' 'addr: 1 byte: .\r\n' ...  Which suggests that @AlexeyFrunze could be on to something with the I2C corrupting registers.  I renamed 'addr' to 'address' which didn't make any difference at all.
Comment: @Clifford unfortunately I do not have a debugger...  I get a segfault.  I made my description above more clear.
Comment: I have examined the I2C code, and I don't see anything that could cause a buffer overflow resulted in corrupt memory.  There is also no mention of strange behaviour in the datasheet errata.
Comment: @danthemman: how large is your stack?  It looks like this code might be for a very small system with limited stack size.  Formatted I/O routines often use a considerable amount of stack space; you may be overrunning the stack, which can cause all sorts of problems.
Comment: I am using a PIC18F25K22 chip (8bit) to interface with an EEPROM over I2C.  All of the program code and RAM lies internally with the PIC controller, and I am using an EEPROM to hold extra data.  I'm not really sure how to diagnose a RAM overflow in this kind of application.  However, the microcontroller is told to reset on stack overflow.
Comment: Fortunatly the segfault is with MPLAB.  I'll attempt to resolve this problem...
Comment: Can you add the value of addr to your opening sprintf() ("Starting EEPROM...")?
Comment: Well, examine the I2C code then.
Comment: Your function writes to `buf`, passed in at `&loc`.  What is `loc` and how is it declared?  If this parameter is incorrect,  writing to `buf` will cause data corruption and undefined behaviour. Insufficient information for a definitive answer, hence the comment.  Do you have a debugger to step this code and observe its behaviour?
Comment: Are the code and data both on the same chip with the CPU or in external memory? If external, are I2C I/O ports also used for external memory control signals? Or, CPU control? I mean, one port with completely different functions on different pins/bits. If that's the case, a simple bug such as improper bit manipulation (wrong mask, overflow, etc) can affect your program execution.
Comment: @KeithThompson:  The `addr` variable is an `unsigned int` not a pointer. so %u is exactly correct.  It refers to the EEPROM location, not a CPU addressable location.
Comment: @MichaelBurr:  Good point; I have seen formatted I/O implementations that need as much as 4KB of stack.
Comment: @Clifford: You're right. I'll delete my earlier comment.
Comment: @dantheman:  You earlier mentioned a segfault; on a PIC18!?  Or did you mean the debugger segfaulted?  If the latter I'd work on that problem first, you'd solve this problem much faster that way.
Answer: I'll tell you one thing wrong with your code, this line:
(unsigned char)addr>>8

doesn't do what you seem to need.
It converts the value in addr into an unsigned char which (assuming 8-bit char and either 16-bit int or only using the lower 16 bits of a wider int), will will always give you the lower eight bits.
If you then right shift that by eight bits, you'll always end up with zero.
If your intent is to get the upper eight bits of the address, you need to use:
(unsigned char)(addr>>8)

so that the shift is done first.

sprintf is outputting some strange data


TFS merge branches in Jenkins

Question: I've tried to merge between two branches in the Jenkins, but I didn't get it. I tried to solve this creating a pipeline (groovy) and run the tfs merge command, like this:
<code>stage('Merging between Dev and Homologação') {
        steps {
            script{

                try{
                     bat "tf merge ${TFS_BRANCH_DEV} ${TFS_BRANCH_HOMOLOGACAO} /recursive /version:T /login:${TFS_USR};${TFS_PSW}"
                }
                catch (exception) {
                    IS_MERGE = 1
                }

                try{
                    if (IS_MERGE == 1){
                        //resolve the merge conflits
                        bat "tf resolve ${TFS_BRANCH_HOMOLOGACAO} /auto:TakeTheirs /recursive /noprompt /login:${TFS_USR};${TFS_PSW}"

                        //build the solution
                        bat "\"${tool name: '.NET Compilação', type: 'msbuild'}\" ${TFS_BRANCH_HOMOLOGACAO_SO} /p:Configuration=Jenkins;Platform=\"Any CPU\" /t:Clean;Build"
                    }
                }
                catch (exception) {
                    throw exception
                }
            }
        }
</code>
Another solution is to create two jobs (free style) for getting and building development and homolog branches and then create another job, using multijob plugin. There, I invoke the other two build jobs and after that I run the merge and resolve command in the command windows area. It didn't work.
I don't know what to do. I got it easily using git another project, however using TFS likes difficult to do it.
Can anyone help me, please?
Thanks.
Comment: What's the error when you run your script? First please make sure tf command is installed on the CI server where your job is running (check where your job is running and jump onto that machine to check) or check tf.exe command  line located in the PATH (try specifying the full path to tf to check this)
Answer: I found a solution.
First, it is necessary to remove all workspaces. After, it needs to clean the TFS cache, as following:
Tfs 2017: "%localappdata%\Microsoft\Team Foundation\7.0\Cache\"
Tfs 2015: "%localappdata%\Microsoft\Team Foundation\6.0\Cache\"
Tfs 2013: "%localappdata%\Microsoft\Team Foundation\5.0\Cache\"
Tfs 2012: "%localappdata%\Microsoft\Team Foundation\4.0\Cache\"
Finally, if there is a free style job in the jenkins, check the workspace out is correct. In general tab, click on advanced project option button, and then mark "Use custom workspace", inform the workspace in the Directory field.

TFS merge branches in Jenkins


Teloxide-rs How to share state between different instances of the same bot?

Question: I'm using teloxide a bot that coordinates information between players of a game. As a simplified example, I want player A to mark task_1 as complete, and then I want player B to be able to ask the bot if task_1 has been completed or not and for the bot to respond appropriately.
So far I've tried the in-memory storage and the Redis storage, and both seem to be storing independent states. For example Player A can mark a task as complete, but when player B asks about the state of that task, it remains incomplete.
I haven't got sqlite setup on my machine so haven't tried it yet, but I wouldn't imagine it's setup differently to redis(?).
I could theoretically write the bot's state to a file on disk and then update the internal state every time, but that seems very round about for something I'm hoping teloxide already has built in?
Is there any way I can have multiple users mutating the same internal state of the bot?
Here's the code:
Here's the code I'm using. This is lightly adjusted from the db_remember.rs example so that I can get a number, reset the number, and set a number to something new using \set XXX
src/main.rs:
use teloxide::{
    dispatching::dialogue::{
        serializer::Bincode,
        ErasedStorage, RedisStorage, Storage,
    },
    prelude::*,
    utils::command::BotCommands,
};
use serde::{self, Deserialize, Serialize};

type MyDialogue = Dialogue<State, ErasedStorage<State>>;
type MyStorage = std::sync::Arc<ErasedStorage<State>>;
type HandlerResult = Result<(), Box<dyn std::error::Error + Send + Sync>>;

#[derive(Clone, Default, Serialize, Deserialize)]
pub enum State {
    #[default]
    Start,
    GotNumber(i32),
}

#[derive(Clone, BotCommands)]
#[command(rename_rule = "lowercase", description = "These commands are supported:")]
pub enum Command {
    #[command(description = "set your number.")]
    Set { num: i32 },
    #[command(description = "get your number.")]
    Get,
    #[command(description = "reset your number.")]
    Reset,
}

#[tokio::main]
async fn main() {
    pretty_env_logger::init();
    log::info!("Starting DB remember bot...");

    let bot = Bot::from_env();

    let storage: MyStorage = RedisStorage::open("redis://127.0.0.1:6379", Bincode).await.unwrap().erase();

    let handler = Update::filter_message()
        .enter_dialogue::<Message, ErasedStorage<State>, State>()
        .branch(dptree::case![State::Start].endpoint(start))
        .branch(
            dptree::case![State::GotNumber(n)]
                .branch(dptree::entry().filter_command::<Command>().endpoint(got_number))
                .branch(dptree::endpoint(invalid_command)),
        );

    Dispatcher::builder(bot, handler)
        .dependencies(dptree::deps![storage])
        .enable_ctrlc_handler()
        .build()
        .dispatch()
        .await;
}

async fn start(bot: Bot, dialogue: MyDialogue, msg: Message) -> HandlerResult {
    match msg.text().map(|text| text.parse::<i32>()) {
        Some(Ok(n)) => {
            log::info!("[{:?}] Number set to {n}", msg.chat.username());
            dialogue.update(State::GotNumber(n)).await?;
            bot.send_message(
                msg.chat.id,
                format!("Remembered number {n}. Now use /get or /reset."),
            )
            .await?;
        }
        _ => {
            bot.send_message(msg.chat.id, "Please, send me a number.").await?;
        }
    }

    Ok(())
}

async fn got_number(
    bot: Bot,
    dialogue: MyDialogue,
    num: i32, // Available from `State::GotNumber`.
    msg: Message,
    cmd: Command,
) -> HandlerResult {
    let old_num = num;
    match cmd {
        Command::Set { num } => {
            log::info!("[{:?}] Number changed from {} to {}",  msg.chat.username(), old_num, num);
            dialogue.update(State::GotNumber(num)).await?;
            bot.send_message(msg.chat.id, format!("Set your number from {} to {}", old_num, num)).await?;
        }
        Command::Get => {
            bot.send_message(msg.chat.id, format!("Here is your number: {num}.")).await?;
        }
        Command::Reset => {
            dialogue.reset().await?;
            bot.send_message(msg.chat.id, "Number reset.").await?;
        }
    }
    Ok(())
}

async fn invalid_command(bot: Bot, msg: Message) -> HandlerResult {
    bot.send_message(msg.chat.id, "Please, send /get or /reset.").await?;
    Ok(())
}

Cargo.toml:
[package]
name = "tmp"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
teloxide = { version = "0.12", features = ["macros", "redis-storage", "bincode-serializer"] }
log = "0.4"
pretty_env_logger = "0.4"
tokio = { version =  "1.8", features = ["rt-multi-thread", "macros"] }
serde_yaml = "0.9.17"
serde = "1.0.152"

Answer: This was answered by WaffleLapkin on the Teloxide github discussion page:

The dialogue storages in teloxide store state per chat, if you need something else, you'll need to work with databases directly.

So I ended up using a Redis database to store the game state, and regular in-memory for storing teloxide's state. Something like:
// Cargo.toml: redis = { version = "*" }
extern crate redis;
use redis::{Commands, Connection};

/// Establish a connection to the redis database,
/// used for sharing Game state across
/// different instances of the bot
fn connect_to_redis() -> Result<Connection, Box<dyn std::error::Error + Sync + Send>> {
    let client = redis::Client::open("redis://127.0.0.1/")?;
    let conn = client.get_connection()?;
    // Cargo.toml: log = "0.4"
    log::info!("Redis connection established");
    Ok(conn)
}

But then you also can't directly store a rust struct into redis, so I used serde_yaml to serialise the game state:
fn set_game_state(
    conn: &mut Connection,
    game: Game,
) -> Result<(), Box<dyn Error + Send + Sync>> {
    let game_key = "game_state";
    conn.set::<&str, String, ()>(game_key, serde_yaml::to_string(&game)?)?;
    Ok(())
}

And then stored it all as one long string in a single key in the DB.
To retrieve the game state is a similar operation, but I also added in some logic to create the game from an existing "template" YAML file game.yaml if the key doesn't exist:
fn get_game_state(conn: &mut Connection) -> Result<Game, Box<dyn Error + Send + Sync>> {
    let game_state_key = "game_state";
    let game_state: Game = if conn.exists(game_state_key)? {
        log::debug!("Getting game state");
        conn.get::<&str, String>(game_state_key)
            .and_then(|game_state| Ok(serde_yaml::from_str::<Game>(&game_state).unwrap().into()))?
    } else {
        log::debug!("Creating game state");
        let s = Game::new("challenges.yaml")?;
        let serialised = serde_yaml::to_string(&s)?;
        conn.set::<&str, String, ()>(game_state_key, serialised)?;
        s
    };
    Ok(game_state)
}

A bit overkill, but it works.


Does assigning a custom URLSessionDelegate override default behavior for methods that are not implemented?

Question: In the documentation for URLSessionDelegate it says:

Your URLSession object doesn't need to have a delegate. If no delegate
  is assigned, a system-provided delegate is used, and you must provide
  a completion callback to obtain the data.

I only need to implement one of the methods like this:
class SessionDelegate: NSObject, URLSessionTaskDelegate {
    func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
        var request = request
        request.httpMethod = task.originalRequest?.httpMethod ?? request.httpMethod
        completionHandler(request)
    }
}

And then initialize my session like this:
self.session = URLSession(configuration: config, delegate: SessionDelegate(), delegateQueue: nil)

Does that override any other behavior in the "system-provided delegate" for the methods that I didn't implement?
Answer: Any (optional) functions you don't override in your SessionDelegate class will respect the default implementation behaviour of the original functions.
In order to check the default behaviour for each function, please see the documentation in the header files (option+click on URLSessionTaskDelegate) or here:
https://developer.apple.com/documentation/foundation/urlsessiontaskdelegate


Unable to connect to azure-blob-storage after upgrading from v8 to v12 java sdk in azure using spring boot

Question: I am upgrading my existing spring boot application which uses azure-blob-storage from V8 SDK to V12 SDK. But I am getting authorization error. I almost tried all the examples suggested in azure sdk, but none of them are working. Below is the code between v8 and v12.
V8 (Working fine):
String endPoint = https://XXXXXXX.blob.core.windows.net/ecommerce/
String sasToken = sp=racwl&st=2021-06-01T05:12:04Z&se=2026-06-01T13:12:04Z&spr=https&sv=2020-02-05&sr=c&sig=XXXXXX%2BXXXXXXXXXXX%2BVVVVVVVVVVVV%3D
StorageCredentialsSharedAccessSignature s = new StorageCredentialsSharedAccessSignature("sas_token");
CloudBlobContainer cbc = new CloudBlobContainer(s.transformUri(new URI(endPoint)));

CloudBlobDirectory bd = cbc.getDirectoryReference("container_name");
InputStream is = new ByteArrayInputStream("my_string".getBytes());
CloudBlockBlob cbb = bd.getBlockBlobReference("blob_name");
cbb.upload(is, "my_string".length());

V12 (Failing with authentication):

String endPoint = https://XXXXXXX.blob.core.windows.net/ecommerce/
String sasToken = sp=racwl&st=2021-06-01T05:12:04Z&se=2026-06-01T13:12:04Z&spr=https&sv=2020-02-05&sr=c&sig=XXXXXX%2BXXXXXXXXXXX%2BVVVVVVVVVVVV%3D
BlobContainerClient bc = new BlobContainerClientBuilder().endpoint(endPoint).sasToken(sasToken).containerName("container_name").buildClient();
InputStream targetStream = new ByteArrayInputStream("my_string".getBytes());
BlockBlobClient cbb = bc.getBlobClient("blob_name").getBlockBlobClient();
cbb.upload(targetStream, payload.length()); ----> This is where it is throwing the exception

Error with V12 approach failing at authentication:
com.azure.storage.blob.models.BlobStorageException: If you are using a StorageSharedKeyCredential, and the server returned an error message that says 'Signature did not match', you can compare the string to sign with the one generated by the SDK. To log the string to sign, pass in the context key value pair 'Azure-Storage-Log-String-To-Sign': true to the appropriate method call.
If you are using a SAS token, and the server returned an error message that says 'Signature did not match', you can compare the string to sign with the one generated by the SDK. To log the string to sign, pass in the context key value pair 'Azure-Storage-Log-String-To-Sign': true to the appropriate generateSas method call.
Please remember to disable 'Azure-Storage-Log-String-To-Sign' before going to production as this string can potentially contain PII.
Status code 403, (empty body)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    ...

Comment: Can you edit your question and include the SAS token and endpoint URI. Please obfuscate the account name and sig portion of your SAS token.
Comment: @GauravMantri Updated the question with sas token and endpoint uri
Comment: Facing the same issue and the [workaround](https://stackoverflow.com/a/68677965/2996452) did not help
Answer: I was able to connect successfully now with the below code. However, there is still an issue with the actuator/health page
BlobContainerClient bcc = new BlobContainerClientBuilder().endpoint(reportProperties.getEndpoint() + "/" + containerName + "/" + "?" + reportProperties.getSastoken()).buildClient();
BlobClient blobClient = bcc.getBlobClient(blobName);
InputStream is = new ByteArrayInputStream("my_string".getBytes());
blobClient.upload(is, payload.length());

Answer: After a days work this is how I managed to get this to work with SDK V12.14.1:
    String endpoint = String.format(Locale.ROOT,
            "https://%s.blob.core.windows.net", "myStorage");

    AzureSasCredential sasCredential = new AzureSasCredential(
            "sp=racwdl&st=2021-10-21T12:23:00Z&se=2021-10-21T20:23:00Z&spr=https&sv=2020-08-04&sr=c&sig=vV...MI%3D");

    BlobServiceClient blobServiceClient = new BlobServiceClientBuilder()
            .endpoint(endpoint).credential(sasCredential).buildClient();

    BlobContainerClient blobContainerClient = blobServiceClient
            .getBlobContainerClient("myContainer");
    for (BlobItem blobItem : blobContainerClient.listBlobs()) {
        BlockBlobClient blobClient = blobContainerClient
                .getBlobClient(blobItem.getName()).getBlockBlobClient();
        System.out.println(blobClient.getBlobName());
    }


source 1.3 (use -source 5 or higher to enable generics)

Question: I am using Maven 2.x, Atlassian Bamboo with maven plugin my build jdk configuration is set to 1.6 and i don't have any jdk version enforced setting in pom.xml file.
When i compile project in my IDE it works fine but when i compile in bamboo it gives me following error.
I have already check my configured jdk version in task is 1.6 and i also tried to enforced jdk version from maven plugin in pom but didn't work as well. someone of you guys may have idea whats going on here ?
[INFO] ------------------------------------------------------------------------
[ERROR] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Compilation failure

in -source 1.3
(use -source 5 or higher to enable generics)
        List<String> matchedList = findMatchPhrase(keyword, expression);

[INFO] ------------------------------------------------------------------------
[INFO] For more information, run Maven with the -e switch

Answer: Add the below properties to your pom.xml.
<properties>
    <maven.compiler.target>1.6</maven.compiler.target>
    <maven.compiler.source>1.6</maven.compiler.source>
</properties>

Comment: Funny you asked this question when I faced exactly the same problem last week :)
Answer: Another way that doesn't involve modifying the pom is to specify the source and target in the command line:
mvn install -Dmaven.compiler.source=1.6 -Dmaven.compiler.target=1.6

Note that this should be avoided generally as the build cannot be guaranteed to be repeatable this way.


Adding methods to already defined class

Question: Why can I add a new method to String class?
class String
  def abc
    "hey"
  end
end

puts "jayanti".abc  #hey
puts "meow".abc     #hey

Can you guys also tell me what OOP concept this is? As in how could I relate this with the OOPS concepts normally taught.
Thanks again
Comment: So what? Ruby is not C, C++, or java.
Comment: It seems like you already know how. Your intention is not clear.
Comment: @sawa I meant why can I add a new method to another class? This shouldn't be allowed. Is it a Ruby specific thing? Is this an inheritance concept or something else?
Comment: Why shouldn't it be allowed?
Comment: I mean I haven't seen this happening in other languages like C, C++, java etc
Comment: Welcome to Ruby.
Answer: New answer:
So you're asking how this is possible.
In ruby everything is object (or almost). For example:
String.class # Class

The class of String is Class, so String is an instance of Class.
The ruby model object is not easy to understand at the first sight when you come from C++ or Java.
When you do:
class String
  def abc
    "hey"
  end
end
puts "foo".abc #hey

You're reopening the class String and define a new instance method abc. You can also add a new method to the String class thanks to the keyword self, like this:
class String
  def self.abc
    "hey from class :)"
  end
end
puts String.abc #hey from class :)

Here, you're adding a abc method to the String object itself.
If you're interested to learn how ruby works in depth, there is a lot of book, one of my favorite is this one:https://www.amazon.co.uk/Metaprogramming-Ruby-Program-Like-Facets/dp/1941222129
as Tiago said, the class reopening method is called Monkey patching and you have to use it sparingly :)
Previous answer:
You can use the self keyword, like this:
class String
  def self.abc
    "hey from class :)"
  end
end

puts String.abc #hey from class :)

Comment: Not sure why this is downvoted :/ The question is: "How can I add a new method to String class?". Maybe that's not what he wanted to say but my answer is the right answer to this specific question.
Comment: I mean How is this possible? More like Why can I add.. I'll change it. As in I don't get the concept. Is this a inheritance concept or something else.
Comment: In fact, you can reopen a class in Ruby. In Java or C++, an object is an instance of a class and nothing more. In Ruby, a class is also an object :)
Comment: Here is a basic explanation of why and how: http://runtime-era.blogspot.fr/2012/12/reopen-and-modify-ruby-classes-monkey.html
Comment: Alright Thanks. So this isn't anything like Inheritance or some other oops concept right?
Comment: This still doesn't make much sense to me but still its the best answer and I just think I'll have to read about this stuff
Comment: You have written **The class of String is Class, so String is an instance of Class.** How is this related to the concept I was asking about? Thanks again
Answer: In Ruby, modules and classes can be modified during runtime. From the documentation:

A module may be reopened any number of times to add, change or remove functionality.

But you should only modify your own modules / classes:

Reopening classes is a very powerful feature of Ruby, but it is best to only reopen classes you own. Reopening classes you do not own may lead to naming conflicts or difficult to diagnose bugs.

In particular, you should not alter Ruby's core classes.
Answer: That technique is called Monkey Patching:
https://en.wikipedia.org/wiki/Monkey_patch
Love or hate it, it's useful specially for tests, think of Mocks/Stubs.

Adding methods to already defined class


How can I connect remotely to our network from behind a double NAT?

Question: Having successfully set up my home office network for remote access via OpenVPN, I would now like to do the same thing at work, however I am double natted.
There is a central router maintained by the company that run our building, with Ethernet cables in each office. We have then connected our DD-WRT router, but obviously we only have a 192. Private ip address.
Our router has an OpenVPN server built in. To get this setup working, is it simply a case of asking the people who own the building to forward port 1194 to the ip address they have assigned our router? Or is it potentially more complicated than that?
Also, if we want to remote desktop in to one of our pcs, is it just a case of getting them to forward port 3389 to our router and then forwarding the same port on our router to the ip address of the pc we want to remotely control on our subnet?
Finally, is ddns going to be a challenge with this setup? Or should it work as expected providing we use their public ip address and relevant ports, ie 1194 or 3389?
Cheers
Rich
Answer:
To get this setup working, is it simply a case of asking the people who own the building to forward port 1194 to the ip address they have assigned our router?

Yes.*

Or is it potentially more complicated than that?

No.*

Also, if we want to remote desktop in to one of our pcs, is it just a case of getting them to forward port 3389 to our router and then forwarding the same port on our router to the ip address of the pc we want to remotely control on our subnet?

It's safer to access RDP server through VPN. Don't leave any other doors to your network, it will work if your ISP'd forward that port too.

Finally, is ddns going to be a challenge with this setup?

It depends if your ISP uses static or dynamic public address, if it's static, then you use address provided by your ISP. It can be simply your outside NAT address as well, you can check it for instance here. If dynamic, then there are some options too.
*assuming that your ISP does simple (P)NAT.
Comment: Ok, so it was as simple as getting port 1194 forwarded from the external router to my routers local ip address 192.168.1.194. DDNS was no problem. I simply directed it to the public IP of the external router and the port forwarding did the rest. I have taken the advice given by other members here and will use this port for my encrypted OpenVPN connection and then Remote desktop through that. This should be the most secure way of doing things. Thanks for everybody's help :)
Comment: The public IP address going to the external router is definitely dynamic, so I will need to use Dynamic DNS for this to work.
I currently have a DDNS account set up and directed towards the external router. I have asked the people that manage the router to forward UDP port 1194 to my IP address. Should that be enough?
Comment: You can use no-ip.com for instance - it's more or less reliable. Yes, that should be it.
Answer: The real answer is : Publish a vpn endpoint. This can be behind building NAT (it is better in a publicly visible endpoint).
From remote, you vpn to your network and then rdp over the vpn.
Making RDP publicly accessible is a bad bad idea.


Menu disappears on small screens

Question: On this site I implemented the Multi Level Push Menu. All works fine, but the menu disappears on small screens (tablet width and below). I use Bootstrap 3 und Drupal 7 in this project.
I already tried it with increasing the z-index on #menu, but it didn't worked.
I'm thankful for any suggestion.
Answer: According to this the problem, was that a div container pushed the menu away.
The old and wrong container was:

It could be fixed by adding additional bootstrap classes:

Comment: When you answer your own question it is customary to accept it as the answer so that it doesn't continue to appear in the unanswered list. Thanks!
Comment: yeah i tried, but stack systems says that this is only allowed two days after submission of the answer, so we have to wait one more day :)
Comment: ok lol sounds good!

Menu disappears on small screens


Get variable from controller in twig using template

Question: I have a php variable in my controller and i want to use it in twig.
So i do this :
Controller :
$firstLetter = '2017'; //dynamic variable but for the test it's a constant

$build ['list'] = array(
      '#theme' => 'liste-adh2',
      '#content'=>$result,
      '#filters'=>$ListApport,
      '#filters2' =>$Listline,
      '#test' => $firstLetter,  //sending to my template
   );

return $build;

Template :
function adh_apport_theme($existing, $type, $theme, $path)
{

    return [
        'liste-adh2' => [
            'variables' => ['content' => NULL, 'filters' => NULL,
                            'filters2' => NULL,], ['test' => NULL,],
                        ],
            ];
}

Twig :
{{ test.firstLetter }}

i got nothing in twig and i don't know why.
Thanks for helping.
Answer: I'm not sure why you're expecting test to be an object, you declared it as a string.
Assuming the value of "2017" from your example is what you're trying to get the variable is just:
{{ test }}

Comment: Omg i'm so bad, you save my day, really thank you for helping. Have a nice day :D


Erro de nome de app no django

Question: Na minha views, do django 1.10, tenho o código:

from django.shortcuts import *
from appcrud.forms import *

def inicial(request):
 if request.method == "POST":
  form = FormCrud(request.POST)
  if form.is_valid():
   form.save()
 else:
  form = FormCrud()
 return render(request, "index.html", {"form": form})

O forms:

from django import forms
from appcrud.models import *

class FormCrud(forms.Form):
 name = forms.CharField(max_length = 150)
 profissao = forms.CharField(max_length=150)

e o model:

from __future__ import unicode_literals

from django.db import models
from mongoengine import *

class Cruds(Document):
 name = StringField(max_length=150,required=True)
 profissao = StringField(max_length=150)

O servidor funciona normalmente mas aparece esse erro no retorno :

__init__() got an unexpected keyword argument 'current_app'
Request Method: GET
Request URL: http://localhost:8000/inicio/
Django Version: 1.10.3
Exception Type: TypeError
Exception Value:
__init__() got an unexpected keyword argument 'current_app'
Exception Location: C:\Anaconda2\lib\site-packages\django\shortcuts\__init__.py in render, line 49

Estou configurando o projeto para usar o mongodb, saberiam me responder?
Grato pela atenção!
Comment: Está parecendo que o Django 1.10 não está instalado corretamente, porque o render nem tem mais esse argumento `current_app` nessa [versão](https://github.com/django/django/blob/master/django/shortcuts.py#L15). Minha sugestão é desinstalar o Django, e instalar novamente:

`pip uninstall -y Django`

`pip install Django --no-cache-dir`
Comment: Valeu, o fiz e deu certo!
Comment: Vou jogar o texto do comentário como resposta, pra ficar documentado pra galera que futuramente esbarrar no mesmo problema :)
Answer: Está parecendo que o Django 1.10 não está instalado corretamente, porque o render nem tem mais esse argumento current_app nessa versão. Desinstale o Django, e instale novamente, mas sem usar o cache, com os seguintes comandos:
$ pip uninstall -y Django

$ pip install Django --no-cache-dir

Erro de nome de app no django


Is there a way to run a GCP Cloud Function locally while authenticated as a service account?

Question: I'm fairly new to GCP Cloud Functions.
I'm developing a cloud function within a GCP project which needs to access some other resources from the project (such as GCS, for instance). When I set up a cloud function, it gets a service account associated to it, so, I'm able give this service account the required permissions on the IAM and it works just fine in production.
I'm handling the required integrations by using the GCP SDKs and identifying the resources relative to the GCP project. For instance, if I need to access a GCS bucket within that project, it looks something like this:
    const bucket = await storage.bucket("bucket-name");

The problem with this is that I'm not able to access these resources if I'm running the cloud function locally for development, so, I have to deploy it every time to test it, which is a process that takes some time and makes development fairly unproductive.
So, is there any way I can run this cloud function locally whilst keeping the access to the necessary project resources so that I'm able to test it while developing? I figured that running this function as it's service account could work, but I don't know how to do it and I'm also open to different approaches.
Comment: If your user account as access to the account, authenticate yourself on your computer with the command `gcloud auth application-default login`. The client libraries use ADC to detect that authentication (as it detects that you run on Google Cloud) and reuse your credentials to run your code.
Answer: Yes, there is!
The only thing you need to do is setting the GOOGLE_APPLICATION_CREDENTIALS environment variable to the path of a service account json file and then the googleapis libraries handle the rest automatically, most of the time.


Personalized message in the cart by product category to encourage you to continue shopping

Question: With the following code I can display a message in the cart to encourage users to continue buying more products, but the message appears permanently for all product categories, how can I make it work for one or more specific categories? Thanks for what you can help me.
    add_action( 'woocommerce_before_cart_table', 'woo_add_continue_shopping_button_to_cart_products' );

function woo_add_continue_shopping_button_to_cart_products() {

 echo '
';
 echo ' Continue Shopping → Do you want more products?';
 echo '
';
}

Comment: _"how can I make it work for one or more specific categories"_ - loop over the current cart content, check what categories the products belong to, and then make your decision based on that …? You are not even specific here, what _exactly_ you want - show it only when _only_ products from those categories are in the cart, or at least one of them, or …?
Answer: You can create an array of the categories for which you want to show the 'Keep shopping' link, and an array of all categories currently in the cart. You can then use array_intersect() to see if there are any matches between the two arrays. If so, show the link:
add_action( 'woocommerce_before_cart_table', 'woo_add_continue_shopping_button_to_cart_products' );
function woo_add_continue_shopping_button_to_cart_products() {

    // Define categories which should show the keep shopping link
    $keep_shopping = array( 'Music', 'Clothing' );

    // Check categories in the cart
    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        $terms = get_the_terms( $cart_item['product_id'], 'product_cat' );
        if ( !empty($terms) ) {
            foreach ($terms as $key => $term) {
                $order_cats[$term->term_id] = $term->name;
            }
        }
    }

    // Get array of category matches
    $cat_matches = array_intersect( $keep_shopping, $order_cats );
    if ( count( $cat_matches ) > 0 ) {
        // 1 or more matches, show keep shopping link
        printf( '
Continue Shopping → Do you want more products?
', get_permalink( wc_get_page_id( 'shop' ) ) );
    }
}

Comment: I implemented your code with one of my categories, but it doesn't work, it doesn't show any messages. ¿It is possible to customize the follow button to redirect you to a custom URL?
Comment: I've tested this and it works on my end. Are you sure you've added the correct category name(s) to the $keep_shopping array? And that the items in the cart belong to one or more of the categories?
Comment: I have done everything correctly according to what you indicate and it does not show the message.
Comment: Could you add some items to the cart. Then add `echo ""; var_dump( $order_cats ); echo ""; die();` after the foreach loop. And reload the cart page. That should display an array of the categories in the cart. The values you'll find there will have to match with what you add to the `$keep_shopping` array.
Comment: show me that. `array(25) {
  [54]=>
  string(10) "Accesorios"
  [80]=>
  string(8) "Bandanas"
  [88]=> `
Comment: I can only see 2 of the 25 categories that were returned, but that is enough. Remove the line of code after the foreach loop I've sent, and make sure your cart has the same items in it. And change the `$keep_shopping` array to: `$keep_shopping = array( 'Accesorios', 'Bandanas' );`
Comment: what happens is that it was not including the sub categories so it did not work, now it does. But do you know why it doesn't work for virtual products?
Comment: Subcategories should also be included in the `$order_cats` array. And there is no specific reason why this wouldn't work for virtual products. Since this is the answer to your question could you mark it as accepted, and possibly upvote? Thank you in advance.
Comment: Thank you @Terminator-Barbapapa