How to correctly write a sagemaker tensorflow input_handler() that returns a numpy array?

Question: I am trying to implement a input_handler() in inference.py for a sagemaker inference container.
The images/arrays are very big (3D). So I want to pass in a S3 URI, then the input_handler() function should load the image/array from s3 and return the actual numpy array for the model (which expects a tensor):
def input_handler(data, context):

    d = data.read().decode('utf-8')

    body = json.loads(d)
    s3path = body['s3_path']

    s3 = S3FileSystem()
    df = np.load(s3.open(s3path))

    return df

Returning a numpy array worked with the Sagemaker python api version < 1.0 and input_fn(), but does not work with the new container used by sagemaker python api > 2.0 that expects input_handler().
The actual container image is "763104351884.dkr.ecr.eu-central-1.amazonaws.com/tensorflow-inference:1.15-gpu".
During inference, I get the following error in CloudWatch thrown by the container:
ERROR:python_service:exception handling request: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all(

Traceback (most recent call last):
  File "/sagemaker/python_service.py", line 289, in _handle_invocation_post
    res.body, res.content_type = self._handlers(data, context)
  File "/sagemaker/python_service.py", line 322, in handler
    response = requests.post(context.rest_uri, data=processed_input)
  File "/usr/local/lib/python3.6/dist-packages/requests/api.py", line 116, in post
    return request('post', url, data=data, json=json, **kwargs)
  File "/usr/local/lib/python3.6/dist-packages/requests/api.py", line 60, in request
    return session.request(method=method, url=url, **kwargs)
  File "/usr/local/lib/python3.6/dist-packages/requests/sessions.py", line 512, in request
    data=data or
{}
,

What is the correct return type? All examples I found were for json & text...
Comment: return json.dumps({"inputs": [df.tolist()] }) seems to work. But this is very inefficient for large 3d images (converting from np.array to string to tensor). Is there a better solution?
Comment: Still not working, when returning json/tolist() tensorflow returns "Invalid argument: input must be 5-dimensional"
Comment: Ok, remove the extra pair of brackets and the dimensions are right: json.dumps({"inputs": df.tolist() })
Answer: This seems to work:
return json.dumps({"inputs": df.tolist() }).
Comment: Stiefel, how should we provide input_handler (which converts json to numpy), I am providing like this `model = TensorFlowModel(entry_point='pre_process.py',
                        model_data='s3://...model.tar.gz', framework_version = '2.3.1',role=sagemaker.get_execution_role())` and then I call `model.deploy(initial_instance_count=1,instance_type='ml.m5.xlarge')` but it seems that input_handler isnt applying. any way to test it?
Comment: You can do a print("*** Test") in pre_process.py / input_handler(). In Amazon CloudWatch->LogGroups you will find the log for your end point. You can also add "def handler(data, context):" instead of input_handler() and see if this is called.


Global.asax URL rewriting

Question: The following works fine on my local host, but not on the server. I keep getting a page not found error. Any ideas? I also have a custom mime type setup in the web.config but that should not matter.
<code>'--------------------------------------------------------
'Sub Application_BeginRequest()
'--------------------------------------------------------
'.
'.
'.
Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)

    '----------------------------------------------------
    'Redirect
    '----------------------------------------------------
    '.
    '.
    '.
    If Request.RawUrl.Contains(".page") Then

        Context.RewritePath("/Default.aspx") ' TEST

    End If

End Sub
</code>
Answer: Replace
"/"
<code>   Context.RewritePath("Default.aspx") ' TEST
</code>
Comment: See http://stackoverflow.com/questions/282805/asp-net-development-server-simulates-iis6-or-iis7
Comment: This solution does not work. There is a CheckIfFile exist setting that is missing in IIS7. Now, I redid this as an HTTP Module, and I can get it to run perfectly on the server but not locally. The reason is you register the module differently in IIS if its version 6 or 7. Is there a way around this. This is becoming ridiculous. See http://stackoverflow.com/questions/282805/asp-net-development-server-simulates-iis6-or-iis7 and http://msdn.microsoft.com/en-us/library/ms227673.aspx

Global.asax URL rewriting


Como permitir quebra de linha no gridview?

Question: Fiz um teste no meu GridView escrevendo o titulo de um livro com muitos caracteres, o que aconteceu foi o seguinte: Ele expandiu meu grid além do tamanho da página, gerando uma quebra de layout. Meu GridView está com Width="100%". Já tentei colocar na coluna ItemStyle-Wrap="False" mas não funcionou, como resolver?
Comment: posta o código do seu grid.
Answer: A solução é definir a seguinte propriedade na coluna que deseja que haja a quebra de linha:
 ItemStyle-Wrap="True"

Ou simplesmente não coloque propriedade nenhuma. O padrão do GridView do Asp.NET é fazer a quebra. Se quiser que não haja quebra, daí adicione a mesma propriedade mas com o valor false. Dessa forma, o HTML gerado para a coluna () virá com a propriedade style="white-space:nowrap;".
Observação: Pela imagem do seu teste nunca vai haver quebra pois você incluiu uma única palavra com centenas de caracteres ("AAAAAAAAA....."). Tente testar com um texto comprido, mas com palavras de tamanhos variados e coerentes com palavras que existam.


How do you wrap an image with a link?

Question: In Drupal 7 this was done with the l() command and setting the html option to true. I have found the Link::fromTextAndUrl() method in Drupal 8 but no mention of something similar to the html option.
[EDIT]
I think i was not clear with my original question. This is not for an image field; i was simply asking how to wrap a link around:

Answer: This way should be bulletproof:
use Drupal\Core\Link;
use Drupal\Core\Render\Markup;

$url = $node->get('field_url')->getValue();
$imageUri = $node->get('field_image')->entity->getFileUri();
$image = [
  '#theme' => 'image_style',
  '#style_name' => 'medium',
  '#uri' => $imageUri,
  '#width' => 200,
  '#height' => 100
];
$rendered = render($image)
$linkMarkup = Markup::create($rendered);
$link = Link::fromTextAndUrl($linkMarkup, $url);
$link = $link->toRenderable();
render($link)

Answer: Yes, Link::fromTextAndUrl() is the replacement for l(), but in D8 you use toRenderable() instead of a html option. This produces a render array which is rendered later.
use Drupal\Core\Link;

  $renderable = Link::fromTextAndUrl($title, $url)
    ->toRenderable();

BTW you can build this render array directly, with the same result, or the image as title, see Render image that is linked
Answer: This worked for me:
use Drupal\Core\Link;
use Drupal\Core\Url;
use Drupal\Core\Render\Markup;
$img = '';
$rendered_image = render($img);
$image_markup = Markup::create($rendered_image);
$link = Link::fromTextAndUrl($image_markup, Url::fromUri('internal:/my_path'))->toString();

Answer: I am not sure if this functionality is preserved in D8
You could either do it in a twig template node--[type-name].html.twig
 {{ content.field_image }}

Or you could do it in a custom module manually
$url = $node->get('field_url')->getValue();
$image_uri = $node->field_image->entity->getFileUri();
$image_url = \Drupal\image\Entity\ImageStyle::load("large")->buildUrl($image_uri);
$image_with_link = "" . $image_url . "";

Comment: I was looking for the replacement of the l() function; you have just typed out the html for an A tag.

How do you wrap an image with a link?


How to play a piano score with three staves?

Question: I've decided to learn La Colombe by Olivier Messiaen, but the score looks like this, and I can't make any sense of it. What might be the purpose of this notation? Thank you very much :)
Answer: The purpose of the notation is to show more clearly the different independent lines of the musical texture. By using three staves, we see more easily the bass/accompaniment voice in the bottom staff, a melodic line in the middle staff, and a shimmering texture in the upper staff.
As for playing it, it's typically up to the performer how to split this material up into two hands. Composers split them up in different ways, so choose what makes the most practical and musical sense for you, and feel free to change your approach as needed.
Notice, for instance, that the top staff has rests on the downbeats, and both outer staves have (non-notated) rests at the end of each measure. These are clues that suggest when hands are supposed to be playing material in other staves.
In many cases, one hand will be playing two staves; in other instances, a single staff will occasionally need to be split among both hands.
Comment: Even with two staves, you really should generally feel free to split up the notes however is more convenient for you, not by staff.


Use a google font and include only [A-Z] and '&'

Question: Is there a way to use a google font and have it load only [A-Z] and the & ampersand character?
I would like to do this to reduce size and improve load time, since I will only use basic latin numbers and letters.
I can host the font myself if I must and it is legal to manipulate the font package, but am not sure if self-hosting is necessary and how to manipulate google's font package.
I have specified A-Z like this:
http://fonts.googleapis.com/css?family=Inconsolata&text=ABCDEFGHIJKLMNOPQRSTUVWXYZ

but specifying & is troublesome. Both of these don't work:
<link href='http://fonts.googleapis.com/css?family=Inconsolata&text=ABC&' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Inconsolata&text=ABC&' rel='stylesheet' type='text/css'>

Answer: There is no way to specify character ranges when including google fonts. The only way to do it is to specify each character like this:
http://fonts.googleapis.com/css2?family=Inconsolata&text=ABCDEFGHIJKLMNOPQRSTUVWXYZ

Comment: And if you only need to style the header, you can load even fewer characters: `http://fonts.googleapis.com/css?family=Inconsolata&text=MyHeader`
Answer: You can include special characters by url-encoding their UTF-8 representation.
& (U+0026) is 26 in UTF-8, so your url should have:
&text=ABCDEFGHIJKLMNOPQRSTUVWXYZ%26

Here's a handy tool for this:
http://www.url-encode-decode.com/


Recreating lyrics (words) from term frequency counts (numbers)

Question: I am trying to "recreate" music lyrics from term frequency counts. I have two source data files. The first is simply a list of the 5000 most-used terms in the corpus of lyrics I'm using, ranked in order from most used (1) to least used (5000). The second file is the lyrics corpus itself, composed of over 200,000 songs.
Each "song" is a comma-delimited string as follows:
SONGID1,SONGID2,1:13,2:10,4:6,7:15,....

where the first two entries are the ID tags of the song, followed by the terms (the numbers to the left of the colons) and the number of times that term is used in the song (the numbers to the right of the colons). In the example above, this would mean that "I" (the first entry "1" in the 5000 most-used terms) occurs 13 times in this given song, while "the" (the second-most used term) occurs 10 times, and so on.
What I want to do is go from this termID:termCount format to actually "recreating" the original (albeit scrambled) lyrics, where I set the numbers to the left of the colons to the actual terms and then list these terms the proper number of times given the term counts to the right of the colons. Again, using the short example above, my preferred resulting output would be:
SONGID1, SONGID2, I I I I I I I I I I I I I the the the the the the the the the the and and and and and and and...

and so on. Thanks!
Answer: Perhaps the following (untested) will inspire you. You didn't say how you wanted it outputted, so you may want to change the print()s to file writes or something.
//assumes that each word is on its own line, sorted from most to least common
String[] words = loadStrings("words.txt");

//two approaches:
//loadStrings() again, but a lot of memory usage for big files.
//buffered reader, which is more complicated but works well for large files.
BufferedReader reader = createReader("songs.txt");
String line = reader.readLine();
while(line != null){
  String[] data = line.split(",");
  print(data[0] + ", " + data[1]); //the two song IDs
  for(int i = 2; i < data.length; i++){
    String[] pair = data[i].split(":");
    // inelegant, but clear. You may have to subtract 1, if
    // the words index from 1 but the array indexes from 0
    for(int j = 0; j < int(pair[1]); j++)
      print(words[int(pair[0])] + " ");
  }
  println();
  line = reader.readLine();
}
reader.close();


Não devo exibir resultados negativos

Question: Montei uma query aonde trago algumas informações, dentre essas informações a ultima coluna retorna valores positivos, negativos e zerados.
Eu não quero que exiba as linhas com valores negativos, porém não estou sabendo fazer isto.
Está é a Query
SELECT C.SG_CONCESSIONARIO,
       A.NU_SG,
       A.NU_CHASSI,
       V.DS_NOME_MODELO,
       V.CD_MODELO_GARANTIA,
       B.CD_PECA_APLICADA,
       P.DS_PECA_IDIOMA1,
       P.QT_VENDA_MINIMA,
       (FN_RETORNA_QTD(B.CD_PECA_APLICADA, M.BOOK_NO, M.PAGE_NO)) AS QTD_CATALOGO,
       B.PR_PECA_ORIGINAL AS VL_UNITARIO,
       B.QT_PECA as QTD_SOLICITADO,
       (B.PR_PECA_ORIGINAL *
       (FN_RETORNA_QTD(B.CD_PECA_APLICADA, M.BOOK_NO, M.PAGE_NO))) AS PRECO_CAT,
       ((B.PR_PECA_ORIGINAL + B.VL_ICMS) * B.QT_PECA) AS PRECO_GAR,
       ((B.PR_PECA_ORIGINAL + B.VL_ICMS) * B.QT_PECA) -
       (B.PR_PECA_ORIGINAL *
       (FN_RETORNA_QTD(B.CD_PECA_APLICADA, M.BOOK_NO, M.PAGE_NO))) AS PRECO_DIF
  FROM GARANTIA A
  LEFT JOIN GARANTIA_PC B
    on A.NU_ORDEM_SERVICO = B.NU_ORDEM_SERVICO
   AND A.NU_SEQ_ORDEM_SERVICO = B.NU_SEQ_ORDEM_SERVICO
   AND A.CD_CONCESSIONARIO = B.CD_CONCESSIONARIO
  LEFT JOIN VEICULO V
    ON A.NU_CHASSI = V.NU_CHASSI
  LEFT JOIN MODEL_MASTER O
    ON v.cd_catalogo = O.CD_PRODUCAO
  LEFT JOIN PECA P
    ON B.CD_PECA_APLICADA = P.CD_PECA
  LEFT JOIN CAT_H5J021D K
    ON O.Illust_Pn = K.Illust_Pn
  LEFT JOIN CAT_H5J024D M
    ON K.BOOK_NO = M.BOOK_NO
   AND B.CD_PECA_APLICADA = M.PART_NO,
CONCESSIONARIO C
 WHERE A.DT_EXCLUSAO IS NULL
   AND B.DT_EXCLUSAO IS NULL
   AND C.DT_EXCLUSAO IS NULL
   AND A.CD_CONCESSIONARIO = C.ID_CONCESSIONARIO
   AND A.CD_TIPO_GARANTIA != 'C'
   AND A.DT_INCLUSAO BETWEEN TO_DATE('01/07/2015', 'dd/MM/yyyy') AND
       TO_DATE('02/07/2015', 'dd/MM/yyyy')
 order by NU_CHASSI, CD_PECA_APLICADA, M.BOOK_NO, M.PAGE_NO

Função FN_RETORNA_QTD
create or replace function FN_RETORNA_QTD(peca     in varchar2,
                                          catalogo in varchar2,
                                          page_no  in varchar2)
  return varchar2 is

  v_qtd number(2);

begin

  select qtd
    into v_qtd
    from (select M.QTY_1 as qtd
            from CAT_H5J024D M
           WHERE PART_NO = peca
             and m.book_no = catalogo
             and M.QTY_1 is not null
             and M.QTY_1 != 'AR'
             and M.PAGE_NO = page_no
          union
          select M.QTY_2 as qtd
            from CAT_H5J024D M
           WHERE PART_NO = peca
             and m.book_no = catalogo
             and M.QTY_2 is not null
             and M.QTY_2 != 'AR'
             and M.PAGE_NO = page_no
          union
          select M.QTY_3 as qtd
            from CAT_H5J024D M
           WHERE PART_NO = peca
             and m.book_no = catalogo
             and M.QTY_3 is not null
             and M.QTY_3 != 'AR'
             and M.PAGE_NO = page_no
          union
          select M.QTY_4 as qtd
            from CAT_H5J024D M
           WHERE PART_NO = peca
             and m.book_no = catalogo
             and M.QTY_4 is not null
             and M.QTY_4 != 'AR'
             and M.PAGE_NO = page_no
          union
          select M.QTY_5 as qtd
            from CAT_H5J024D M
           WHERE PART_NO = peca
             and m.book_no = catalogo
             and M.QTY_5 is not null
             and M.QTY_5 != 'AR'
             and M.PAGE_NO = page_no
             )
   where rownum = 1;

  return(v_qtd);

end FN_RETORNA_QTD;

Comment: Já tentou colocar o `(FN_RETORNA_QTD(B.CD_PECA_APLICADA, M.BOOK_NO, M.PAGE_NO))) >= 0` no where?
Comment: Tentei, mas ainda sim retornam os resultados negativos
Comment: A função FN_RETORNA_QTD pode retonar valores negativos?
Comment: A FN_RETORNA_QTD não retorna nenhum valor negativo. O que ela faz é informar a quantidade minima de peças utilizada em cada veículo de acordo com o catálogo em que a peça se encontra.
Estou incluindo a função na pergunta.
Comment: Outra pergunta @Igor, B.VL_ICMS e B.QT_PECA podem ser negativos?
Comment: Também não, os valores que retornam nesses itens é 0 ou maior. Somente a ultima coluna aonde é feito a conta de O preço da qtd_min do catalogo * preço da peça menos a qtd usada na garantia * preço que pode ser negativo.
Answer: A expressão que calcula o PRECO_DIF pode ser simplificada para:
B.PR_PECA_ORIGINAL*(B.QT_PECA + B.VL_ICMS - FN_RETORNA_QTD(B.CD_PECA_APLICADA, M.BOOK_NO, M.PAGE_NO))

Isso mostra que não basta fazer B.PR_PECA_ORIGINAL >= 0 ou FN_RETORNA_QTD >=0, já que se o resultado retornado pela FN_RETORNA_QTD for maior do que a soma entre B.QT_PECA + B.VL_ICMS, então o preço será negativo.
Neste caso, portanto, você pode incluir a seguinte expressão na sua clausula Where:
AND (B.QT_PECA + B.VL_ICMS - FN_RETORNA_QTD(B.CD_PECA_APLICADA, M.BOOK_NO, M.PAGE_NO)) >= 0

Uma outra solução seria criar uma tabela temporária com o resultado do SQL e depois fazer uma SQL nessa tabela WHERE PRECO_DIF >= 0.
Outra solução é colocar esse SQL dentro de outro e na clásula WHERE do SQL mais externo fazer PRECO_DIF >= 0.
Comment: Funcionou certinho adicionando o AND >=0. Também ficou mais limpo essa forma de calcular o PRECO_DIF.
Obrigado !

Não devo exibir resultados negativos


Why is $\sqrt{1 + \sin{x}}$ not differentiable?

Question: $1 + \sin x$ has a very trivial graph and is differentiable

However as it is raised to some powers its graph changes
for example if x > 1 the graph has the following form

It has a broader base which seems understandable considering that when some $x < 1$ is raised to higher powers it will become even smaller
However I am not able to understand the graphs when it is raised to powers smaller than 1

In this case the graph suddenly becomes non differentiable, the reason for which I am not able to understand. Also mathematically how can I prove that $\sqrt{1 + \sin{x}}$ is non differentiable ?
Comment: There are kinks at $-\pi/2,3\pi/2$, etc. which make the function not differentiable at these points. Much like the canonical example of $f(x)=|x|$. To show non differentiability, compute the left and right hand derivative limits at these points and see that they're not equal.
Answer: The most straightforward way to see that $f(x) = \sqrt{1+\sin x}$ is not differentiable at, say, $x = 3\pi/2$ would be to compute the derivative by the definition:
$$
f'(3\pi/2) = \lim_{h \to 0} \frac{f(3\pi/2 + h) - f(3\pi/2)}{h} = \lim_{h \to 0} \frac{\sqrt{1 + \sin(3\pi/2 + h)}}{h}.
$$
This limit is a bit tricky.  Hint:  Try computing
$$
\lim_{h \to 0^+} \frac{\sqrt{1+\sin(3\pi/2+h)}}{h} = \lim_{h \to 0^+} \sqrt{\frac{1+\sin(3\pi/2+h)}{h^2}}
$$
and then do a similar calculation for the limit as $h \to 0^-$.
Answer: At $x=0$, $$x^\alpha$$ is differentiable for $\alpha\ge1$ and not differentiable for $\alpha<1$, as you can check by computing the derivative.
Now close to its minima, $\sqrt{1+\sin x}$ behaves like a (rectified) linear function.
Comment: I think the final sentence could use more explanation.  One way to explain it would be to use the Taylor series for $\sin x$ centered at $3\pi/2$:  $\sin x = -1 + (x-3\pi/2)^2/2 - (x-3\pi/2)^4/4!+ \cdots$ and therefore $\sqrt{1+\sin x} = \sqrt{(x-3\pi/2)^2/2 - (x-3\pi/2)^4/4! + \cdots} = |x-3\pi/2|\sqrt{1/2 - (x-3\pi/2)^2/4! + \cdots}$.  For $x$ close to $3\pi/2$, $\sqrt{1+\sin x} \approx |x-3\pi/2| \sqrt{1/2}$.


Move "Submitted By" from node.tpl to page.tpl

Question: I'm looking to move "Submitted By" info from node.tpl to page.tpl however when I add the following from node.tpl into page.tpl I get errors. Im assuming I dont have access to those variables, but would like to know how I can set up a pre-proccess to get it to display as it does in the node.tpl
  <?php if ($display_submitted): ?>

      <?php print $submitted; ?>

  <?php endif; ?>

Comment: What kind of errors do you get? And at the `admin/structure/types/manage/page` the _Display Author and Date Information_ is enabled?
Comment: I'm not using DS and would like to keep it that way for  now if possible. Trying to reduce un-needed bloat.
Answer: you can construct your own with something like this, adjust as desired:
if(isset($node))
{
    $nodeUser = user_load($node->uid);
    print 'Submitted By ' . l(t($nodeUser->name), 'user/' . $node->uid) . ' on ' . format_date($node->created);
}

Answer: You can see herci's comment. It's settings to show or hidden submitted. Or you can see code here line below to preprocess variable $submitted
// Display post information only on certain node types.
  if (variable_get('node_submitted_' . $node->type, TRUE)) {
    $variables ['display_submitted'] = TRUE;
    $variables ['submitted'] = t('Submitted by !username on !datetime', array('!username' => $variables ['name'], '!datetime' => $variables ['date']));
    $variables ['user_picture'] = theme_get_setting('toggle_node_user_picture') ? theme('user_picture', array('account' => $node)) : '';
  }
  else {
    $variables ['display_submitted'] = FALSE;
    $variables ['submitted'] = '';
    $variables ['user_picture'] = '';
  }

You can write some line code in file template.php to set up show or hidden summitted.
function YourTheme_preprocess_node($vars){
  $node = $vars ['node'];
  if ($node->type == 'YOUR_TYPE') {
    $vars ['display_submitted'] = FALSE; //hide submitted
  }
}

Comment: I'm not looking to hide it.  This code looks like its works for withing the node.tpl.  Im specifically looking to move the Submitted by into the page.tpl
Comment: Do you read code? If $display_submitted = false, when line code in if ($display_submitted) don't print.
Comment: As i said before.... I'm not looking to hide anything.  @Geoff answered my question.
Comment: Ok. You have your answer.

Move “Submitted By” from node.tpl to page.tpl


Unit-speed Reparametrization of a circle

Question: I am studying some differential Geometry from Shifrin's differential Geometry notes.
From what I understand so far it seems like it is possible to unit-speed reparametrize a curve whenever the curve is regular.
In the notes that I am reading the parametrization of the circle is:
$\alpha = (a\cos{t},a\sin{t}), \implies \lVert \alpha '(t)\rVert = a$
And then it is mentioned that if we reparametrize the curve by
$\beta(s) = (a\cos(s/a),a\sin(s/a)) \implies \lVert\beta'(s)\rVert=1$
So my question how did the author derive that this exact reparametrization have unit speed?, He could impossibly just have guessed it..
And is there any General way to find a unit speed reparametrization of a parametrized curve?
Comment: When dealing with a problem involving a simple curve like this, it's probably better to use simple algebra and geometry than calculus. And since the circle has uniform speed, you could just treat it as a line segment of length $2\pi a$ instead.
Answer: The answer to your question is at the top of p. 8 of my notes. In the case of the circle as originally parametrized, the arclength, starting at $t=0$, is $s(t)=at$. So $t=s/a$. Thus, $\beta(s) = \alpha(s/a) = \big(a\cos(s/a),a\sin(s/a)\big)$ is a reparametrization by arclength. You can immediately check that $\|\beta'(s)\|=1$, but the general argument is in the notes there.
Comment: No, you get the unit tangent vector along the curve. That's sort of the whole point, as you'll see in the next section.
Comment: Now this might be a silly question, but when taking the derivative of a unit-speed reparametrization curve, do we just get 0?
Answer: The speed of a parametrization $r$ is given by $|r'|$ by definition. Intuitively you can think of it in this way: if you visualize your curve in space and assume $t$ to represent time then $r(t+ \Delta t)-r(t)$ is the vector that takes the points on the curve $r(t)$ at time $t$ to the point on the curve $\Delta t$ time later, which is $r(t+ \Delta t)$. If you divide this by $\Delta t$ you obtain a vector  $\frac{r(t+ \Delta t)-r(t)}{\Delta t}$ whose norm is just "distance" between two points divided by the time it takes to go from one to anoher. By making $\Delta t$ very small and by taking the norm one obtains the so called speed of the parametrization.
You can look for unitary speed parametrized curves at https://en.wikipedia.org/wiki/Differential_geometry_of_curves#Length_and_natural_parametrization
Comment: Sorry my question was stated unclearly... I edited to how did the author know that this exact reparametrization have unit speed
Comment: It's the definition of derivatives of functions $\mathbb{R} \rightarrow \mathbb{R}^n$ : $\beta ' (s) = ( \beta_1'(s), \beta_2'(s) ) = (-a \frac{1}{a} \sin(s/a), a \frac{1}{a}  \cos(s/a))$. Now if you compute the norm it's $1$


ErrorException Undefined variable | Laravel , php

Question: i'm new to Laravel.
I have trouble in showing data to a view page with this error:
ErrorException
Undefined variable $ikus (View: D:\XAMPP\htdocs\SKP-PA-BKT\resources\views\iku.blade.php)

And Laravel give me solution:
$ikus is undefined

Here is code in iku.blade.php :
@extends('layouts.sidebar')

@section('content')

                                No
                                Opsi

                                @foreach ($ikus as $iku)
                                {{ $iku->id }}
                                @endforeach

@endsection

Here's code in IkuController.php
<?php

namespace App\Http\Controllers

use App\Models\Iku;
use Illuminate\Http\Request;

class IkuController extends Controller
{
    public function getIku()
    {
        $ikus = Iku::all();
        //dd($ikus);
        return view('iku', compact('ikus'));
    }
}

And here's in web.php
<?php

use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\IkuController;

Auth::routes();
Route::get('/', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Route::get('/indikator-kinerja', [IkuController::class, 'getIku'])->name('iku');

It seems the $ikus variable from IkuController.php file can not be accessed by iku.blade.php file.
I have looked for solutions and most of what i've found is to add code like this:
    return view ('layouts.index')->with(['features' => $features]);

or like this one:
return view ('layouts.index', compact('features'));

in IkuController.php file.
I have added it as written above. But i still get the same error. Is there anything left?
Thanks in advance.
Answer: This is most likely because your view is cached, you most likely ran the command
php artisan optimize

So just clear your view cache by doing:
php artisan view:clear

For the future, you can always see what is being cached by doing
php artisan about


Why would considering $\theta$ to be a random variable not be 'Bayesian'?

Question: I am currently studying the textbook In All Likelihood -- Statistical Modelling and Inference Using Likelihood by Yudi Pawitan. Section Inverse probability: the Bayesians of chapter 1 says the following:

The first modern method to assimilate observed data for quantitative inductive reasoning was published (posthumously) in 1763 by Bayes with his Essay towards Solving a Problem in the Doctrine of Chances. He used an inverse probability, via the now-standard Bayes theorem, to estimate a binomial probability. The simplest form of the Bayes theorem for two events $A$ and $B$ is
$$P(A \vert B) = \dfrac{P(AB)}{P(B)} = \dfrac{P(B \vert A)P(A)}{P(B \vert A)P(A) + P(B \vert \overline{A})P(\overline{A})}. \tag{1.1}$$
Suppose the unknown binomial probability is $\theta$ and the observed number of successes in $n$ independent trials is $x$. Then, in modern notation, Bayes's solution is
$$f(\theta \vert x) = \dfrac{f(x, \theta)}{f(x)} = \dfrac{f(x \vert \theta) f(\theta)}{\int f(x \vert \theta) f(\theta) d \theta}, \tag{1.2}$$
where $f(\theta \vert x)$ is the conditional density of $\theta$ given $x$, $f(\theta)$ is the so-called prior density of $\theta$ and $f(x)$ is the marginal probability of $x$. (Note that we have used the symbol $f(\cdot)$ as a generic function, much like the way we use $P(\cdot)$ for probability. The named argument(s) of the function determines what the function is. Thus, $f(\theta, x)$ is the joint density of $\theta$ and $x$, $f(x \vert \theta)$ is the conditional density of $x$ given $\theta$, etc.)
Leaving aside the problem of specifying $f(\theta)$, Bayes had accomplished a giant step: he had put the problem of inductive inference (i.e. learning from data $x$) within the clean deductive steps of mathematics. Alas, 'the problem of specifying $f(\theta)$' a priori is an equally giant point of controversy up to the present day.
There is nothing controversial about the Bayes theorem (1.1), but (1.2) is a different matter. Both $A$ and $B$ in (1.1) are random events, while in the Bayesian use of (1.2) only $x$ needs to be a random outcome; in a typical binomial experiment $\theta$ is an unknown fixed parameter. Bayes was well aware of this problem, which he overcame by considering that $\theta$ was generated in an auxiliary physical experiment - throwing a ball on a level square table - such that $\theta$ is expected to be uniform in the interval $(0, 1)$. Specifically, in this case we have $f(\theta) = 1$ and
$$f(\theta \vert x) = \dfrac{\theta^x(1 - \theta)^{n - x}}{\int_0^1 u^x(1 - u)^{n - x} du} \tag{1.3}$$
Fisher was very respectful of Bayes's seeming apprehension about using an axiomatic prior; in fact, he used Bayes's auxiliary experiment to indicate that Bayes was not a Bayesian in the modern sense. If $\theta$ is a random variable then there is nothing 'Bayesian' in the use of the Bayes theorem. Frequentists do use the Bayes theorem in applications that call for it.

It is this last part that I am curious about:

Fisher was very respectful of Bayes's seeming apprehension about using an axiomatic prior; in fact, he used Bayes's auxiliary experiment to indicate that Bayes was not a Bayesian in the modern sense. If $\theta$ is a random variable then there is nothing 'Bayesian' in the use of the Bayes theorem. Frequentists do use the Bayes theorem in applications that call for it.

So what specifically is the controversy here? Why would considering $\theta$ to be a random variable not be 'Bayesian'?
Based on prior (hehe, no pun intended) study, I understanding that there is significant controversy here between Bayesians and Frequentists. And I understand the differences between the two philosophies. But it's not clear to me what the specific problem is with Bayes's work (or, rather, what it is that Frequentists find so controversial about his work).
I would greatly appreciate it if people would please take the time to explain this.
Comment: Essentially, if the prior distribution on $\theta$ is provided by the experimental setting, ie if there is no debate about the prior, then this is not a Bayesian framework but rather an error-in-variable type model.
Comment: Frequentists find nothing at all controversial about Bayes' Theorem--it is, after all, a simple mathematical lemma.  Many frequentist results are proven using Bayes' Theorem and Bayesian approaches. The heart of the matter--beyond a fundamental difference in interpreting the meaning of "probability"--concerns what it means to model parameters by means of probability distributions and how to determine those distributions.
Comment: There's "subjective" and "objective Bayes", and more than one flavour of each. It's not appropriate to talk about "Bayesians" as if this was a homogeneous group.
Comment: @whuber is it fair to say the "controversy" arises in the Bayesian interpretation of probability, which allows one to use Bayes theorem to assign probability to retrospective events?
Comment: @AdamO I don't think any controversy pertains to the temporal sequence of events.
Comment: @Xi'an So this was what Fisher was referring to? The fact that, in Bayes's table experiment, the nature of the experiment forces us to use the uniform distribution as the prior, rather than having to speculate?
Comment: Obviously, I have no idea what Fisher was thinking. And we have very little idea either at Bayes' reason(ing) for using the Uniform. For all I know, he picked the Uniform for convenience's sake as a completely artificial illustration of the derivation of a conditional density and had no inkling he was starting a school of statistical inference.
Comment: @Xi'an so, essentially, the differentiating characteristic is that the prior is subjective (for the Bayesian framework)?
Comment: @Xi'an 'relative' instead of 'subjective'? And 'multiverse' instead of 'framework'?
Comment: @Lewian Oh, I see.
Answer: The quote does not say that if $\theta$ is a random variable, this is not Bayesian scenario. It says that the fact that $\theta$ is a random variable doesn't make it a Bayesian setting by itself. As already noticed in the comments, Bayes theorem is just a theorem in probability theory that lets us get the "reversed" conditional probability from $p(a|b)$ to $p(b|a)$. As mentioned here, or here, $a$ and $b$ can be any random variables for Bayes theorem to hold.
In Bayesian statistics we use Bayes theorem with particular kind of random variables, the ones that are "made up", the prior distributions. When Bayesian wants to estimate the distribution of the parameter of interest $\theta$ for the likelihood function $p(x|\theta)$, she uses a prior distribution $p(\theta)$ (the distribution that she assumes that the parameter can follow) and applies Bayes theorem, to calculate the posterior
$$
p(\theta|x) = \frac{p(x|\theta)\;p(\theta)}{p(x)}
$$
In non-Bayesian setting, you could use some random variables, in this example, they show how can we calculate the probability of having a cancer given the positive test result $p(C|+)$ by applying Bayes theorem to cancer prevalence $p(C)$ and the probability of the test of giving positive results $p(+|C)$:
$$
p(C|+) = \frac{p(+|C)\,p(C)}{p(+)}
$$
In here, both probabilities are known to us, contrary to Bayesian setting where the prior is assumed.
Comment: I don't understand what you mean by "It says that $\theta$ could be a random variable *while* this weren't a Bayesian setting." Can you please elaborate?
Comment: @ThePointer see my edit.
Comment: *"In here, both probabilities are known to us, contrary to Bayesian setting where the prior is assumed."* Is the Bayesian setting really defined as 'when the prior is assumed instead of known'?
Comment: @SextusEmpiricus what I wanted to say is that Bayesian statistics is about updating your knowledge or assumptions. However I agree, this is a vague statement.
Comment: @Tim, I believe that the cancer example is also about updating knowledge/assumptions. But it is all indeed very vague. I guess that the philosophical problems are more a matter whether it is appropiate to 'treat a parameter that is fixed, e.g. a physical constant, as a variable'. And there is the other (practical) matter about how to 'choose' a prior and the possibility that the method introduces (too much) subjectivity. I guess that it is more about the philosophical matter when it is about the situation whether we consider $\theta $ as a random variable or not.
Answer: I think that the confusion stems from a somewhat ambiguous use of the terminology. In my view the term frequentism should be used for an interpretation of probabilities, namely that they refer to data generating processes in reality and correspond to limits of relative frequencies under idealised infinite repetition. In frequentism often parametric models are used in which the parameter is fixed. However, it is also possible to have a process in which a parameter value itself is the result of a potentially repeatable experiment, in which case there can be a frequentist distribution over the parameter, and Bayes theorem can be applied. Otherwise, though, most frequentists would not accept a probability distribution over their parameters, because they are fixed and not random in reality, or rather in what they think of as reality.
What is today called "Bayesian" is an approach in which a prior distribution over the parameter of parametric model is assumed, which normally is interpreted as encoding epistemic probabilities, referring to prior knowledge of the parameter, but not to a real physical process generating it. This approach always requires Bayes theorem. However this can still be connected with a frequentist idea of probabilities, see e.g. the section on "falsificationist Bayes" in Gelman and Hennig "Beyond subjective and objective in statistics".
Furthermore, Fisher favoured so-called "fiducial probabilities", which are epistemic probabilities over the parameters of frequentist models. These are widely rejected these days though. Anyway, in this setting the $\theta$ was treated as random variable, but without prior, not requiring Bayes theorem.
What I find problematic and potentially confusing about the terminology is that seemingly today many would no longer call the use of Bayesian computation with frequentist probabilities Bayesian, despite the fact that Bayes himself did such a thing.
Comment: Interesting. Thanks for the clarification.


What are the URLs being accessed while installing Laravel and AsgardCMS?

Question: I recently joined an organisation with a very restrictive corporate proxy policy. As we would be working primarily on Laravel and AsgardCMS, I was told to install them on the machine provided (Windows 7, limited user account).
Now, individual URLs need to be approved and whitelisted by the management here. So far, I identified two URLs I would be needing to install the above.

https://packagist.org/
https://api.github.com/

My manager asked me for a comprehensive list of URLs for him to whitelist so that he doesn't have to contact IT time and again.
This has put me in a kind of fix as I am unable to predict what URLs access the installation and subsequent running of Laravel and AsgardCMS would entail.
I tried to run iftop while running the installation on my personal machine to check which URLs are getting accessed but all it is giving me is some random IP addressed and URLs, not the list I was expecting.
Any help would be greatly appreciated.
Answer: I'm not entirely sure all all the endpoints its hitting during a composer install, but your list looks correct. Composer will hit packagist, which in turn will hit github.
Comment: Thanks. :) the suits at work have somewhat opened up. Could finally get an installation of Asgard CMS running on the server.


Embed Views remove pager

Question: I have embedded view in a node with following code:
<code><?php
 $view = views_get_view('articles');
 $view->set_items_per_page(1);
 $view->set_offset(2);
 print $view->preview('page');
 $view->destroy();
?>
</code>
I just need to display only one specific row (that's why I'm using offset). I couldn't find a way to retrieve one specific row with any other method.
This code is acceptable but it has pager because that view has more than one row.
Is there a way to remove pager like in Views UI? In Views there is a option to not use a pager but "Display a specified number of items".
I would like to remove it completely from code without CSS.
Comment: The simplest way might be to create a second display via the Views UI (call it `offset_2` for descriptive purposes) that doesn't have a pager in it, eg, selecting `Display a specified number of items` instead of `Paged Output` and then calling that in your `print $view->preview('offset_2');`
Comment: Yes, it's  possible to do that way but I wanted to do this programaticaly. I want to optimize page as much as possible because that page has already too much queries.
Comment: It would be much better to do it from single display. I will need to create about 10 displays. it will clutter views ui. Reason I'm doing this is to have about 10 blocks placed on diferrent places on page. Think of metro ui.
Comment: well you can always modify the pager settings in a pre_render() or pre_build() hook much like you are doing in your question with other settings.  google will be your friend here as there are many options.  http://drupal.stackexchange.com/questions/86007/change-views-pager-programmatically?rq=1 might be a good starting place.
Comment: you could also look at somehow overriding the appropriate theme template for this view.  if you look in there you will see the pager is creating by just printing `$pager` so if you can figure out a way to target this instantiation of the view, you could just comment it out there.
Answer: I ended up having to hide the specific pager with css in the case I did what you are trying to do...
Comment: I'm aware of display:none but I would like to remove it from code. CSS is last resort.
Comment: I understand that, I am saying that I was unable to find another way after much research...hopefully you can, unfortunately I don't think you will...
Comment: If I stumble across anything I will certainly post it here.

Embed Views remove pager


Hausdorff's maximality principle lemma in Rudin Real and Complex analysis

Question: Here's the lemma that is needed before proving the Hausdorff's maximality principle (in Rudin's real and complex analysis appendix):

Lemma Suppose $\mathcal{F}$ is a nonempty collection of subsets of a set $X$ such that the union of every subchain of $\mathcal{F}$ belongs to $\mathcal{F}$. Suppose $g$ is a function which associates to each $A \in \mathcal{F}$ a set $g(A) \in \mathcal{F}$ such that $A \subset g(A)$ and $g(A) - A$ consists of at most one element. Then there exists an $A \in \mathcal{F}$ for which $g(A) = A$.

In the proof, it first defines a tower:

Fix $A_0 \in \mathcal{F}$. Call a subcollection $\mathcal{F}'$ of $\mathcal{F}$ a tower if $\mathcal{F}'$ has the following three properties:
(a) $A_0 \in \mathcal{F}'$
(b) The union of every subchain of $\mathcal{F}'$ belongs to $\mathcal{F}'$
(c) If $A \in \mathcal{F}'$, then also $g(A) \in \mathcal{F}'$

In the proof, we let $\mathcal{F}_0$ be the intersection of all towers which is also a tower (proof is trivial). Then we go on to define two more collection of sets:

Let $\Gamma$ be the collection of all $C \in \mathcal{F}_0$ such that every $A \in \mathcal{F}_0$ satisfies either $A \subset C$ or $C \subset A$.
For each $C \in \Gamma$, let $\Phi(C)$ be the collection of all $A \in \mathcal{F}_0$ such that either $A \subset C$ or $g(C) \subset A$.

In other words
\begin{align*}
\Gamma &= \{ C \in \mathcal{F}_0 : A \subset C \text{ or } C \subset A \; \text{ for every } A \in \mathcal{F}_0 \}\\
\Phi(C) &= \{ A \in \mathcal{F}_0: A \subset C \text{ or } g(C) \subset A \}
\end{align*}
Now in the proof, it proves that $\Phi(C)$ is a tower by showing that it meets all three properties shown above. The first two properties can be shown easily. For the third property, we do the following:

If $A \in \Phi(C)$ there are three possibilities: Either $A \subset C$ and $A \neq C$, or $A = C$, or $g(C) \subset A$. If $A$ is a proper subset of $C$, then $C$ cannot be a proper subset of $g(A)$, otherwise $g(A) - A$ would contain at least two elements; since $C \in \Gamma$, it follows that $g(A) \subset C$. If $A = C$, then $g(A) = g(C)$. If $g(C) \subset A$, then also $g(C) \subset g(A)$ since $A \subset g(A)$. Thus $g(A) \in \Phi(C)$, and we have proved that $\Phi(C)$ is a tower. The minimality of $\mathcal{F}_0$ implies now that $\Phi(C) = \mathcal{F}_0$, for every $C \in \Gamma$

I am stuck on the last claim in the proof where it says The minimality of $\mathcal{F}_0$ implies now that $\Phi(C) = \mathcal{F}_0$, for every $C \in \Gamma$. What exactly does the minimality mean in this context and how does that lead to the equality? My guess is that $\Phi(C)$ is the smallest tower containing $C$, and since $\mathcal{F}_0$ is also the smallest tower containing $C$, they must be equal?
Also the proof says that

In other words, if $A \in \mathcal{F}_0$ and $C \in \Gamma$, then either $A \subset C$ or $g(C) \subset A$. But this says that $g(C) \in \Gamma$. Hence $\Gamma$ is a tower, and the minimality of $\mathcal{F}_0$ shows that $\Gamma = \mathcal{F}_0$. It follows from the definition of $\Gamma$ that $\mathcal{F}_0$ is totally ordered.

Here, since $\Phi(C) = \mathcal{F}_0$, for any $A \in \mathcal{F}_0$, either $A \subset C$ or $g(C) \subset A$. Since $C \subset g(C)$, we can say that for all $A \in \mathcal{F}_0$, either $A \subset g(C)$ or $g(C) \subset A$, which implies that $g(C) \in \Gamma$. Hence this satisfies property (c) of the definition of tower. Here they again use the minimality condition to show that $\Gamma = \mathcal{F}_0$ which I'm not sure how they did. And how does this result in $\mathcal{F}_0$ being totally ordered?
Answer:
What exactly does the minimality mean in this context and how does that lead to the equality?

Recall that $\mathscr F_0$ is the intersection of all towers. Hence it is a subset of every tower, and is thus the smallest possible tower. But $\Phi(C)$ is also a tower, and a subset of $\mathscr F_0$. Since they are both subsets of the other, $\Phi(C) = \mathscr F_0$.
The same is true for $\Gamma$. By its definition, it is a subset of $\mathscr F_0$, and now you have shown it is a tower, so  $\mathscr F_0$ is a subset of it. So $\Gamma = \mathscr F_0$.
You will encounter this sort of construction a lot. If you have a property on a collection of sets which is preserved under intersection (including infinite intersections), then the intersection of all sets with the property will be the smallest set having that property. Similarly if a property is preserved under unions, then the union of all sets having the property will be the largest set having that property. Two simple examples involving a set $A$ in a topological space:

The union of all open sets within $A$ is the largest open set in $A$. This is the interior of $A$.
The intersection of all closed sets containing $A$ is the smallest closed set containing $A$. This is the closure of $A$.

As for totally ordered, $\subset$ is already a partial order on $\mathscr F_0$, so to get totally ordered, all that is needed is to show that every two elements of $\mathscr F_0$ are comparable. But $\Gamma$ is by definition every set which is comparable to all sets in $\mathscr F_0$. And since it turns out $\Gamma$ is $\mathscr F_0$, that means every set in $\mathscr F_0$ is comparable to every other.
Comment: @texmex - since $\scr F_0$ is the intersection of all towers that are subsets of $\scr F$. Any subset $\scr G$ of $\scr F_0$ is also a subset of $\scr F$. If $\scr G$ is a tower, then it is one of the towers in the intersection defining $\scr F_0$, and thus $\scr F_0 \subseteq \scr G$. Thus it can only be that $\scr G = \scr F_0$, not a proper subset.
Comment: Thank you for the detailed answer!
Comment: @paulsinclair Please note, in the proof it is mentioned that: "A proper Subcollection of $\mathscr F_0$ is not a Tower". Can you please clarify and show how this is the case. Am happy to make this a separate question if necessary?
Comment: @PaulSinclair Thanks for this very helpful answer. I will be in touch if I have more questions.
Comment: @PaulSinclair Could you please clarify this related question? It is stated that $A_{0}\subset A$ if $A\in\mathscr{F}_{0}$. Suppose there is $A\in\mathscr{F}_{0}$
such that $A_{0}\not\subset A$. Then all towers need to contain $A$
since $\mathscr{F}_{0}$ is the intersection of all towers. But we
can have valid a tower without containing $A$ contradicting the definition
that $\mathscr{F}_{0}$ is the intersection of all towers.
Comment: @texmex - could you please clarify that question? What is $A_0$? Where is this "stated"? Why would the existence of a subset of a set in $A_0$ imply the existences of a tower in $\scr F$? Why do you claim that $A_0 \subset A$, then suppose $A_0 \not\subset A$? Did no one teach you that you should not use the same variable in the same context to mean two different things?
Comment: @PaulSinclair, Please note the $A_{0}$ is the same one given in the definition of a tower. Each tower contains a $A_{0}$ by definition. This is given above in the original question. It is stated in the proof of the Lemma for this question that $A_{0}\subset A$ if $A\in\mathscr{F}_{0}$. We are trying to prove this by contradiction. Perhaps should have stated the contradiction part above. So the naming of the variables should be fine. Please let me know if I should clarify this further.
Comment: @texmex - okay, I think I understand now, except what is it that you are asking about? You assumed the existence of an $A$ with $A_0\not\subset A$, and arrived at a contradiction, thus showing that no such $A$ can exist. What is your concern? Is it why there is a valid tower not containing $A$?  $\{A_0\}\cup \{g^n(A_0)\mid n\in \Bbb N\}$ is such a tower, which cannot contain $A$ since $A_0 \subset g^n(A_0)$ for all $n$.
Comment: I guess I need to be a little more careful than that, as it isn't closed under unions of subchains. But for that you could define that set as $G(A_0)$, then define $\mathscr G = \bigcup_{n=1}^\infty G^n(A_0)$ to get a tower.
Comment: @PaulSinclair, Thanks again for your helpful clarifications. I will digest this and be in touch if anything else.


select dynamic element using document doesn't work

Question: $(document).on('ul li:nth-child(even)',function(){
    $(this).addClass('e');
});

user can add and delete li, but with the code above it doesn't seem work.
Comment: You must specify the event type. Look at `on` documentation.
Comment: Your code doesn't really make sense. Can you precise what you try to do ?
Comment: I used like this  $('ul li:nth-child(even)').addClass('even'); it doesn;t work too
Comment: add class to every 2nd item of my li
Answer: I don't think you need on here; on is designed for event attaching and handling:

Attach an event handler function for one or more events
  to the selected elements.

Try:
$('ul li:nth-child(even)').addClass('e');

Demo: http://jsfiddle.net/IrvinDominin/6u6wS/


Como trocar uma imagem pelo Javascript

Question: Preciso mudar uma imagem pelo javaScript mas não estou conseguindo, tentei da seguinte forma e não funcionou;
html

JavaScript
document.getElementById("imagemPerfil").src ="<?php echo'../img/perfilUsuario/'.$usuario_pesquisado->getImg(); ?>";

notei que o valor é recebido pelo php, porém ele não é passado ao src da imagem
Answer: Ola,
Eu vejo duas opcoes que voce pode utilizar, talvez com mais detalhes de como vc quer utilizar eu tenha outras ideias, mas vamos la:
voce pode atribuir a img direto no src:
<img id="imagemPerfil" src="<?php echo'../img/perfilUsuario/'.$usuario_pesquisado->getImg(); ?>" alt="profile image"  class="circle z-depth-2 responsive-img activator gradient-45deg-light-blue-cyan gradient-shadow">

Ou você cria uma requisição Ajax via javascript e no OnSucess vc troca a imagem.
Answer: Isso talvez seja cache do navegador, ou do servidor principalmente se você estiver utilizando um CDN.
Experimente colocar uma url com parâmetros para ver se não resolve.
Exemplo: /image/arquivo.jpg?v=2
Comment: pior que não, eu vi pelo console que o caminho ainda é o da imagem antiga
Comment: Quando você obtém a imagem pelo url direto no Browser ela é carregada corretamente?
Comment: Experimente colocar um outro valor, e verifique pelo inspect do browser na página se esse novo valor é atribuido.
Comment: sim consigo pegar a imagem pelo browser
Comment: alterei o valor no javascript não funcionou, mesmo retirando aparte do php
Answer: No head da página onde estará o javascript

No contexto do HTML / Quem mostra a imagem

No contexto do Javascript / Quem pede a imagem

Na parte onde entra o PerfilUsuarioController.php, é onde fiz o teste aqui em casa, mas para funcionar para você, Verifique no seu projeto, qual é o caminho para acessoar a imagem.
Exemplo genérico PHP / Quem fornece a imagem
class PerfilUsuarioController {

    public function verificarRequest() {
        $request = $_GET["Request"];
        switch ($request) {
            case "GetImgPerf":
                $this->getImgPerfil();
                break;

            default:
                break;
        }
    }

    public function getImgPerfil() {
        // Codigo de busca do usua ou qualquer outra verificação
        print $usuario_pesquisado->getImg();
    }

}

$perf = new PerfilUsuarioController();
$perf->verificarRequest();

Como trocar uma imagem pelo Javascript


How do water-temperature, swim distance and skill influence the choice of using a wet suit for the swim-stretch in a triathlon competition?

Question: Water Temperature: I'm good with cold, but I am not an ice-swimmer.
Frequency/Distance: I swim an hour weekly (tri-club), with two hours additionally every 2-3 weeks, but I have yet to swim more than 200m without pushing off a wall.
Skill: I have been swimming for a few months. Through training, I have been able to manage a small constant glide at an easy pace.
Would a wet suit provide added benefit to swimming in different temperatures of water in varying distances? Is my skill level a significant factor in considering which type of wet suit I should consider? How do water-temperature, swim distance and skill influence the choice of using a wet suit for the swim-stretch in a triathlon competition?
Comment: I asked in my club - but everyone there is quite competitive (I'm the taillight in my age group), and the answers I got all pointed at the competitive advantage of a wetsuit.
Answer: Differing suits might provide a benefit, but I think that would be offset by your overall skill level.
Older swimsuits and skins increased the amount of drag on the body, which is a bad thing for competitive swimming.  I noticed a big difference in drag between the speedos I wore during Masters swimming versus the light skin I wore when scuba diving.  The rule then was less is more as your own skin presented less drag.  << Insert obligatory "yes, I dated myself there" comment >>
Newer swimsuits / skins can present less drag than your own skin does since the material is a tighter weave.  Case in point, many Olympic swimmers are now wearing full swim skins.  I believe the balance now is between economics versus performance gain.
I think I would purchase suits based upon the temperature of the water you expect to be competing in.  If it's a lake and you know it will be cold, having a little heavier suit will keep you warmer so you can function better.  Likewise, if it will be more reasonable temperatures then I would go with a lighter suit.  The focus is really upon staying warm enough that you can keep swimming.
I don't compete in triathlons, but I expect you wear the same base layer for all 3 events, so keep the other 2 events in mind when picking your swimming gear.
Finally, I would recommend just focusing on improving your overall swimming skill versus worrying about the minimal benefit that you may receive from aerodynamics.  After you get to the point where you're knocking out a few miles of swimming per practice then you'll be at a point to consider differing suit types.
Comment: The water temperature + time spent in water really makes the difference I guess. At my last triathlon there were some people who didn' wear neoprene - I really felt sorry for them, bcs, 17,5°C water is cold...
Comment: @RafaelCichocki I scuba dive in 3mm shorty when the water is warmer than 16°C hahahahaha - Here in the Cape Town the water ranges from 6°C to 20°C. All fun and games :-)
Answer: Wet suits will make you more buoyant which for a swimmer is not a good thing.
Can also increase drag, there are better materials that give less drag or even improve ability to glide in water. And may also offer some thermal protection.
I was workign as a PM for a engineering company that developed measuring equipment that was used by Sport Science Institute, under Prof Tim Noakes, to measure various thigns when Lewis Pugh did his swims in Arctic Oceans.
And he was able to train his body to swim in almsot freezing water without a wet suit :-)
http://lewispugh.com/


In phoenix, how do upsert from select with group by and put the values of one column into an array column?

Question: I have two tables, one which is defined as:
CREATE TABLE DESTINATION_TABLE (
  EFFECTIVE_DATE DATE NOT NULL,
  UID UNSIGNED_LONG NOT NULL,
  SOURCES VARCHAR[],
  CONSTRAINT PK_DT PRIMARY KEY (EFFECTIVE_DATE,UID)
);

I want to upsert into this from another table with something like this (pseudo code):
UPSERT INTO DESTINATION_TABLE
SELECT
  EFFECTIVE_DATE,
  NEXT VALUE FOR CIBC_COPY.AUM_AGGREGATES_SEQ AS "UID",
  (SELECT DISTINCT ACCOUNT_ID) AS SOURCES
FROM SOURCE_TABLE
GROUP BY EFFECTIVE_DATE;

Is something like this possible in phoenix?
Answer: You can do an upsert-select as specified in the phoenix documentation.
https://phoenix.apache.org/language/index.html#upsert_select

UPSERT INTO test.targetTable(col1, col2) SELECT col3, col4 FROM test.sourceTable WHERE col5 < 100
  UPSERT INTO foo SELECT * FROM bar;

This can also be used to update multiple rows in your table.In this case your source table and target table would be the same.
For eg you could do something like this

UPSERT INTO FOO(RK,AGE,CITY,NAME) SELECT RK,AGE,CITY,REGEX_REPLACE('MATT','MATT','CARTER') FROM FOO WHERE NAME='MATT';

This will update the name from MATT to CARTER in all rows where the persons name is MATT.


Determine (with justification) whether the series converges or diverges. If convergent find the sum.

Question: Consider:
$$\sum_{k = 1}^{\infty} (\frac{(\arcsin(0.5))^k+2^{-k})}{2})$$
This is what I tried:
I know that by a theorem if $$\sum_{k = 1}^{\infty} a_n$$ and $$\sum_{k = 1}^{\infty} b_n$$ are convergent series, and C is a constant then $$\sum_{k = 1}^{\infty} (a_n+b_n)$$ will be equal to $$\sum_{k = 1}^{\infty} a_n+ \sum_{k = 1}^{\infty} b_n$$
So what I'm thinking of doing is first splitting up the series into two:
$$\sum_{k = 1}^{\infty} (\frac{(arcsin(0.5))^k)}{2}) + \sum_{k = 1}^{\infty} (\frac{2^{-k}}{2})$$
Then I could take the limit of my b(subn) and show it is going to infinity, thus, by the theorem the whole thing must be going towards infinity. But, Im not sure if I'm missing something big because I do not think the arcsin would be in the problem for no reason.
EDIT: Actually if I take the limit off my b(subn) it would go to 0. So then I would need to take the limit of the first one as well...
Comment: Use braces, `2^{-k}` -> $2^{-k}$. And `a_n` for $a_n$, plus `\arcsin` for $\arcsin$.
Comment: For the problem: You probably have learned about geometric series.
Comment: Yes of course, but this does not seem like one at all. Can I tell simply because it is being raised to k?
Comment: You have a constant factor, and something (also constant) raised to the $k$-th power. That's a geometric series.
Comment: Two geometric series added.
Comment: So my constant factor would be 1/2 then? And then I would be able to pull that in front of the series to get something like: $$1/2\sum_{k = 1}^{\infty} ({(\arcsin(0.5))^k+2^{-k})})$$
Comment: Now I have this: $$1/2\sum_{k = 1}^{\infty} {\arcsin(0.5)^k} + 1/2\sum_{k = 1}^{\infty} {2^{-k}}$$
Comment: Im not sure if this would be ok to do next, since they are both convergent as k goes to infinity, could I take a limit of both and show that they both converge to 0, therefore my answer would be 0?
Comment: Wait I should take one r = arcsin(0.5) and another as r = 2 and then go from there to get the answer!
Answer:
Split the series into two different series

$$\sum_{k = 1}^{\infty} (\frac{(\arcsin(0.5))^k)}{2}) + \sum_{k = 1}^{\infty} (\frac{2^{-k}}{2})$$

Pull out 1/2 from both

$$1/2\sum_{k = 1}^{\infty} {\arcsin(0.5)^k} + 1/2\sum_{k = 1}^{\infty} {2^{-k}}$$

Notice it is now a geometric series so for $a_n$ r = $\arcsin(0.5)$ and for $b_n$ r = 2
Divide both answers in half and both r's will be less than one, so the series converges.


Prove that the limit does not exist: $\lim_{(x,y)\to(1,3)}\frac{|\sin(3x-y)|}{\sqrt{2(x-1)^2+5(y-3)^4}}$ (Without L'Hopital's)

Question: It seems that the function is underfined at $(1,3)$, so when I try to directly plug in $(1,3)$ via limit laws, I get an undetermined term $\frac{0}{0}$. So I tried instead to consider individual paths in the domain leading towards $(1,3)$, i.e.,
Along the x-axis: fixing $y=0$, $$f(x,0)=\frac{|\sin(3x)|}{\sqrt{2(x-1)^2+5(y-3)^4}}$$
However, I don't see where to go from there (if this is even the right approach), and try to show that two different paths that I pick result in differing limits.
For these type of questions in general, am I supposed to simply "try" a bunch of paths towards my limit point $(a,b)$ and simply "hope" that two paths will give different limits, or can we do better with a faster method?
Comment: You should try along $y=3, x=1$
Comment: You can try the horizontal case $(x,3)$ and the vertical case $(1, y)$ and hope the results are different. A stronger method is to take $x = 1 + \epsilon \cos(\phi)$ and $y = 3 + \epsilon \sin(\phi)$. Substitute this and check whether the result depends on $\phi$.
Comment: First reduce to $(u,v)\to(0,0)$ by letting $x=1+u,y=3+v.$ Then, the first paths to try are the linear ones, $v=ku.$ If your limit depends on $k,$ you have won. Else, try more "ad hoc" paths.
Comment: 1) You have not replaced $y$ with zero under the radical in denominator. 2) You will not approach point $(1,3)$ by walking along the $X$ axis only $(y=0)$.
Comment: I think I finally managed to get it using @AnneBauval 's method (or at least what I think you meant). Continuing with what I had above, I get $$\lim_{u\to 0} \left[ \frac{|\sin((3-m)u)|}{|u|}\cdot \frac{1}{\sqrt{2+5m^4u^2}}\right ]$$. Then by limit laws $$\lim{u\to 0} \left[ \frac{|\sin((3-m)u)|}{|u|}\right ] \cdot \lim{u\to 0} \left [ \frac{1}{\sqrt{2+5m^4u^2}}\right ]\implies |3-m|\cdot \frac{1}{\sqrt{2}},$$ and since $v=mu$ was an arbitrary linear path through $(0,0)$, we can clearly choose two different $m$ that give different limits. Can someone please confirm? This is quite new to me.
Comment: Ok, I tried the general linear path approach, but still cannot get it to work after several attempts:

Let x=1+u and y=3+u, so u=x-1 and v=y-3
then $$\lim{(u,v)\to (0,0)}\frac{|\sin(3u-v)|}{\sqrt{2u^2+5v^4}}$$
now consider the limit along a generic linear path $v=mu, ; m\in\mathbb{R}$
so we have:
$f(u,mu)=\frac{|\sin(3u-mu)|}{\sqrt{2u^2+5(mu)^4}}=\frac{|\sin(u(3-m))|}{u \sqrt{2+5m^4u^2}}$.
I planned on choosing different values of m to find two that contradict, but then I realised that I am still going to get an indeterminate form no matter what m I choose: 0/0
Answer: Consider the paths $y=mx+3-m$ for $m\in\Bbb R^+$ passing through the point $(1,3)$. Along these paths, the given limit becomes
$$\lim_{(x,y)\to(1,3)}\frac{|\sin(3x-y)|}{\sqrt{2(x-1)^2+5(y-3)^4}}=\lim_{x\to 1}\left|\frac{\sin((m-3)(x-1))|}{x-1}\right|\frac1{\sqrt{2+5m^4(x-1)^2}}$$
which is equal to $\frac{|m-3|}{\sqrt2}.$ It depends on $m$. So, there is no limit. Note that the trigonometric limit is well-known and it can be calculated without L'Hopital's rule.
Answer: First reduce to $(u,v)→(0,0)$
by letting $x=1+u,y=3+v.$
Then, the first paths to try are the linear ones, $v=mu.$
If your limit depends on $m,$
you have won. Else, try more "ad hoc" paths.
Your last comment confirms that you completely understood: as $u\to0,$
$$\begin{align}\frac{|\sin(3x-y)|}{\sqrt{2(x-1)^2+5(y-3)^4}}&=\frac{|\sin(3u-v)|}{\sqrt{2u^2+5v^4}}\\&=\frac{|\sin((3-m)u)|}{\sqrt{2u^2+5m^2u^4}}\\&\sim\frac{|3-m||u|}{|u|\sqrt{2+5m^2u^2}}\\&\to\frac{|3-m|}{\sqrt2}\end{align}$$
which depends on $m,$ thereby proving that $\lim_{(x,y)\to(1,3)}\frac{|\sin(3x-y)|}{\sqrt{2(x-1)^2+5(y-3)^4}}$ does not exist.
You might also notice that the limit along the line $u=0$ (as $v\to0$) is $+\infty.$


Leitura e escrita de arquivo Laravel

Question: Estou tentando ler um arquivo que vem de um formulário. Quando envio ele para o Controller, tenho que ler o arquivo e procurar uma linha, se ela existir, adicionar uma linha logo abaixo.
Dúvidas:
1- Consigo localizar no arquivo a frase, mas não estou conseguindo adicionar uma linha logo abaixo.
public function adiciona(Request $request){
       /*
        * O campo do form com o arquivo tinha o atributo name="file".
        */
        $file = $request->file('file');

$searchthis = "|C190|000|6102|12,00|36702,99|36702,99|4404,36|0,00|0,00|0,00|0,00||";
$matches = array();

$handle = fopen($file, "r");

if ($handle) {
      while (!feof($handle)) {
          $buffer = fgets($handle);
          if (strpos($buffer, $searchthis) !== FALSE) {
              //$matches[] = $buffer;

          }
      }
  fclose($handle);
}

//mostra os resultados:
print_r($matches);

        // Faça qualquer coisa com o arquivo enviado...
}

Comment: Já tentou pular a linha com PHP_EOL?
Comment: já consegui pegar a linha que queria, o que falta é comparar essas duas strings, para ver se existe no arquivo
Answer: já consegui pegar a linha que queria, o que falta é comparar essas duas strings, para ver se existe no arquivo
public function adiciona(Request $request){

$file = $request->file('file');
$busca ="*|C100|1|0|FOR000002301|55|00|001|48950|50190410761127000187550010000489501000489504|23042019|23042019|36702,99|1|0,00|0,00|36702,99|1|0,00|0,00|0,00|36702,99|4404,36|0,00|0,00|0,00|0,00|0,00|0,00|0,00|";
$arquivo = file($file);

// armazena o que contem a linha 11
$linha_trocada = $arquivo[2561];
$linha_compara = $arquivo[2559];
//dd($linha_compara);
var_dump($linha_compara);
if($linha_compara==$busca){
    dd("aaaaaaaaaaaaaaaaaaaaaaaa");
}
        //print_r($conteudoLinha);

}

Leitura e escrita de arquivo Laravel


Modal Chord Families

Question: Lately I came here with a question about modal II-V patterns and my answers were varied. I'm very confused about modal chord families and I can't find a single book or page on the internet anywhere. I'm trying to keep this short, if you have any questions just comment.
Some sort of chart would be incredibly helpful. For example, the ii of Phrygian acts like a dominant chord. And etc for all the other modes. I'm reading a Berklee college book that states chords built on the first, third, and sixth degree tend to be in the tonic family. Also, chords that contain the fourth of a scale tend to be sub-dominant. I was told The ii of Phrygian acts like a dominant chord because of the way it moves into the tonic, which sounds correct. But this chord contains the fourth of the scale so shouldnt it be sub-dominant? It states that it's the same for evey scale and i even copied the chart from the library. Im starting to work on it myself but any help would be appreciated for me to check over my work. Here's the page to my question if anyone is curious about the responses I got: Modal II-V Patterns
Comment: Are you asking us if we know of any charts?
Comment: Well, yes. But if there are none available, how do you find them on your own? Of course you can use your ear but I'm just worried about my ear being a bit different from others. There was obviously some difference with the two people in that link I posted.
Answer: In addition to the answers given in the your last thread I would suggest using an aug sixth chord to resolve to Phrygian tonic at some point. This will have the leading tone and have an overwhelming tendency to resolve to root position tonic but the resolution will feel rather unstable into a minor chord since the ear in the west will expect the i to become I or I7. Both of those would be rightfully notated as a V/iv. Therefore using this make for easy modulation to the relative aeolian off of the subdominant to your Phrygian tonal center.

Modal Chord Families


Como fazer para copiar o valor do textbox expecifico do UserFom aberto?

Question: Tem um jeito mais fácil que escrever
x = UserForm1.textbox2.value  ?
Essa instrução significa: Copie o valor da caixa de texto1 do UserForm1.
Eu queria substituir a declaração "UserForm1" por algo que signifique "UserForm aberto".
ou seja: copiar o valor da caixa de texto 1 do "UserForm aberto".
Comment: Caso seja em vb6 procure expor uma `Property Get` para consumir o valor do seu controle essa seria uma forma mais elegante. Outro ponto crie instancias dos formulários isso reduzirá o número de de falhas em sua aplicação, pois acessando diretamente o formulário não será descarregado.
Comment: Se você omitir o Userform o VBA já vai utilizar o Formulário Ativo, portanto com `textbox2.value` ele já realiza no texbox2 do userform. Já se quiser no textbox ativo você pode utilizar os módulos de Classe
Answer: Pra pegar qualquer coisa de uma form que está aberta no momento, basta usar o "me":
a = me.textBox.value

Answer:     For i = 0 To Forms.Count - 1
    If Forms(i).ZOrder = 0 Then
        Forms(i).TextBox1.text
    End If
    Next

Será que te ajuda?


Please help finding positive integers less than $1000$ which satisfy the constraint: $x=7k , x=4l+2 , x=3m+1$

Question: Please help finding positive integers less than $1000$ which satisfy the constraint: $x=7k , x=4l+2 , x=3m+1$
Comment: try the chinese remainder theorem.
Comment: i want a good solution not only a number for this question
Comment: what is it? than you
Comment: Hey I have edited the question. Please check once if it still looks the same...
Comment: yes, that is your kind. thank you so much
Answer: You have $x\equiv 0\bmod 7, 2\bmod 4, 1 \bmod 3$.
By the Chinese Remainder Theorem there is a unique solution modulo $7 \times 4 \times 3=84$. Note that this works because $7, 4 , 3$ are mutually coprime.
We can immediately see that there will be $\lfloor \frac {999}{84}\rfloor= 11$ or $\lceil \frac {999}{84}\rceil=12$ such integers, and this will depend on whether the lowest positive solution is greater than $999-11\times 84 = 75$.
Now we can solve this in various ways, including the full machinery of CRT for the general case. Here we know we have a multiple of $7$ and from the second equation we know it must be even, hence a multiple of $14$.
Since $14 \equiv 2 \bmod 4$ we know that we need $14+28k$ to get the right answer $\bmod 4$. Testing the options give $70$ as the least positive solution.
I've left some gaps for you to fill in, since this will help you understand the way of working so that you can solve other similar problems.
Answer: We want to find integers $x$ that satisfy$$\begin{align}x&=7k\\x&=4l+2\\x&=3m+1\end{align}$$
Substitute $x=7k$ into the second equation and obtain
$$7k = 4l+2\\\implies 8k-k=4l+2\\\implies -k=4\heartsuit+2\\\implies k = 4n+2 $$
So we have $k=4n+2$, where $n$ is an integer. Then
$$x=7(4n+2) = 28n+14$$
For $x$ to satisfy the last equation, we must have
$$28n+14=3m+1\\\implies n+27n+14=3m+1\\\implies n = 3\spadesuit -1\\\implies n = 3s+2$$
This yields
$$x=28(3s+2)+14 = 84s+70$$
All in all, you want to find the integers $x=84s+70$ such that
$$\color{blue}{0\lt 84s+70\lt 1000}$$
Answer: I assume you are not familiar with modular arithmetic. (If you want to dig deeper, you should try to look into that).
So, it goes like this:
Let's set $x_1 = 7k$ for some $k$. The first constraint is fulfilled. We want to find $k$, such that the second constraint is also fulfilled. You'll find, that $k=2$ works, because $x_1 = 7\cdot 2 = 4\cdot 3 + 2$. Let's set $x_2 = 7\cdot 2 + 7\cdot 4\cdot n = 14 + 28n$ for some $n$. $x_2$ fulfills the first and second constraint. If you set $n = 2$, then $x_2 = 14+28\cdot 2 = 3\cdot 23 + 1$, hence $14+28\cdot 2 = 70$ fulfills all three constraints, and so do $70 + 3\cdot 4\cdot 7\cdot y = 70 + 84\cdot y$ for all $y$. Now choose $y=1,2,\dots$ to get all solutions.


Crond offset five minute schedule

Question: Is it possible to offset a cron script set to run every 5 minutes?
I have two scripts, script 1 collects some data from one database and inserts it into another, script 2 pulls out this data and a lot of other data and creates some pretty reports from it. Both scripts need to run every 5 minutes. I want to offset script 2 by one minute so that it can create a report from the new data. E.G. I want script one to run at :00, :05, :10, :15 [...] and script two to run at :01, :06, :11, :16 [...] every hour. The scripts are not dependent on each other, and script 2 must run regardless of whether script one was successful or not. But it would be useful if the reports could have hte latest data. Is this possible with cron?
Post;
I have thought about using both commands in a shell script so they run immediately after each other but this wouldn't work, sometimes script 1 can get hung up on waiting for external APIs etc. so might take up to 15 mins to run, but script 2 must run every 5 minutes so doing it this way would stop/delay the execution of script 2. If I could set this in Cron it would mean script 2 would run regardless of what script 1 was doing
Answer: The minute entry field for crontab accepts an "increments of" operator that is kind of confusing because it looks like it should be a mathematical "divide by" operator but isn't. You will most often see it used something like the following. Note that this does not find numbers that are divisible by five but rather takes every fifth item from a set:
 */5 * * * * command

This tells cron to match every fifth item (/5) from the set of minutes 0-59 (*) but you can change the set like this:
 1-59/5 * * * * command

This would take every fifth item from the set 1-59, running your command at minutes 6, 11, 16,  etc.
If you need more fine grained offsets than one minute, you can hack it using the sleep command as part of your crontab like this:
 */5 * * * * sleep 15 && command

This would run your job every five minutes, but the command would not actually start until 15 seconds after the minute. For short running jobs where being a few seconds after something else makes all the difference but you don't want to be a full minute late, this is a simple enough hack.
Comment: This is a better answer than the accepted one.  Setting the offset via the range is much cleaner than sleeping.
Answer: You can run scripts whenever you want using cron.  If you want to run script 1 every 5 minutes, you might start like this:
*/5 * * * * /path/to/script1

But this is really just shorthand for:
0,5,10,15,20,25,30,35,40,45,50,55 * * * * /path/to/script1

If you want to run script 2 one minute after script 1, you can do this:
1,6,11,16,21,26,31,36,41,46,51,56 * * * * /path/to/script2

You could also do this:
*/5 * * * * /path/to/script1
*/5 * * * * /path/to/script2

And then at the start of script 2, sleep for one minute:
sleep 60

Comment: Putting the sleep in the script itself is an ugly hack that makes running the script by hand from the prompt painful. There is a [less ugly way to hack that](http://serverfault.com/a/429397/40193) by making the sleep part of the crontab entry, but an even more elegant way is to just offset the jobs using the correct crontab notation, which your answer doesn't touch on.
Answer: You can indicate a time offset with the + symbol.  For example, to run at :01, :06, :11, :16 [...], create a task such as
*/5+1 * * * * command

Comment: This doesn't seem to work in some versions of cron
Comment: Which version of cron are you using that supports this syntax? Cronie doesn't seem to support it.
Comment: I have Cronie on CentOS7, so ty I won't try this solution first.
Answer: This worked for me:
1/5 * ? * * *

Where 1 is the offset minutes. So if you want to offset three minutes:
3/5 * ? * * *

I have this working in AWS schedule settings
Comment: Unfortunately it doesn't work with Ubuntu 21.10 `bad minute errors in crontab file, can't install.`
Answer: This is an XY problem.
Offsetting cron from whole hour intervals, or common fractions thereof, can be generally valuable to reduce coinciding processes, but this question explicitly states the offset is to resolve a dependency.
Though we're told script 2 must run regardless of whether script 1 completes, it should certainly not try whilst script 1 is in the middle of updating the shared dataset.
Using time alone to enforce a sequence creates an unnecessary delay between the two at best, and a race condition at worst.
It's better to put them into the same cron job line to create the chronological dependency:
*/5 * * * * /path/to/script1; /path/to/script2

The semicolon separates the commands but ensures all will run regardless of the previous exit status.
In cases where the second command should run only if the first command is successful, change it to:
*/5 * * * * /path/to/script1 && /path/to/script2

I believe this is a case of the latter, where the report will not change if it's generated from old data, or will be plain wrong if generated from incomplete data, so why create another until a successful run of the first script?
Either resend a cached copy of the previous report or none at all.
If the first script has any chance of running longer than the cron interval, it should employ basic locking (e.g. with flock) to ensure there won't be concurrent runs making competing requests to the same places.

Crond offset five minute schedule


Change lim from -k to k

Question: \begin{align*}
f\,''(x)&=\lim_{h\to 0}\frac{f\,'(x)-f\,'(x-h)}h\\
&=\lim_{-k\to0}\frac{f\,'(x)-f\,'(x-(-k))}{-k}\\
&=\lim_{k\to 0}\frac{f\,'(x-(-k))-f(x)}k\\
&=\lim_{k\to 0}\frac{f\,'(x+k)-f(x)}k\;,
\end{align*}
Can someone explain why he can changed from -k to k?
Comment: multiply both sides by $-1$
Answer: Replacing $k$ by $-k$ is legitimate since this change results in switching left-hand limits with right-hand limits, that is, $-k\to 0^+$ is equivalent to $k\to 0^-$. We are interested in a two-sided limit, so the result doesn't change.

Change lim from -k to k


proof using mathematical induction the largest anti-symmetric binary relation

Question: Using mathematical induction prove that, for a finite set $S$, the largest anti-symmetric binary relation $\rho\subseteq S\times S$ is such that:
$$|\rho| = \frac{|S|(|S|+1)}{2}$$
I tried solving this problem but I couldn't reach an answer. I hope someone could help.
Comment: Thanks for your post. For future reference, please use the link to format your questions: https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference
Comment: Are you required to use induction? The result can be proved fairly easily without it.
Comment: yes I have to @BrianM.Scott
Comment: @mariamessam: That's too bad (and in my opinion an example of inferior teaching), since (a) it's an artificial limitation, and (b) another approach is actually a little more informative. Okay; **Agniv**'s answer below is a bit hard to follow, but the first paragraph is pretty much what you're supposed to do.
Comment: Thank you @BrianM.Scott
Comment: @ReemTantawy: You're welcome.
Answer: For one element set, size of such relation is 1, namely the only reflexive element so the result holds true.
Suppose for n element set, size of such relation is A =n(n+1)/2
Now for n+1 element set, size of such relation would be A +{1 element for (p,p) if p is the n+1 th element } + { n elements in the form (i, p) where i are previous n elements}. Note that (p,i) is not a part of the relation if (p,i) is, as the relationship is anti symmetric. So adding them all we get (n+1)((n+1)+1)/2.
Hence proved for all n.
Using combinatorics, the size of the relation will be {n for all the reflective tuples} + {half of  n choose 2 for all the other pairs counting only once occurance of (a,b) and (b,a) where a is not equal to b as the relation is anti symmetric.}


Run an ephemeral Spring Boot app out of main class or a startup listener?

Question: Java 8 and Spring Boot 2.x here. I've used Spring Boot for the last several years to write web apps and RESTful web services alike, and I absolutely love it.
I now have a need to write a bunch of short-lived (non-service/daemon) apps that need to start up, do some work, and shut down. Exact length of runtime will vary depending on workload but never more than ~10 minutes. Although they do not involve hosting any server-side HTTP code (REST endpoints, controllers, etc.) like an traditional web app/service does, they do still need:

Dependency injection
YAML-based external configuration
Auditing
Metrics
Lots of other stuff that comes with stock Spring Boot

So I don't see any reason why I can't use Spring Boot as the underlying framework even though these apps will not be standing up any @Controllers or @RestControllers.
With Spring Boot, if you don't specify any controllers, it simply starts up and shuts down, because there's nothing to execute. So the question becomes: where do I put my main code that needs to execute? And the two logical places I've thought of are:

Right inside the main @SpringBootApplication-annotated class where the main method is also defined; or, possibly...
In an ApplicationListener<ContextStartedEvent> implementation

I'm wondering if there is a right/wrong approach here. I guess I just don't know enough about the Spring/Boot lifecycle (and the complicated order of events that things execute in) to know which is correct.
For instance, what if it takes Spring Boot a certain amount of time to fire up properly, but I put my code all inside of the main @SpringBootApplication-annotated class and it executes in a few seconds, and prompts Spring to shut down before its even properly finished starting up fully? So I guess the question comes down to this, does one use:
@SpringBootApplication
public class MyApp {
    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
        new MyApp().run();
    }

    private void run() {
        // put all the app code in here?
    }
}

Or, something like:
@Component
public class StartupListener implements ApplicationListener<ContextStartedEvent> {
    @Override
    public void onApplicationEvent(ContextStartedEvent event) {
        // put all the app code in here?
    }
}

Considerations of either approach? Does Spring Boot offer anything better than either of these solutions, perhaps, something specifically intended for short-lived/ephemeral applications?
Comment: What you are doingin your main won't work and is actually useless. You are creating a spring boot application, ignore it an new an instance of a class. Create a class that implements `CommandLineRunner` or `ApplicationRunner` which will exeute right after everything has been setup. Implement that to exeecute what you want to do. After that finishes (and it doesn't include the `spring-boot-starter-web`) it will shutdown afterwards.
Comment: I've normally use ContextStartedEvent, since it is clearer, but you can literally just make a bean, and that will also run at startup. I'd avoid your first suggestion.
Comment: Thanks @M.Deinum, I think you have a typo though ("exeecute" instead of "execute").
Answer: Just regurgitating M. Deinum's answer above so that I can mark this as answered.
You can use either CommandLineRunner or ApplicationRunner.


Why don't GCP, AWS or Azure support IGMP multicast/broadcast?

Question: It's well known that GCP/AWS/Azure do not support IGMP multicast or broadcast. Some state it's because of security concerns, but don't mention what those concerns are.
Is there a reason why these cloud providers do not support such long-standing, well-specified routing paradigms?
Comment: @womble are you speculating this? Or is that a definitive answer? If there is a technical reason, there will be a definitive answer. This is not an unfocused or subjective question. Your assumption that it's an arbitrary reason is not a reason to close - the question is perfectly answerable. We can take this to Meta for a vote if you'd like... I don't appreciate questions being unilaterally judged in the first five minutes of it being asked. That's not how SE should work.
Comment: Each provider likely has their own reasons, and it is nearly impossible to know what that reason is unless the provider makes a statement on it, which they're unlikely to do.
Answer: I believe that is for preventing multicast flood, if Cloud virtual network support IGMP multicast, one physical interface of switch or router could be receive ton of package from several multicast, it is same as multicast flood, their physical switches and routers will easily overload.


Can I put an anchor's href value in its contents automatically, without JS?

Question: For the purpose of rapid coding and reducing tedium, I want to know if it's possible to auto-generate the contents of an HTML anchor as its href value without using JavaScript. The application I'll be using this in has pages large enough for a JavaScript solution to introduce significant lag.
Example:

Is this possible? Is it W3C-compliant? Why or why not?
Answer: Yes, to an extent. You can use the CSS2 content property and its attr value to get the value of an anchor's href attribute. For instance:

http://jsfiddle.net/aA4Em/2/
This is not guaranteed to work cross-browser! For instance, in the current version of WebKit (Safari, Chrome, Yandex, Rockmelt, many mobile browsers, etc.), the link text is rendered, but it cannot be clicked. That said, it works as you might expect in the currently most-used versions of Presto (Opera, soon to be replaced by WebKit), Trident (Internet Explorer), and Gecko (Firefox, Waterfox, etc.).
Mind you I don't know if this is W3C-compliant or not (I don't even know if an empty anchor is W3C-compliant), so my answer is definitely to use this solution at your own risk.
Update

As of this edit (2013-04-30), Google's Chromium platform's flavor of Webkit (Chrome, Yandex, Rockmelt, many mobile browsers, etc.) and Blink (Currently just Chrome Canary) now allows users to click anchor pseudo-elements. Safari, which still runs on Apple's flavor of WebKit, still does not allow this.


Is there any kind of known pattern to $\sqrt 2$ in base 2?

Question: Is there any kind of known pattern to $\sqrt 2$ in base 2?
Is there any classification categories for decimal digits of numbers that for example would put $\sqrt 2, \sqrt 3 \cdots \sqrt n$ into separate category than $\sqrt[3] 2, \sqrt[3] 3 \cdots \sqrt[3] n$
Or given a decimal expansion with arbitrary precision, or definition of digit in the nth place (not necessarily decimal expansion) to get a probability of which class of numbers the number is likely to be? e.g. transcedental or algebraic of degree k?
Comment: @barakmanos : The question did not ask for a "repeating pattern", e.g. liouville's number has a simple pattern and it is transcendental.
Comment: I believe it remains unknown whether $\sqrt {2} $ is "normal" in any base i.e. for each natural number $n$ having uniform distribution of all $n$-tuples of digits in that base.
Comment: The wikipedia page is pretty interesting, and points out that it is unknown if $\sqrt 2$ is normal. In fact, we have never proven that a number is normal, except for numbers which were constructed to be normal. https://en.wikipedia.org/wiki/Normal_number
Comment: See this :http://community.wolfram.com/web/community/groups/-/m/t/1063480
Comment: If there was one on base $2$, then there would be one on base $10$ as well, making $\sqrt2$ rational.
Comment: @Arjang The answer depends sensitively on what you will accept as a 'pattern', then.
Comment: @DanielLittlewood : what are some possible examples that could be considered a pattern? At this stage looking for any in's into what subject in mathematics deals with anything related to this. Simon mentioned number being "normal", I think that is a start.
Answer: One expression for the square root of 2 is given by $\sqrt{2} = \sum_{k=0}^{\infty} (2k+1) \binom{2k}{k}  2^{-3k -1} $ which is rather useful for computing the digits exactly. It also means that any pattern in the binary digits of $\sqrt{2}$ should be somewhat related to the the digits of the central binomial coefficients. There's probably a combinatorial interpretation of this.
Incidentally, $(2k+1) \binom{2k}{k}$ is asymptotic to $\frac{2^{2k + 1}}{\sqrt{\pi}}$ so the number of terms affecting the kth digit is linear in k. Also, the greatest power of 2 dividing the central binomial coefficient is known as Gould's sequence, i,e, $\binom{2k}{k} = 2^{2^{h(k)}}$ where $h(k)$ is the hamming weight of k.
Answer: there is a method to calculate decimal places of root2, probably that could help find a pattern with it. Although this is not a very obvious one, it probably could (very loosely) help to find a pattern.
The method works a bit like dividing, so you have to calculate the next decimal place, then the next.
It does not work on approximations by the way.
http://www.murderousmaths.co.uk/books/sqroot.htm
On this link you will see a few methods, but scroll down past the cyan shortcut box and you will see the one shown by Frank La Fontaine.
I'm sorry that I can't show an actual pattern, but hopefully this helps.


Inverse recursively tree menu on mysql

Question: I have a very simple recursive category tree table in my website
id
name
parent_id

Normally people wants to show the whole tree from the parents to their children
In my case I have the children ids and I need to do the inverse, create the tree from the children to their parents
Let's suppose that I have the following tree:
1 - Computer
 2 - Storage
  5 - HDD
  6 - SSD
 3 - Motherboard
  7 - AMD
  8 - Intel
 4 - Graphics Card
  9 - Nvidia
  10 - AMD

and I have the ID of the children categories 6 and 10
6 - SSD
10 - AMD

in one select I need to retrieve all the parents of these categories 6 and 10 to create a tree like this:
1 - Computer
 2 - Storage
  6 - SSD
 4 - Graphics Card
  10 - AMD

So, how should I do that?
Answer: I think this could help you: http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/
If you know the maximum number of sub-levels, for example 3, you could do something like this:
SELECT t1.id, t1.name, t2.id, t2.name, t3.id, t3.name
FROM table t1
INNER JOIN table t2
    ON t1.parent_id = t2.id
INNER JOIN table t3
    ON t2.parent_id = t3.id
WHERE t1.id IN (6, 10)

Inverse recursively tree menu on mysql


Ηοw important is to know classical music theory to study jazz theory?

Question: I was interesting in getting a little more involved with jazz theory. I know classical music theory and harmony up to a point.
Should I keep developing my classical music theory/harmony knowledge before I continue with jazz or is it not necessary?
PS: I'm not a total beginner; I have been studying music for some time now.
Answer: Coming from a similar perspective as you (likely with less classical music theory) I can only say go for the jazz now. There are a lot of overlapping areas, the foundation of scales and chords is obviously an area where a lot is shared.
There are jazz theory books; I've been using one called Jazzology, which contains a lot of stuff. It starts out with basic triads and scales though, so not much prior knowledge is needed. You should know staff notation, basic knowledge about how the modes of a scale works is a definite advantage.
Comment: Do they start from the scratch or do I need any knowledge before I pick up a book like that?
Comment: @Shevliaskovic: They start pretty much from the start with triads, basic scales and then continue onwards.
Comment: can you add it to your answer? It would be more complete
Comment: @Shevliaskovic: Done and done!
Answer: It rather depends where the 'point' is that you've got up to.As a sort of yardstick, ABRSM grade 5 theory is probably as far as you need to go with Classical theory, as harmony, scales, basic chords etc., are covered, plus a lot of stuff that only applies to classical playing - ornaments, writing for transposing instruments, alto clefs and so on won't be too relevant.
Stuff that will be, at this level, is - odd time sigs., writing in certain keys,intervals etc.Then there's always extended chords !At this level, you're probably better going off at a tangent and studying jazz theory, which will have started in the same frame of mind as the Classical anyway.
I'm guessing you're studying this with bass in mind, but whatever instrument, the theory will make far more sense when it becomes practice. Play with other jazzers, read the real and fake books.Get backing tracks: there are loads to Google, and get good at transcribing notes and chords from them.
Answer: As a general rule, knowing "classical theory" does not help you when it comes to playing jazz. to get started on jazz piano, first get a good foundation in harmony, then start learning jazz voicings and reharmonization methods:

Understanding and Implementing Harmony on the Piano.
Play Piano by Ear.
The Blues Scales: Essential Tools
The Harmonic Foundation for Jazz and Popular Music

Once you've made some progress on those, then the next steps are indispensable:

private instruction with a performing jazz musician in your area
playing with a jazz band

The goal is to learn the fundamentals and basics from the books, and then to learn best practices of how to really implement this from playing with others.
Comment: That's a totally different statement than "classical theory does not help you when it comes to playing jazz"...
Comment: Is that really true that classical theory does not help you? To understand e.g. the functions of chords should be a great help. Many (most?) of the greats had classical training.
Comment: The classical theory by itself does not get you to playing jazz.
Answer: Let me give an answer that is from a broader perspective (and supports Tim's response).
All western music that you hear, whether it is techno, jazz, or hip hop, is based off of "classical theory" (a.k.a western harmony).  Therefore, you will need to know the classical theory fundamentals.
However, those fundamentals will naturally be taught first before you start learning "jazz theory".  You can't understand the significance of the raised 7th of a chord without knowing what a triad is, for example.
So, you probably don't need to devote any time to "classical theory" (you don't need to be adept at counterpoint, for example), therefore go for theory books that come from a jazz perspective.


Como mensurar a quantidade de espaço necessária em disco para uma operação ALTER TABLE?

Question: Preciso fazer algumas alterações em uma das tabelas para adicionar novas colunas. O problema é que não consigo de forma alguma. Recebo o seguinte erro:

PG::DiskFull: ERROR:  could not extend file "base/1672994/5557167.4":
  No space left on device. HINT:  Check free disk space.

Bem, não há dúvida de que preciso aumentar o meu espaço em disco, já que nem mesmo uma operação VACUUM FULL deu certo, apresentando esse mesmo problema.
A query que tentei fazer é a seguinte:
ALTER TABLE messages ADD COLUMN readed BOOLEAN DEFAULT FALSE;
É um campo simples, e boolean não ocupa muito espaço. Mas lendo em outros fóruns, vi algo relacionado ao fato de que o PG precisa de mais espaço para fazer uma operação assim. Não sei ao certo como funciona, mas essa tabela que tento alterar tem mais de 6.700.000 linhas, e levando isso em consideração, talvez faça sentido o fato de o espaço atual não ser o suficiente para a operação.
Mas enfim. O que quero saber é: Existe uma forma de eu calcular em média quanto espaço adicional vou precisar comprar para que essa operação funcione? E como funciona essa questão do ALTER TABLE? Realmente precisa de muito mais espaço pra funcionar?
Comment: Eu entendo que como o PostgreSQL utiliza MVCC (Multiversion Concurrency Control) ele irá gerar uma cópia de toda a tabela, acrescentando nela o novo campo, e apenas ao final remover a tabela antiga. Talvez um pg_dumpall (em outro meio de armazenamento), modificar a definição da tabela no arquivo gerado, apagar o banco e recria-lo dom o psql possa ser uma solução.
Answer: É difícil dar uma resposta definitiva sobre isso e a tentativa e erro acaba sendo um método eficaz para descobrir até onde ir.
De fato é um pouco estranho precisar de tanto espaço porque a forma como está fazendo não deveria alterar toda a tabela. O PostgreSQL tem um mecanismo em que ele vai alterando as linhas conforme tem escrita nela. Enquanto não tem escrita, ela pega a linha sem a coluna e considera o valor default para a query de leitura. É bem inteligente. Mas por alguma razão isso parece não estar funcionando.
A ideia básica é ver o tamanho da tabela. Para listar as tabelas:
SELECT pg_database.datname, pg_database_size(pg_database.datname),
    pg_size_pretty(pg_database_size(pg_database.datname))
FROM pg_database ORDER BY pg_database_size DESC

Coloquei no GitHub para referência futura.
Pode ser que isso não seja suficiente já que pode haver alterações no índice também ou precisar de outras manipulações que só analisando o funcionamento interno do PostgreSQL para ter certeza.
Comment: Você mencionou que pode haver alterações no índice...
Nessa tabela em questão, há 15 índices. Eles são sobre campos INT, DATE, e TIMESTAMP. Todos eles são bTree. Isso influencia?
Comment: Eu acho até que não vai alterar, porque só faz sentido alterar o índice primário, que deve ser *clusterizado*, ou seja, é a própria tabela. Eu só coloquei porque pode ser que tenha algo que eu não sei e você tem a informação que pode ser mais que o tamanho da tabela. Tem que testar. Comece liberando o tamanho da tabela. Embora como eu disse, é estranho que precisa até isto.