How to prove that $\int_{[-\pi,\pi]}\log(\vert 1- \exp(it)\vert)\mathrm{d}\lambda(t)=0$?

Question: Let $r>1$ and $\displaystyle\int_{[-\pi,\pi]}\log(\vert 1- r\exp(it)\vert)\mathrm{d}\lambda(t)= 2\pi\log(r)$.
We want to prove that :
$\displaystyle \lim \limits_{r\to 1} \int_{[-\pi,\pi]}\log(\vert 1- r\exp(it)\vert)\mathrm{d}\lambda(t)=\int_{[-\pi,\pi]}\log(\vert 1- \exp(it)\vert)\mathrm{d}\lambda(t)$.
We want to apply the dominated convergence theorem. Let $(r_n)_{n\ge 0}$ a sequence of real numbers such that $\lim \limits_{n\to +\infty}r_n = \lim \limits_{r \to 1} r$.

For all $t \in [-\pi,\pi]$, the sequence of functions $t \mapsto \log(\vert 1- r_n\exp(it)\vert)$ is continuous. So the sequence of functions is in $L^1([-\pi,\pi])$.

$\lim \limits_{n\to +\infty} \log(\vert 1- r_n\exp(it)\vert)=\lim \limits_{r\to 1} \log(\vert 1- r\exp(it)\vert)=\log(\vert 1- \exp(it)\vert)$.

Note that the function $t\mapsto \log(\vert 1- \exp(it)\vert)$ is continuous on $[-\pi,\pi]- \{0\}$ and in a neighborhood of $t=0$ we have $\log(\sqrt{(2-2\cos(t)}))=o \ (\dfrac{1}{\sqrt t})$. So the function $t\mapsto \log(\vert 1- \exp(it)\vert)$ is in $L^1([-\pi,\pi])$.

For the hypothesis of domination I am stuck.

Thanks in advance !
Answer: Let $r_n \to 1$
You can assume that $r_n<2,\forall n \in \Bbb{N}$
$|1-r_ne^{it}|\leq 1+r_n<3$ almost everywhere
Thus $\log|...| \leq \log 3 \in L^1[-\pi,\pi]$
Comment: Thanks but I think it should be a $\vert \log(\vert .. \vert )\vert$ and the inequality is not verified for $t=0$.
Comment: @Maman its ok,because you can apply Dominated convergence if the equality is true almost everywhere.
Comment: Problem is still that $\log$ has not constant sign for $t \in [-\pi, \pi]$
Answer: The following observation is useful:
$$ \log |1 - re^{it}| \geq \log |1 - e^{it}| \qquad\text{for} \quad t \in \mathbb{R} \text{ and }r > 1 $$
Indeed,
$$ \frac{\partial}{\partial r} \log |1 - re^{it}|
= \frac{\partial}{\partial r} \operatorname{Re}\log(r - e^{-it})
= \operatorname{Re}\left(\frac{1}{r - e^{-it}}\right)
= \frac{r - \cos t}{|r - e^{-it}|^2} > 0, $$
and so, $r \mapsto \log |1 - re^{it}|$ is increasing for each given $t$.
Now, since $\log |1 - re^{it}|$ is squeezed between two integrable functions and converges pointwise to $\log|1 - e^{it}|$, we can apply the dominated convergence theorem to conclude.
Comment: Indeed really nice observation ! I tried something slight similar finally : I used the fact that for $z \in \mathbb{C}$, $\mathfrak{R}(z)\le \vert z \vert$. Then I want to prove that : $\dfrac{\vert 1- re^{it}\vert}{\vert 1 -e^{it} \vert}\ge 1$ for all $t\in[-\pi, \pi]\backslash \{0\}$ and $r>1$. Hence $\dfrac{\vert 1- re^{it}\vert}{\vert 1 -e^{it} \vert}\ge \mathfrak{R}\left(\dfrac{ 1- re^{it}}{1 -e^{it}}\right)=\dfrac{1+r}{2} \ge 1$.
Comment: @Maman, Your approach looks much simpler! Actually, I originally wanted to use the monotone convergence theorem, so that's why my solution contains a bit stronger claim than what is enough.


Why it is preferred to use GCM for push notifications?

Question: I know, it's so. But I don't understand, why?
Why not simply send queries to server periodically? Sure, it may discharge battery and increase internet traffic. I understand it. But how usage of Google Cloud Messaging can eliminate this problems?
I have found an answer. But it isn't pretty clear for me.
Can anyone give me a clear explanation?
Answer: Let's say you have 50 applications on your phone that do not use GCM. Each app developer decides it is appropriate to poll their respective backend once a minute.
Since these are all separate applications, each call will likely not happen at the same time as another api call. The biggest kill to battery is when the radio within an android device has to turn back on after being off to make an API call, so multiple calls happening with blocks of time in between drains battery faster (read this article on the radio state machine to better understand why this is https://developer.android.com/training/efficient-downloads/efficient-network-access.html)
In addition, each application will be hitting a separate endpoint. Each time you make an API call, you have to go through the connect process for a given server. With batched api requests or HTTP 2.0, multiple calls going to the same server can be optimized by not having to re-do a handshake or the connect process.
Now imagine, all 50 applications used GCM. GCM will poll an endpoint at some regular time interval on behalf of all 50 apps. Let's say GCM polls once a minute to a server that all the respective apps' backends send their notifications to to send to a device. You have reduced 50 different oddly timed API calls that are likely turning on and off the battery to one api call. You will use less data for polling. You do not incur the cost of the connect step of an HTTP call to 50 different servers. In addition, google is using the same polling already in place checking for OS updates, so there is no additional network overhead from using GCM (this info is based on old docs What technology does GCM (Google Cloud Messaging) use?)
Also, see this explanation straight from the Android website in an article entitled "Minimizing the Effects of Regular Updates" (http://developer.android.com/training/efficient-downloads/regular_updates.html):

Every time your app polls your server to check if an update is required, you activate the wireless radio, drawing power unnecessarily, for up to 20 seconds on a typical 3G connection.
Google Cloud Messaging for Android (GCM) is a lightweight mechanism used to transmit data from a server to a particular app instance. Using GCM, your server can notify your app running on a particular device that there is new data available for it.
Compared to polling, where your app must regularly ping the server to query for new data, this event-driven model allows your app to create a new connection only when it knows there is data to download.
The result is a reduction in unnecessary connections, and a reduced latency for updated data within your application.
GCM is implemented using a persistent TCP/IP connection. While it's possible to implement your own push service, it's best practice to use GCM. This minimizes the number of persistent connections and allows the platform to optimize bandwidth and minimize the associated impact on battery life.
Comment: Thanks for sharing of your experience! It is very helpful information for me.


Admin module for content managers

Question: I am building a drupal website for a customer (=content manager) of mine. Normaly I would just adjust the permissions for the content manager so he can change what he needs to. But it would be much simpeler if I could provide a menu with shortcuts of the actions he needs.
To keep everything clean I would like to use rubik and the admin menu.
Is there a way to hide all the "admin" links for the content manager and add some custom menu links my own ? So I can provide a "custom" content management system for his needs without all the drupal possibilities (which I only need).
Answer: Try the Quickbar module.

This is a simple administration toolbar. It allows you to take any menu and assign it to a role. This menu will be displayed at the top of your page as an administration toolbar.

Most of this module is taken from [the] Admin [m]odule version 1.x. It also uses some features from the Toolbar module.
Answer: The links to actions the user doesn't have access to won't appear if I'm not mistaken.
However, you might be better off using the toolbar instead of admin_menu and adding a couple links to management menu.
Try and login as that user, you will see a much less-cluttered toolbar because of permissions :)

Admin module for content managers


Why ItemCollection.Groups is collection of Objects and not CollectionViewGroups?

Question: I mean are there cases when its items are not CollectionViewGroup?
Answer: It would limit the use for ItemCollection.Groups in the future. Right now all elements might always be CollectionViewGroup and if you need to use the interface you can cast objects to an instance of CollectionViewGroup.
Comment: Wouldn't it be smarter to create an interface `ICollectionViewGroup` and make `ItemCollection.Groups` a `ReadOnlyObservableCollection`? This would reduce costs of boxing/unboxing...


How to add integer field to content type?

Question: I am trying to add  year field to content type. I selected integer as field type, then i see text field as widget. How can I set to 4 digits max and allows only numbers only?
Thanks,
D
Answer: You could use the Date Module
Then when you add a new field, select Date as your Field Type.
When you configure it use something like this
Answer: If I understand correctly, you want a field validator.  There is a module for Field Validation.
Here is a nice tutorial on number formats.
I'm curious why you are using Year as an integer type.  Did you try using the Date Field Module?
Comment: Yes, when you configure a Date field there are settings for the granularity. You can choose to only allow people to enter years.
Comment: I thought date module requires me to enter entire date but i just need to enter 4 digits here. Will the date module allow me to enter just 4 digits year?
Comment: As for date module, if you do not care about the year as a date (ie. use other date related functions like calculating duration, range, etc.) then you should not store as a date.  You can always display just a date year though.
Comment: Here is another module to specify number formats: https://www.drupal.org/project/formatted_number or you can create a custom formatter.


Texto não inserindo quebra de linha

Question: Dei uma pesquisada e não encontrei nenhum post sobre o problema que estou enfrentando.
Estou fazendo uma busca no banco de dados e escrevendo na tela o que encontro. Porém quando o texto é exibido ele não está inserindo quebra de linha, com isso o texto fica tudo em uma linha.
Abaixo coloco as imagens do problema e de como é feita a implementação (Um Trecho).

     <?php echo $results['descricao']; ?>

Answer: A não ser que o texto no banco esteja já marcado com HTML, você terá essa "tripa" na tela. Se você procura apresentar o texto na sua disposição original de espaçamento e linhas, ainda que não esteja marcado com HTML, envolva-o com a tag pre.
É bastante comum processar o texto do banco antes de exibi-lo. Por exemplo, pode carregar o texto num vetor, dividido em parágrafos. Depois imprima cada elemento desse vetor (um parágrafo) com o elemento HTML parágrafo:
$paragrafos = explode("\n\n", $texto);
foreach($paragrafos as $paragrafo) {
  echo '
' . $paragrafo . '
';
}

Dê uma olhadinha em explode e foreach.

Texto não inserindo quebra de linha


Read in JPEG, resize it and save it to disk

Question: What I want:
Resize an existing jpeg into a new, smaller one.
Example: before_3000x2000.jpeg →→→ after_1024x768.jpeg
I think I'll need pseudo-functions like these:

foo( before_file_path, after_file_path, new_width, new_height )

which makes use of

decompress_jpeg( before_file_path )
resize( decompressed_data, new_width, new_height )
compress_jpeg( resized_data )
save_jpeg( compressed_data, after_file_path )

Please correct my approach if I misunderstood something.
What I assume:

Since the resolutions will vary, first you have to decompress the existing jpeg so you can properly work with the pixel data.
Second, you resize the pixeldata to a smaller buffer with some function foo().
Third, you compress said buffer and save it to disk.

What I tried (and failed):
For starters, I tried playing around with the

write_JPEG_file (char * filename, int quality)

function provided in example.c of jpeglib-9b. I just want to write out a test-picture in whatever resolution I specify with a single colour. But I run into a problem. I think I'm writing out random memory and I dont know why. (here is a picture: img_100x100) Notice how at the top there is white colour up to a certain point. This part changes accordingly to what I assign in the first loop. But after a certain amount it changes to random noise. Why?
What I changed:
I defined image_width, image_height, image_buffer
I replaced all fopen(...) with fopen_s(...).
I hardcoded the quality to 100 in jpeg_set_quality(...)
Code:
#include <iostream>
#include "jpeg-9b\jpeglib.h"
#include "jpeg-9b\jerror.h"

int TEST_WRITE_JPEG(char* file_name)
{
    // DEFINE A PIC HERE
    const int image_width = 100;        /* Number of columns in image */
    const int image_height = 100;   /* Number of rows in image */
    JSAMPLE* image_buffer = new JSAMPLE[image_width * image_height]();  /* Points to large array of R,G,B-order data */
    for (int i = 0; i < image_width*image_height; i++)
    {
        image_buffer[i] = 255;
    }

    /* Step 1: allocate and initialize JPEG compression object */
    struct jpeg_compress_struct cinfo;
    struct jpeg_error_mgr jerr;
    FILE * outfile;
    JSAMPROW row_pointer[1];
    int row_stride;

    cinfo.err = jpeg_std_error(&jerr);
    jpeg_create_compress(&cinfo);

    /* Step 2: specify data destination (eg, a file) */
    if (fopen_s(&outfile, file_name, "wb") != NULL)
    {
        fprintf(stderr, "can't open %s\n", file_name);
        exit(1);
    }
    jpeg_stdio_dest(&cinfo, outfile);

    /* Step 3: set parameters for compression */
    cinfo.image_width = image_width;    /* image width and height, in pixels */
    cinfo.image_height = image_height;
    cinfo.input_components = 3;         /* # of color components per pixel */
    cinfo.in_color_space = JCS_RGB;     /* colorspace of input image */

    jpeg_set_defaults(&cinfo);
    jpeg_set_quality(&cinfo, 100, TRUE);

    /* Step 4: Start compressor */
    jpeg_start_compress(&cinfo, TRUE);

    /* Step 5: while (scan lines remain to be written) */
    row_stride = image_width * 3;

    while (cinfo.next_scanline < cinfo.image_height)
    {
        row_pointer[0] = (JSAMPROW)&image_buffer[cinfo.next_scanline * row_stride];
        (void)jpeg_write_scanlines(&cinfo, row_pointer, 1);
    }

    /* Step 6: Finish compression */
    jpeg_finish_compress(&cinfo);
    /* After finish_compress, we can close the output file. */
    fclose(outfile);

    /* Step 7: release JPEG compression object */
    /* This is an important step since it will release a good deal of memory. */
    jpeg_destroy_compress(&cinfo);

    return 0;
}

Clear questions:
Why do I write out this picture and not a plain white one?
Why does the program crash if image_buffer contains more than 128x128 unsigned chars?
Comment: You don't want to do this. You want to save it with a lower Q. This approach will pixilate the data.
Comment: @EJP I dont want to do what specifically? I assume you're talking about the resizing part? Could you elaborate, please?
Answer: 3 bytes are used for each pixels, so you have to allocate 3 * image_width * image_height elements while you allocated only image_width * image_height elements. Allocate and initialize sufficient elements.
Comment: Yes, 3 seconds after I hit submit I immediately saw that. Wow this is embarrassing. Thank you very much! That fixed everything. No crash and works perfectly for larger sizes. Can't accept your answer yet, since it is so early.


Registration form in popup in drupal 8

Question: I have to show log in and registration form in popup in drupal 8 website. I had check for module but I did not find any module.
can anyone help me ?
Answer: You Can take a look on Login Popup module.
This module will provide simple Login and Register link as a block plugin, which will load the Drupal Login form and Register form in a popup.
Comment: Is this possible to customise registration form if we are using login popup? I have to also show registration with social media.
Comment: I am using https://www.drupal.org/project/password_policy with login popup but its not working properly. Thanks for your suggestion
Answer: When I have had to do such things in a custom theme I have created a popup with CSS/JS (or Bootstrap to be honest) in a relevant template file and put a region in the popup which you populate with whatever you want.

Registration form in popup in drupal 8


What stretches should I be do doing to reduce my chance of injury from long term playing?

Question:
Possible Duplicate:
What can I do to minimize damage to my picking hand wrist as I practice guitar?

I've heard of many musicians having problems with carpal tunnel and tendonitis, and now some of my friends are even dealing with mild cases (one of them is even less than 17 years old). How can injuries of this type be prevented? What types of stretches of should I look at to protect myself from injury?
I want to be able to enjoy a lifetime's worth of making music, so I'm eager to make sure my body is able to handle it as well.
NOTE: I think this question is fairly instrument-agnostic as nearly all instruments involve repetitive motion, but it could be split up for specific groups of instruments if necessary. I know this is a health topic, but I think it's highly relevant to virtually all musicians.
Comment: To be honest, as the question is really "What should I do to reduce my chances of injury from a repetitive activity" I think it should be migrated to fitness.se
Comment: I agree.  I could see this possibly working here if it were about a specific instrument and better yet a specific action, but when it's so broad I don't think the average musician has the relevant expertise.  On the opposite end, experts in fitness and health should know how to deal with and prevent RSIs.
Comment: I disagree - musicians' issues with RSI are very different from, say, computer programmers (I happen to be both  ;-)   Also, musicians have to build strength, stamina and flexibility, which usually involves some discomfort, which make them more like athletes, except that athletics never (?) involves such fine manual motor movements.
Comment: I think if it belongs here, there needs to be a separate question for each type of instrument. A guitarist, drummer, pianist, trombonist, all use completely different muscles. Even an acoustic guitar and an electric guitar player (with light gauge strings and super-low action) would have very different needs.
Comment: Looks like a dupe of http://music.stackexchange.com/q/349/104, but especially in light of @slim's comments I think this is a fitness SE question.
Comment: Closing even though the linked question is guitar-specific because this question seems to broad to be answered well.
Answer: The American Society for Surgery of the Hand
The Electronic Textbook of Hand Surgery: Carpal tunnel syndrome exercises
http://www.eatonhand.com/hw/ctexercise.htm
Comment: Can you explain some of the exercises? This helps prevent link rot from affecting the helpfulness of the answer.


Como passar dados pesquisados por uma view de volta para a própria view

Question: Eu preciso pesquisar um banco de dados através de uma view (Laravel Blade).
Os dados obtidos, guardados num array, necessito exibir na própria página chamou o banco de dados.
Não estou obtendo êxito no retorno do array com tais dados, porque não sei como tratar o array dentro do bloco da view que espera esta resposta.
Explico:
A view que prepara a consulta ao banco de dados tem um formulário, com um botão Submit.
Esta ação dispara um método do Controller que vai ao banco de dados, pesquisa os dados e retorna um array.
Os dados existem, o array está populado.
São os seguintes passos:
Primeiro, a view e o formulário.
Nome do arquivo: listar.blade.php:
<code>@extends ('PrincipalView')
@corpo
<form name="frmTSPesquisar"
action="{{    action('TSController@pesquisarExecutar') }}"
method="GET" role="form">
Busca: <input list="files" placeholder="20000">
<datalist id="files">
<option>20000</option>
</datalist>
<button type="submit">Pesquisar</button>
</form>
@stop
</code>
Veja que a tag Action do formulário já encaminha o que o Submit vai provocar.
Na página TSController.php, onde reside o método provocado, tenho o código:
<code>public function pesquisarExecutar(Request $request) {
    $resultado=DB::table('tabts')
            ->join('tabfiles', 'tabts.file_tabfiles', '=', 'tabfiles.id')
            ->where('tabfiles.file',"=",$request->input('namSelNumFile'))
            ->get();

}//pesquisarExecutar
</code>
Neste método acima, como poderia fazer com que o array $resultado pudesse ser utilizado na mesma página (listar.blade.php) original, abaixo do formulário que provocou esta coleta de dados?
A estrutura deste aproveitamento do array $resultado poderia completar o código com o formulário de alguma maneira assim:
<code>@extends ('PrincipalView')
@corpo
  <form name="frmTSPesquisar"
action="{{  action('TSController@pesquisarExecutar') }}" method="GET" role="form">
    Busca: <input list="files" placeholder="20000">
    <datalist id="files">
    <option>20000</option>
    </datalist>
    <button type="submit">Pesquisar</button>
    </form>
@stop
{{-- abaixo seria o que eu preciso para interagir com a resposta via array --}}
@foreach ($resultado as $r)
{{r$->datalancamento}}
@endforeach
</code>
Enfim, meu problema está, acredito, em como passar o array para a view e, uma vez nesta view, como fazer um loop para aproveitar cada valor obtido dentro do array.
Comment: Você pode fazer com requisições via AJAX (js) .
Evitaria o "recarregamento" da páginas e formulário.
Answer: Para passar variáveis para a view no laravel 5.* no retorno do método do seu controller utilize:
<code>  return  view('listar',compact('resultado'));

    ou

  return  view('listar',get_defined_vars());
</code>
Comment: Muito útil o seu comentário. Segui o que você disse e funcionou, mas mudei a passagem dos valores da seguinte forma: return view('listar')->with('resultado',$resultado);
Comment: Editei minha resposta porque quando você usa o compact a váriavel deve ser passada como string


Default return value for Collectors.toMap

Question: If we image, we have a object called person and person looks like the follwing:
class Person {
    int id;
    String name;
    String country
    // ...
    // getter/setter
}

And we have a List of Person objects and we want to "convert" it to a map. We can use the following:
Map<Long, List<Person>> collect = personList.stream().
    collect(Collectors.toMap(Person::getId, p -> p));

But it is possible to return a default value for the valuemapper and change the type of the valuemapper?
I thought on something like that:
Map<Long, List<Person>> collect =
     personList.stream().collect(Collectors.groupingBy(Person::getId, 0));

but with this i get the following error is not applicable for the arguments
I have a workaround but i think it's not really pretty.
Map<Long, Object> collect2 = personList.stream().
    collect(Collectors.toMap(Person::getId, pe -> {
            return 0;
    }));

Comment: Why use groupingBy? Doesn't each Person have a unique id? What are you grouping here?
Comment: I have a hard time understanding what you want to achieve. What do you want the map to contain: give an example with 3 or 4 persons, and the resulting map.
Comment: Yes you right. Sorry, my mistkae, because i have in my ide a other object but before there come questions about what that object is and make etc. i decided to use a "allrounder" for this example. i change it.
Answer: If you want to map every ID of each person to the same value, that's exactly what you need to do, although you can simplify it by writing Collectors.toMap(Person::getId, pe -> 0).


"$.fieldValue is not a function" alert on login form submit

Question: In Drupal 7, with Devel, CTools and Ajax Login/Register plugins, I get an alert on submitting the login form on http://p262957.mittwaldserver.info/drupal/user/login.
I am using a custom child theme based on bootstrap project. I already tried the instructions on https://www.drupal.org/node/1008664 that says I should be sure to load jquery.form.js before ajax.js.
Does anybody have an idea?
Answer: In the parent theme was a ajax.js override function that caused the error. It can be found in theme_root_dir/js/misc/. You just have to empty it. Don't forget to empty your cache afterwards. Now it should work.
Comment: I have tried your way, issue has been fixed but ajax functionality is not working now. Is it right way to make changes in drupal core files?


How to slide position of a div when we drag other div upon it in java-script

Question: I have two divs I want that when I drag first div on second div than second div should move from its position.

#mover {
    position: absolute;
    left: 150px;
    width: 80px;
    height: 60px;
    background: red;
}

#trigger {
     position: absolute;
    left: 80px;
    width: 50px;
    height: 60px;
    background: green;
}

Answer: You have to handle ondrop event of green block.
function drop(ev) {
   ev.preventDefault();
   document.getElementById("mover").style="left:80px";
   document.getElementById("trigger").style="left:200px";
}

Here is link for codepen.Code pen
I have red block as draggable. When you drop on green block, position will be changed.
Comment: i have already implemented this thing, what i want instead of this when i that when i drag first div upon second div than position of the second div should slide automatically(no style change)
Comment: actually i need this in pure java script


Most cost effective package combination (shipping)

Question: I have a very simple function for my shipping method to put the packages together. Basically everything works exactly the way it should. However, in special constellations, e.g. when the quantity is 42, more costs are charged than necessary.
The variable $packages is filled like this:
Array
(
    [0] => Array
        (
            [name] => 18er
            [contain] => 18
            [cost] => 5
        )

    [1] => Array
        (
            [name] => 12er
            [contain] => 12
            [cost] => 5
        )

    [2] => Array
        (
            [name] => 6er
            [contain] => 6
            [cost] => 8
        )

)

The relevant part of my function is the following:
$overrun    = 42; // Items in cart
$cost       = 0;
$filled     = array();
$quantities = array();
foreach( $packages as $the_package ){
    $delivers = floor( $overrun / $the_package['contain'] );
    if( ! $delivers ) {
        continue;
    }
    $filled[$the_package['name']] = $delivers;
    $overrun = $overrun - ( $delivers * $the_package['contain'] );
    $cost = $cost + ( $delivers * $the_package['cost'] );
}

After the calculation, the variable $filled is defined as follows, which results in shipping costs of $18:
Array
(
    [18er] => 2
    [6er] => 1
)

Optimal would be a result of $15, therefore the variable $filled would have to look like this:
Array
(
    [18er] => 1
    [12er] => 2
)

I guess I can't do it at all with this simple foreach loop. Can you give me some help on how to solve this?
You can find a working example at 3v4l.org.
Thanks a lot!
Comment: You are right that this optimization problem requires more sophisticated solution if you really need the best possible result. If you are able to define the function mathematically you will be able to find the derivative numerically - or you may choose to try the popular AMPL math package (https://ampl.com/try-ampl/download-a-free-demo/) From its bundled solvers I would recommend the MINOS one.
Comment: @IVOGELOV thank you for your comment. The AMPL package looks very promising on the first sight. Unfortunately there may be a licence issue. The code I'm struggling with is for a WooCommerce plugin. I thought this information is useless in my question, but in case of 3rd party packages relevant though.
Comment: You are right that the free size-limited version (the one I am referring to) indeed is marked/intended for noncommercial use. If you intend to sell your code - there will be a licensing issue. The only other option you have (besides buying AMPL license) is to write down your math function, find its derivative(s) on paper - and then choose how to find the global minimum programmaticaly. Or, you may try searching some open-source solver ...
Comment: It's not clear what the business rules require use of 6er box; even for qty 1 the 12er is the cheaper choice.  If you require qty <=6 to use the 6er box b/c that's the rule, then do so.  This suggests for any qty > 6 to never use the 6er box if you want the lowest shipping charges.
Answer: Half of my answers comes from this question and the subsequent answers, so if my answer works, please vote over there, too. I'll start with a tweaked version of that code here. The gist of it is that it takes each item in a given array $numbers such as [6, 12, 18] and sees if it can sum up to $target such as 42. My tweak to this function is that I'm also passing in a $final array so that I can get something back instead of just printing.
function subset_sum(array &$final, array $numbers, int $target, array $partial = []): void
{
    $s = array_sum($partial);

    if ($s === $target) {
        if (!in_array($partial, $final, true)) {
            $final[] = $partial;
        }
    }

    if ($s >= $target) {
        return;
    }

    for ($i = 0; $i < count($numbers); $i++) {
        $n = $numbers[$i];
        $remaining = array_slice($numbers, $i + 1);
        subset_sum($final, $remaining, $target, array_merge($partial, [$n]));
    }
}

The problem with that function, however, is that it tries every combination of the array provided, but once a number is used it won't try it again in the same sequence. So in your case, that function would never try 18 + 18 + 6 because 18 isn't in the array twice. To fix that, we'll use array_fill to repeat our numbers as much as needed. For instance, we need 6 to be in the array seven times to target 42.
function grow_initial_array(array $numbers, int $max): array
{
    $numbers = array_unique($numbers);
    $ret = [];
    foreach ($numbers as $n) {
        assert(is_int($n));
        // The maximum number of times that $n can be divided into $max
        $x = (int)floor($max / $n);
        // Fill our array with that many items (repeat 6 seven times for 42)
        $f = array_fill(1, $x, $n);
        $ret = array_merge($ret, $f);
    }

    return $ret;
}

For your three inputs of [18, 12, 6] this produces an array of :
Array
(
    [0] => 18
    [1] => 18
    [2] => 12
    [3] => 12
    [4] => 12
    [5] => 6
    [6] => 6
    [7] => 6
    [8] => 6
    [9] => 6
    [10] => 6
    [11] => 6
)

Next up, we need to merge this simple data back in with your business logic. There's lots of ways to do this including the array_reduce etc. functions, but I'm just going to keep it simple with nested foreach loops which might not be as performant/pretty. This code creates a new array with keys being the sum of package options. The values for those sums is another array of potential options (just in case two or more combinations sum up to the same total). The third inner array is an array of your product options as initially outlined.
function remerge_to_packages_with_sums(array $final, array $packages): array
{
    $package_options = [];
    foreach ($final as $numbers) {
        $package_option = [];
        $sum = 0;
        foreach ($numbers as $n) {
            foreach ($packages as $p) {
                if ($p['contain'] === $n) {
                    $package_option[] = $p;
                    $sum += $p['cost'];
                    break;
                }
            }
        }

        if (!array_key_exists($sum, $package_options)) {
            $package_options[$sum] = [];
        }

        $package_options[$sum][] = $package_option;

    }

    return $package_options;
}

That code produces the following array (only the first key is shown):
Array
(
    [18] => Array
        (
            [0] => Array
                (
                    [0] => Array
                        (
                            [name] => 18er
                            [contain] => 18
                            [cost] => 5
                        )

                    [1] => Array
                        (
                            [name] => 18er
                            [contain] => 18
                            [cost] => 5
                        )

                    [2] => Array
                        (
                            [name] => 6er
                            [contain] => 6
                            [cost] => 8
                        )

                )

        )
        // Extra items removed for display purposes
    )
)

You can pretty much stop there if you want, your answer lies in the deeply nested array. But if you want to keep going, you can transform that into a smaller array where the keys are the sum, and the values are arrays of arrays matching your initial input:
function reduce_merged_array(array $merged_array): array
{
    $final = [];
    foreach ($merged_array as $sum => $package_collection) {
        if (!array_key_exists($sum, $final)) {
            $final[$sum] = [];
        }
        foreach ($package_collection as $pc) {
            $local = [];
            foreach ($pc as $item) {
                if (!array_key_exists($item['name'], $local)) {
                    $local[$item['name']] = 0;
                }
                $local[$item['name']]++;
            }
            $final[$sum][] = $local;
        }
    }

    return $final;
}

Which produces:
Array
(
    [15] => Array
        (
            [0] => Array
                (
                    [18er] => 1
                    [12er] => 2
                )

        )

    [18] => Array
        (
            [0] => Array
                (
                    [18er] => 2
                    [6er] => 1
                )

        )
    // Only two shown for example
)

We can put those functions to work with this code, the in-code comments should hopefully explain everything:

// Initial array
$packages = [
    [
        'name' => '18er',
        'contain' => 18,
        'cost' => 5,
    ],
    [
        'name' => '12er',
        'contain' => 12,
        'cost' => 5,
    ],
    [
        'name' => '6er',
        'contain' => 6,
        'cost' => 8,
    ],
];

// Get just our contain values
$values = array_column($packages, 'contain');

// This is our quantity that we are targeting
$target = 42;

// Will hold the result of potential summing options
$sum_options = [];

// Duplicate our items in values so that we can get every possible combination
$value_duplicated = grow_initial_array($values, $target);

// Calculate all possible sums
subset_sum($sum_options, $value_duplicated, $target);

if (0 === count($sum_options)) {
    // TODO: Nothing found that matches
    exit;
}

// Convert back to packages
$packages_with_sums = remerge_to_packages_with_sums($sum_options, $packages);

// Convert to simplified array
$reduced = reduce_merged_array($packages_with_sums);

// Sort by sum, smallest first
ksort($reduced);

// Best options
$best_price = array_key_first($reduced);
$best_priced_options = reset($reduced);

// Worst options
$worst_price = array_key_last($reduced);
$worst_priced_options = end($reduced);

The $best_priced_options and $worst_priced_options variables are arrays, just FYI, because it could be possible for two or more combinations to sum up to a given price.
Comment: Hey @ChrisHaas , thank you very much for this detailed answer and the fair handling of the origins. I will need some time to unpack everything.


Download the necessary .properties file depending on the OS

Question: There are two configuration files for different OS windows.properties and unix.properties.
There is a configuration:
@Configuration
@ConfigurationProperties (prefix = "storage")
public class StorageProperties {

     private String root;
     private String sitesDirName;
     private String avatarsDirName;
     private String screenshotsDirName;

     @PostConstruct
     public void postConstruct () {

     }

}

How to make so that a certain file would be loaded depending on the OS? I ran across @Conditional, but this is one condition. Maybe he will help somehow.
Answer: (1) Define an enum for OS .Use system property os.name  to determine current OS :
public enum OS {
    WINDOWS, UNIX, MAC, UNKNOWN;

    public static OS currentOS() {
        String OS = System.getProperty("os.name").toLowerCase();

        if (OS.indexOf("win") >= 0) {
            return WINDOWS;
        } else if (OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0 || OS.indexOf("aix") > 0) {
            return UNIX;
        } else if ((OS.indexOf("mac") >= 0)) {
            return MAC;
        } else {
            return UNKNOWN;
        }
    }
}

(2) Implement ConditionalOnOS :
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(OsCondition.class)
public @interface ConditionalOnOS {
    OS os();
}

public class OsCondition implements Condition {

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {

        MultiValueMap<String, Object> attrs = metadata.getAllAnnotationAttributes(ConditionalOnOS.class.getName());
        if (attrs != null) {
            Object os = attrs.getFirst("os");
            if (os != null && os instanceof OS) {
                if (OS.currentOS().equals(((OS) os))) {
                    return true;
                }
            }
        }
        return false;
    }
}

(3) Configure @ConfigurationProperties for different OS. Use @PropertySource to define the properties file paths for different OS:
@ConfigurationProperties(prefix = "storage")
public static class StorageProperties {
    private String root;
    private String sitesDirName;
    private String avatarsDirName;
    private String screenshotsDirName;

    @Configuration
    @PropertySource("classpath:windows.properties")
    @ConditionalOnOS(os = OS.WINDOWS)
    public static class WindowsStrogeProperties extends StorageProperties {

    }

    @Configuration
    @PropertySource("classpath:unix.properties")
    @ConditionalOnOS(os = OS.UNIX)
    public static class UnixStrogeProperties extends StorageProperties {

    }
}

(4) Inject StorageProperties to the client
Answer: @Conditional would be useful to determine the operating system, whereby you would have to define the conditional classes.
As a shorter approach, you can use good old if statements to determine the operating system. Assuming you have two different files, windows.properties and unix.properties as suggested, create the configuration class to determine the operating system and load the appropriate .properties file.
The code for the configuration class is as shown below.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.ClassPathResource;
import com.sun.javafx.PlatformUtil;

@Configuration
public class OSConfiguration {

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
                String osName = "";

    if (PlatformUtil.isWindows()) {
        osName = "windows";
    } else if (PlatformUtil.isUnix()) {
        osName = "unix";
    } else if (PlatformUtil.isMac()) {
        osName = "mac";
    }

    String propertiesFilename = osName + ".properties";
    PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
    configurer.setLocation(new ClassPathResource(propertiesFilename));

    return configurer;
    }

}

Comment: Not sure if you really want to rely on a JavaFX class for this, as this has been removed in newer Java versions. Also adding an additional `PropertySourcesPlaceholderConfigurer` might cause issues and will not let the regular Spring Boot magic happen with property files.
Comment: Yes, @M.Deinum raises good points, especially on the JavaFX having been removed from newer Java versions.

As per Java release notes: [JavaFX is no longer included in the JDK. It is now available as a separate download from openjfx.io](https://www.oracle.com/technetwork/java/javase/11-relnote-issues-5012449.html)


Gerar uma janela de pop-up no R

Question: Tenho um código em R que gera de saída uma mensagem informando se uma série está atualizada ou não. Rodo o código através de um arquivo .bat no Windows e ele gera um arquivo txt.
Tentei gerar um pop-up usando o pacote svDialogs, mas ele só gera o pop-up se eu executar o código pelo próprio R. Existe alguma forma de o pop-up ser exibido executando o código atráves do arquivo .bat?
Código que estou usando para mostrar o pop-up dentro do R:
dlg_message(mensagem, type = "ok")

Código do arquivo .bat que estou usando para executar o código em R:
cd C:\Program Files\R\R-3.6.1\bin\i386
Rscript.exe C:\Users\User\Documents\R\consulta_ettj.R

Obs.: O código funciona normalmente sendo executado pelo .bat, só o pop-up que não é gerado.
Comment: A diferença está em que uma seção é interativa e a outra não. Para maiores informações veja `?interactive()`
Answer:

Precisa ser usando svDialogs? Aparentemente, ele só funciona no modo interativo ou nem nele (rodando dentro do RStudio).

Existe alguma forma de o pop-up ser exibido executando o código através do arquivo .bat?

1) Sim, usando o tc/ltk, opção que funciona fora do RStudio, digo, fora do modo interativo, e que já vem com as ultimas versões do r.

2) A alternativa com uso do tc/ltk e que funciona no bat/cmd

a) Ou você entra na pasta do R executa:  cd /d "C:\Program Files\R\R-3.6.1\bin\i386" && Rscript.exe Script.R

b) Ou pode fazer o seu bat/cmd criar o seu Rscript para excutá-lo em tempo de execução, e sem usar escaping:

@;echo off && setlocal && mode 70,10 & color 0A & title ..\%~dpnx0
@;
@;<con: pushd "C:\Program Files\R\R-4.0.5\bin\i386\." 2>nul && =;(
@;cmd/r %__APPDIR__%findstr.exe /vb @; ^<"%~f0">"%temp%\RScr.r")=;
@;R.exe --vanilla <"%tmp%\RScr.r">nul 2>&1 &&(del/q "%tmp%\RScr.r"
@;endlocal & goto :EOF )||(del/q "%temp%\RScr.r" 2>nul && endlocal
@;echo[Error: Path para R/Rscript nao encontrado^!! & goto :EOF);=
@;
@; Nas linhas abaixo entraram o código R, mas sem iniciar com "@;"

require(tcltk)

msgBox <- tkmessageBox(title = "tc/ltk SO Q431647",
                       message = "Hello, world! by tcltk!", icon = "info", type = "ok")

msgBox <- tkmessageBox(title = "zOk Click..",
                       message = "z0k", type = "ok")

Obs.: As linhas do código acima, são executadas pelo  interpretador de comando, e ele saí da execução em: goto :EOF, também são filtradas para o script R, todas que não começam com os caráteres @;, então perceba que seu código em R, terá essa limitação apenas, nenhuma linha pode começar com @;

Para uso convencional

1) Salve esse código no seu Script.R:

require(tcltk)

msgBox <- tkmessageBox(title = "tc/ltk SO Q431647",
                      message = "Hello, world! by tcltk!", icon = "info", type = "ok")

msgBox <- tkmessageBox(title = "zOk Click..",
                       message = "z0k", type = "ok")

2) Salve esse código no seu bat/cmd:

@echo off && setlocal && mode 70,10 && color 0A && title %~dpnx0

pushd "C:\Program Files\R\R-3.6.1\bin\i386\." && R.exe --vanilla <"d:\caminho\do\seu\RScriptR.r"
popd && endlocal && goto :EOF

Comentando o bat/cmd:

echo off
inibir eco do comando na sáida do prompt

setlocal
herdar as variáveis da sessão ambiente atual

mode 70,10
muda tamanho da janela p 70 colunas 10 linhas

color 0A
muda cor de fundo para preto e a fonte verde claro

title %~dpnx0
atribuir titulo da janela com: d=drive p=path n=name x ext do bat

pushd "c:\..."
faz a pasta atual ser salva para retorno (via popd) e traz para pila a pasta

&& (
caso a execução anterior se deu se erro, vai executar as ações dentro enfileiradas dentro do ()

cmd  /r type "%~f0"
vai direcionar o conteúdo do arquivo bat (fullpath %~f0) para o findstr

findstr /vb ^@ |%__APPDIR__%findstr /vb ^@; >"%temp%\RScr.r")
vai ignorar todas as linhas iniciadas por "@;", e redirecionar como conteúdo para o arquivo >"%temp%\RScr.r" (gravar nele)

@;R.exe --vanilla <"%tmp%\RScr.r" 2>&1>&0
executar o escript apontado pelo operador < file. ignorando arquivos e avariável R_LIBS_USER local do usuário.

&& (del "%temp%\RScr.r"
se a execução se deu sem erro, vai apagar o script criado (temporário), finalizar o local, (endlocal) e ir para o final do arquivo, sair.. (executando o que esta em ()

||(del "%temp%\RScr.r" 2>nul && ;endlocal
@;echo[Error: Path para R/Rscript não encontrado^!! & goto :EOF )
se a execução decorrer em erro(s), vai exibir uma mensagem, sugerindo que o erro está no caminho, vai apagar o script temporário, finalizar o local, (endlocal) e ir para o final do arquivo, sair..

@;:: Nas linhas abaixo entra o código R, mas sem iniciar com "@;"
Apenas um comentário lembrado da limitação para autoria de código em script R

Gerar uma janela de pop-up no R


'e.target.files' is possibly 'null'

Question: In my input component I extract file content after input. Took code from here
Error occurred on the line of onChange={e => handleFileChosen(e.target.files[0])}, to be more accurate, ts underlines e.target.files.
Error message is 'e.target.files' is possibly 'null'
And here is the code:
import styles from './Input.module.scss'
import { FileInputProps } from './FileInput.props';
import cn from 'classnames'
import { useState } from 'react';

export const FileInput = ({ ...props }: FileInputProps): JSX.Element => {
      const [fileContent, setFileContent] = useState<string>('')

      const handleFileChosen = (file: File) => {
            let fileReader = new FileReader()
            fileReader.onloadend = (e: Event) => {
                  const content = fileReader.result || ''
                  setFileContent(content.toString())
            }
            fileReader.readAsText(file)
      }

      return (
            <>
                  <input
                        type='file'
                        onChange={(e) => {handleFileChosen(e.target.files[0])}}
                  />

{fileContent}

            </>
      )
}

I've checked this SO page, but none of those solutions helped me
Comment: Can you reproduce the error in the code sandbox?
as I'm not able to reproduce the error with your code
Comment: Didn't [this answer](https://stackoverflow.com/a/61750419/893780) provide you with a solution that you can apply to your code?
Comment: @robertklep for some reason no
Answer: Please review this code
import React, {ChangeEvent, useEffect, useState} from 'react';

const FileUploadComponent = () => {
    const [base64Data, setBase64Data] = useState("");
    const [error, setError] = useState("");

    const handleFileChange = (e: ChangeEvent<HTMLInputElement>) => {
        const files: FileList | null = e.target.files;
        const reader: FileReader = new FileReader();
        reader.onloadend = function () {
            setBase64Data(reader.result as string)
        }
        reader.onerror = function () {
            setError("Error file not reading");
        }
        reader.readAsDataURL(files?.[0] as File);
    }

    useEffect(()=> {
        console.log(base64Data)
    }, [base64Data])

    return (

            <input
                className={"form-control"}
                type={"file"}
                onChange={handleFileChange}
            />

    );
};

export default FileUploadComponent;

'e.target.files' is possibly 'null'


Image with title over top

Question: I am trying to create a view that has a image that is linked to another node, which I can do. However, I want to take the title (of content) and place it over top of the image like this.

I tried with CSS. Am I missing something?
Comment: My guess is that I will need the title ID within the image ID (css). Maybe rewriting will work?
Comment: Just to clarify. Are you talking about views-module view and is the content title referring to title of the content where the image is saved or title of the linked content?
Comment: View module, Content Title, Content Image
Answer: This isn't really a Drupal question.
One of the usual methods is to use absolute positioning to remove the title from the document flow. Starting from HTML looking something like (e.g., rewriting with views):

Image title

Then use CSS rules something like:
.my-frame { position: relative; }
.my-title { position: absolute; top: 10; left: 10; }

Comment: Notice how in this example the position of title is after the image and therefore remains visible when positioned over preceding content. If the title would be before the image the css would need to include also z-index parameter.

Image with title over top


Activate Passive Arp learning

Question: I want to enable my linux-kernel to passively listen (learn) the arp request broadcasted in the lan segment (arp request in the network not destined for me). Is there any configuration available?
Comment: The "why" matters often just as much (if not more) than the "how". All good technical questions should contain what you're trying to achieve, because that allows us to help you best and maybe even offer up some clever alternatives that you hadn't thought of. That's the beauty of collective knowledge.
Comment: What do you want to do with this information?  Merely for logging purposes, or do you want to forward with these entries?   If you want forwarding, how many differen tsubnets are attached to this ethernet interface?
Comment: does it matter anyway what I want to do with the information?
Comment: I tried this without VRRP. I connected 3 routers in a lan. now i sent an arp request from the first router to second routers. Now both get each other's mac-address. Meanwhile tcpdump was running on the router3 and I could see that the arp-request went to router3 also but it didn't updated its arp table. I want it to passively listen and learn. All the routers have linux kernel.
Answer: Does the information have to be collected by the kernel? Or do you just need the machine to collect the information?
A good solution for learning the arp mappings in a network is Arpwatch. I run it on RHEL and it works like a champ. It keeps all the mappings in a database file, and can be configured to email on various kinds of events, like a new mapping appearing, or the MAC address mapped to an IP address changing.
Comment: I'm sorry but arpwatch isn't helpful for the reasons I explained in my answer.
Answer: What you want is not what ARP (or ethernet switching) is supposed to do; ethernet switches deliver ARP replies to the address in the ethernet frame, and ARP replies are sent to a unicast mac-address.
If you want to constantly keep the mac-address of a host in your local linux ARP table, then cron a job to send a ping to each host every five minutes.  Alternatively, you can manually hard-code the ARP entry in linux (as root):
arp -s 192.168.0.65 00:50:ba:85:85:ca

Activate Passive Arp learning


How to get data from a multidimensional sql database?

Question: I have a database which I call datenbank in this example... In this database I have a table called "artikel"..
I now have a number and want to search my table "artikel" in the column "idartikel" for this number; Once I found the right row I want to compare the entry of another column called kategorie_idkategorie of this row but of another column  with a certain value;
To do so I start connecting to my database

error_reporting(E_ALL);
define ( 'MYSQL_HOST',      'localhost' );
define ( 'MYSQL_BENUTZER',  'root' );
define ( 'MYSQL_KENNWORT',  '' );

define ( 'MYSQL_DATENBANK', 'datenbank' );

    $db_link = mysqli_connect (
                 MYSQL_HOST,
                 MYSQL_BENUTZER,
                 MYSQL_KENNWORT,
                 MYSQL_DATENBANK
                );

    if ($db_link === False) {
        die("
 Error
");
    }

?>

Diese connection works; Now I want to search for my numer, in this case 55065 in the table artikel and the column idartikel; Once I found the row I want the entry of the column kategorie_idkategorie and compare it to the value 1592
<?php

require_once ('configdatenbank.php');
$id=55065; //Diese Nummer möchte ich in meiner Tabelle artikel suchen

$wert1 = 1592;

$sql = "SELECT kategorie_idkategorie FROM artikel WHERE idartikel=55065";
$query = mysql_query($sql);
$row = mysql_fetch_row($query);
if($row['kategorie_idkategorie'] == $wert1){
  echo 'equal';
}else{
 echo 'not equal';
}

?>

For a better understanding I made a screenshot of the entry of the table;
http://www.bilder-upload.eu/show.php?file=bed499-1446912607.png
As you see there is the entry where the column idartikel has the value 55065;
Now I want to check if this row has the value 1592 in the colummn kategorie_idkategorie, which is obviously true; So I should get the message "equal";
However I get several errors when doing so and also get the message "not equal"
If you look at the database you see three different parts of each column:
Funktion, Null and Wert;
Is it the problem that I point on the column in general and not specifically on the "wert" part of the column?
Or what is the problem in this case?
Many thanks!! :)
Edit: My new version...But it's still not working
<?php

require_once ('configdatenbank.php');
$id=55065;

$wert1 = 1592;

// MySQL-Query zum holen des wertes aus der DB
$sql = "SELECT kategorie_idkategorie FROM artikel WHERE idartikel=55065";
$query = mysqli_query($sql);
$row = mysqli_fetch_assoc($query);

if($row['kategorie_idkategorie'] == $wert1){
  echo 'werte sind gleich';
}else{
 echo 'werte sind nicht gleich';
}

?>

Comment: You're mixing `mysql_*` with `mysqli_*`. That doesn't work.
Answer: I had to edit, because jeroen pointed out that your connection is mysqli. Thats correct, you cannot mix the two, so upgrade from mysql to mysqli:
And to fix your code, use fetch_assoc instead of fetch_row so that you can index by key. Change three lines in your code to this:
$sql = "SELECT kategorie_idkategorie FROM artikel WHERE idartikel=55065";
$query = mysqli_query($db_link, $sql);
$row = mysqli_fetch_assoc($query);

Comment: Sorry I'm really a beginner; Can someone help me by telling me exactly what I need to replace it that it is going to work? I'm trying now for the whole day, unfortunately... :(
Comment: Warning: mysqli_query() expects at least 2 parameters, 1 given in C:\xampp\htdocs\Amazon\test.php on line 12

Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, null given in C:\xampp\htdocs\test.php on line 13
not equal
Comment: It still doesnt't work..... :( Do you have an idea why?  I posted the new script as Update in my question... :)
Comment: that's correct, see my edit. it's the $db_link connection.
Comment: Yes....!!!! It works you are the best... :) :) :) Can I ask you one more thing? If you look at the picture you see the line "aktiv" where it is either J or N... Can I use it the same way as with the other column just compare instead of the number 1592 the string 'J' or how would I do it in that case?


Can a user be excluded from /etc/profile.d scripts?

Question: I am having a problem using Rsync/SSH with a specific user for Amanda backups on a server.
rsync -e 'ssh -i /var/lib/amanda/.ssh/id_rsa_amdump' -az otherserver:/dir/to/copy /copy/dir
I have noticed that it gives all kinds of errors on a script within /etc/profile.d and cannot log on with the SSH key. If I try to log into the user account with SSH it just displays errors and will not give a prompt. Is there a way to tell the user to not read /etc/profile.d or to set it to skip/exclude that user?
The errors it gives on log on attempt with SSH  is:
/etc/profile.d/somescript.sh line 125: bind: warning: line editing not enabled
It shows this error for at least 20 different lines inside the script. I do not get this error for any other user. In addition the home directory for the Amanda backup user is in /var/lib/ not /home.
Comment: I imagine the best solution may be to simply fix the error in the scripts. It's surprising that the specific user can't log on but others can. Do they have a different shell configured?
Comment: What are the error messages ?
Comment: What's line 125 of somescript.sh ?
Comment: `bind -x '"\e[M":'$'"ls -l"';`
Answer: Using bind only makes sense in a interactive shell. In somescript.sh check if the shell is interactive and only run bind if it is. For example,
if [ -n "$PS1" ]; then
    bind -x '"\e[M":'$'"ls -l"';
fi

Comment: An alternate test is `if tty -s; then ...`.


RuntimeWarning: invalid value encountered in greater large = s > cutoff

Question: sns.lmplot(x='day_diff',y='add_child_21',data=mean, hue='treatment',ci=90,height=6,aspect=1.4, fit_reg=True)

This code fails to plot the LM regression on the left side. I have no missing or infinite values.
ERROR: RuntimeWarning: invalid value encountered in greater large = s > cutoff
Comment: hard to tell what went wrong. works ok for me with simulated data. Can you post the data?
Answer: I used your data and plotted, i don't get the error:
import pandas as pd
import seaborn as sns

df = pd.read_csv("https://raw.githubusercontent.com/andrahiriscau/data/main/data.xls")

sns.lmplot(x='day_diff',y='add_child_21',data=df,
           hue='treatment',ci=90,height=6,aspect=1.4, fit_reg=True)

Comment: Thank you. Might be some issue with my Python
Comment: Which Python version are you using?
Comment: It was an environment issue. I created a new environment for the project and it works.  Note: Jupyter started working only the next day, but the code run from the command line immediately.
Comment: hmmm there must be something wrong with the installation in the environment then. you are using conda i guess.. can be a bit problematic


React and Flowtype - inherit class

Question: Lets assume that I have
// Foo.js
type PropsType = { cool: boolean };
class Foo extends React.Component<PropsType> {}

// Bar.js
import Foo from './Foo';

type PropsBar = { temp: string };
class Bar extends Foo {
  test() {
     this.props.cool; // there is no error
     this.props.temp;
                ^^^^ Property not found in object type
  }
}

My question is, how to pass additional Props to Bar component?
Answer: You need to make your super class generic. Just as React.Component is generic, so can your classes and functions be as well.
You can make a declaration such as a class or function generic by introducing a type parameter.
Let us make Foo generic
export default class Foo<T> extends React.Component<FooProps & T> {}

Note the intersection type, written FooProps & T, that is passed to the generic super class React.Component. This means that Foo.prototype.props will have the properties declared in FooProps and also any properties declared by T.
Now when we use Foo, such as in an extends clause, we need to specify a type for T.
type BarProps = { temp: string };

export default class Bar extends Foo<BarProps> {
  constructor(props, context) {
    super(props, context);
    console.log(this.props.temp);
  }
}

If you want to maintain simplicity for consumers of Foo that do not add additional props, you can specify a default type for T as in
export default class Foo<T = {}> extends React.Component<FooProps & T> {}

export class Bar extends Foo {}

Note: All of the syntax above is valid in both Flow and TypeScript.
Comment: Perfect! Thank you for your explanation :)
Comment: Glad I could help

React and Flowtype - inherit class


Parametrize $D = \left\{ (x,y,z) \in \mathbb{R}^3: x^2+y^2+z^2=1; (x-1)^2+y^2+(z-1)^2=1 \right\}$

Question: I need to find a parametrization in terms of $t$ (one variable) for $$D = \left\{ (x,y,z) \in \mathbb{R}^3: x^2+y^2+z^2=1; (x-1)^2+y^2+(z-1)^2=1 \right\}$$
I can only use cartesian coordinates. I've tried to do $y^2=-(x-1)^2-(z-1)^2$ and replace it on the first condition, so $x=-z+1$. But I'm not sure about that...I'm stuck. Thanks in advance!
Comment: $D$ is the intersection of two spheres. What might the resulting curve be?
Comment: In your $y^2=...$ you forgot $+1$, so $x=-z+1$.
Answer: Yes, I would use your idea.
By the difference of both equations,
\begin{equation}
x^2 + z^2 - (x-1)^2 - (z-1)^2 = 0 \iff z = 1 - x.
\end{equation}
Then, it suffices to find $y$ in terms of $x$ and we will use the parameter $t = x$. Replacing $z = 1-x$ into the second equation,
\begin{equation}
(x-1)^2 + y^2 + x^2 = 1 \implies y = \pm \sqrt{1 - x^2 - (x-1)^2} = \pm \sqrt{2x(1-x)}.
\end{equation}
This last equation restrict your $x$ values so that $x\in[0,1]$, and your set will be
\begin{equation}
D = \left\{(t,\pm \sqrt{2t(1-t)},1-t)\;:\;t\in[0,1]\right\}.
\end{equation}
If I am not wrong, the intersection $D$ is a circumference. Maybe it would better to solve the exercise changing the coordinates to spherical.
Comment: A substitution in the end $t=\sin(u)^2$ with $u\in[0,\pi/2]$ remove the square root, then followed by $u\in[0,\pi]$ remove the $\pm$. This gives $\{sin^2(u),\frac{sin(2u)}{\sqrt 2},cos^2(u),\ u\in[0,\pi]\}$, which is the same than Jacky Chong's.
Answer: Setting the two constraint equal to each other yields
\begin{align}
y^2= 1-x^2-z^2= 1-(x-1)^2-(z-1)^2 \ \ \Rightarrow \ \  z= -x-1.
\end{align}
Plug the new constraint back into one of the old constraints, you get
\begin{align}
1=x^2+y^2+(x+1)^2 = 2\left(x+\frac{1}{2}\right)^2+y^2+\frac{1}{2}\ \ \Rightarrow \ \ \frac{\left(x+\frac{1}{2}\right)^2}{\left(\frac{1}{2}\right)^2}+\frac{y^2}{\left(\frac{1}{\sqrt{2}}\right)^2}= 1.
\end{align}
This can be easily parametrized using cosine and sine. In particular, we have that
\begin{align}
x=\frac{1}{2}\cos t-\frac{1}{2}, \ \ y = \frac{1}{\sqrt{2}}\sin t
\end{align}
gives a parametrization. Lastly, since $z= -x-1$, then we see that
\begin{align}
z = -\frac{1}{2}\cos t-\frac{1}{2}.
\end{align}
Remark: It should be clear that the intersection is a circle, but when projected down onto the $xy$-plane you will get an ellipse (as remarked by A.G.).
Comment: I didn't understand this passage:

$$2\left(x+\frac{1}{2}\right)^2+y^2+\frac{1}{2}\ \ \Rightarrow \ \ \frac{\left(x+\frac{1}{2}\right)^2}{\left(\frac{1}{2}\right)^2}+\frac{y^2}{\left(\frac{1}{\sqrt{2}}\right)^2}= 1$$

Please, could you explain it?
Comment: I wanted to write the equation in the standard ellipse form.
Comment: Sorry, I meant about the denominators, because I got:

$$1=2\left(x+\frac{1}{2}\right)^2+y^2+\frac{1}{2}\ \ \Rightarrow \ \ \frac{\left(x+\frac{1}{2}\right)^2}{\left(\frac{1}{2}\right)^2}+\frac{y^2}{\left(\frac{1}{\sqrt{2}}\right)^2}+1= 1$$

dividing the left side for 2.
Comment: I moved the $\frac{1}{2}$ to the other side then divided both sides by $\frac{1}{2}$. Also, I don't understand how you got your implication.
Comment: Oh, I made a mistake here! Thank you!
Answer: Just outline for major steps.
Method 1: As you did, express $y^2=1-(x-1)^2-(z-1)^2$ to find that $x+z-1=0$. It is the plane where the curve belongs to. Substitute $x=-z+1$ to get an equation for ellipse in $x,y$. It is the projection of the curve onto $xy$-plane. Parameterize the ellipse by $t$ (via scaled $\sin t$ and $\cos t$) and get the last coordinate from $x+z-1=0$.
Method 2: Rotate everything around $y$-axis by the angle $\pi/4$, so that in the new coordinates the center of the second sphere becomes $(0,0,\sqrt{2})$. Then the curve is a simple circle in the plane $z=\frac{\sqrt{2}}{2}$. Parameterize it and rotate back.


How do I add the  tag in ?

Question: If I want to add JavaScript in the head tag, I use drupal_add_js($js, 'inline'). This will add a

How do I add the  tag in ?


dataUrl in jqGrid calls every time

Question: I am using jqGrid with inline editing. In one column there is dropdown list and pulls data from web service.

$("#Freight").jqGrid({
  datatype: 'xmlstring',
  datastr: xmlString,
  mtype: 'GET',
  ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
  xmlReader: { repeatitems: false, root: "DocumentsAdditionalExpenses", row: 'row' },
  colNames: ['ExpenseCode', 'Feight Name', 'Remarks', 'Tax Code', 'Total Tax Amount', 'Distribution Method', 'Amount'],
  colModel: [
                    { name: 'ExpenseCode', index: 'ExpenseCode', hidden: true, key: true },
                    { name: 'FreightName', index: 'FreightName', width: 100 },
                    { name: 'Remarks', index: 'Remarks', editable: true, edittype: 'text', width: 150 },
                    { name: 'TaxCode', index: 'TaxCode', editable: true,
                     width: 100,
                     edittype: 'select',
                     formatter: 'select',
                     editoptions: { aysnc: false, dataUrl: clientURL,
                      buildSelect: function (data) {
                       var v = data.replace(/</g, '<').replace(/>/g, '>');
                       response = $.parseXML(v);
                       $response = $(response);
                       var s = '<select>';
                       $response.find('FreightExpense row').each(function (index) {
                        var code = $(this).find('Code').text();
                        var name = $(this).find('Name').text();
                        s += '<option value="' + code + '">' + name + '</option>';
                       });
                       return s + "</select>";
                      }
                     },
                     formoptions: { elmsuffix: ' *', label: 'Name' }
                    },
                    { name: 'TaxSum', index: 'TaxSum', width: 120 },
                    { name: 'DistributionMethod', index: 'DistributionMethod', editable: true,
                     width: 150,
                     edittype: "select",
                     formatter: 'select',
                     editoptions: {
                      value: "aedm_Equally:Equally;aedm_None:None;aedm_Quantity:Quantity;aedm_RowTotal:RowTotal;aedm_Volume:Volume;aedm_Weight:Weight"
                     }
                    },
                    { name: 'LineTotal', index: 'LineTotal', editable: true, edittype: 'text' }
               ],
  viewrecords: true,
  gridview: true,
  onSelectRow: function (id) {
   if (id && id !== lastSelection) {
    var grid = $("#Freight");
    grid.jqGrid('restoreRow', lastSelection);
    grid.jqGrid('editRow', id, true);
    lastSelection = id;
   }
  },
  height: 150,
  width: 650,
  viewrecords: true,
  gridview: true,
  rownumbers: true,
  loadonce: true,
  scrollOffset: 0
 });

I have observed two things which I don't understand.

Why the width of dropdown is greater than the column width. I want to fix its width based on the column. If size of the column get increased, width of dropdown should also increase.

Please see below screen shot

2. Whenever I click on grid row to edit it calls web service, I don't understand this, why it is calling everytime when the data is fixed for every row for that perticular column.
Can any body guide me on this two topic?
Answer:
your first question

Why the width of dropdown is greater than the column width. I want to fix its width based on the column. If size of the column get increased, width of dropdown should also increase.
The width of dropdown is greater because of the option lists .The text part of the options is too wide to come under the column TaxCode.You can do either thing :-
1)-Increase the TaxCode column width .
  { name: 'TaxCode', index: 'TaxCode', editable: true,
                    width: 100,   //change this as per requirement

2)- Get a horizontal scroll inside the option list (which i don't think is a good idea as jqGrid provides you the way to increase column width.)
You change your TaxCode column width depending upon your dropdown width.Then it will solve your this issue "If size of the column get increased, width of dropdown should also increase."

your second question

Whenever I click on grid row to edit it calls web service, I don't understand this, why it is calling everytime when the data is fixed for every row for that perticular column.
This is happening because you must have called your WebService on jqGrid row click event . Check once and if it is so , then move that piece of code(I guess you are doing this by Ajax) to directly under document-ready(if you want this grid on load) .

One more

Width of the dropdown list is higher than the column
Decrease the width of Quantity column as you will be doing for TaxCode column.
Hope it help !
Comment: clear about the first doubt. but what about 2nd, actually I found this snippet on internet, so I used it. I want call this ajax only once and set the values of dropdownlist instead of calling web service every click on row. My problem is If I get the data from ajax out the jqgrid block then I don't know how to set the option / values for select
Comment: you can do this simply by calling jqGrid in `document-ready` binding all the data you want from web server .you can bind your dropdown lists as well with the data coming from web service
Comment: how to bind this in jqGrid Column. If you closely look in the column "Distribution Method", it has fixed values, How do I set such values at runtime.
Comment: One more thing regarding 1st query, if you closely look into "Distribution Method" text value is very small, but still it is greater then column size. Please look the width of text value  (dropdownlist - figure 2)
Comment: Write an ajax call for getting all the values to bind at runtime.Then in ajax success , write your code for jqgrid and wherever you have to bind data in jqgrid columns whether it's a simple text or dropdown texts just use data parameter of success function.The data parameter will be holding all the required runtime values to be binded inside columns.Hope I am clear this time

dataUrl in jqGrid calls every time


Get controller name in AuthenticationHandler in asp.net core 2.2 web api

Question: I have a basic custom AuthenticationHandler like in this post https://jasonwatmore.com/post/2018/09/08/aspnet-core-21-basic-authentication-tutorial-with-example-api
In the Task<AuthenticateResult> HandleAuthenticateAsync() override I need to to get the controller name.
Injecting IActionContextAccessor in the startup doesn't work:
services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();

The ActionContext property is null (not set yet I think)
HttpContext is available, so should i just try to parse the Context.Request.Path ?
Thanks in advance !
Comment: Does this answer your question? [Get controller and action name from AuthorizationHandlerContext object](https://stackoverflow.com/questions/41103694/get-controller-and-action-name-from-authorizationhandlercontext-object)
Comment: @PBO can you post your code where you use `ActionContextAccessor`? have you tried `services.AddHttpContextAccessor();`?
Comment: are you looking for this: https://github.com/aspnet/mvc/issues/3936 ?
Comment: its an AuthenticationHandler which dont have a context.Resource property :(
Comment: can you show us more code?
Comment: You won't get route data before the Router middleware is invoked.A workaround here is that try to add `app.UseEndpointRouting()` before `app.UseAuthentication()` ( Though it is not recommended ) or call router yourself .refer to https://stackoverflow.com/questions/58016881/getroutedata-always-null-using-aspnetcore-odata-7-2-1
Answer: As I explained in the comment that you won't get route data before the Router middleware is invoked.
For your tutorial code,I find out a solution to create a router and make it runs before the Authentication middleware. In startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        app.UseRouter(routeBuilder => {

            var template = "{controller=Users}/{action=GetAll}/{id?}";
            routeBuilder.MapMiddlewareRoute(template, appBuilder => {
                appBuilder.UseAuthentication();
                appBuilder.UseMvc();

            });
        });

        //add more middlewares if you want other routes
        app.UseAuthentication();

        app.UseMvc();
    }

Get controller name in AuthenticationaHandler (using Microsoft.AspNetCore.Routing reference):
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        var name = Context.GetRouteValue("controller");
        //...
    }


In Python, how do I check if a variable exists?

Question: If "x" exists, then print "x exists".
I ask this because I always get this error:
UnboundLocalError at /settings/
local variable 'avatarlink' referenced before assignment

Comment: -1: If you always get this error, you have **design** issues.  You don't need to "test" for a variable, you need to fix your design.  Why are you "always" getting this error?  What design mistake are you making?
Comment: To reiterate: In general, don't use `locals()`, `globals()`, don't catch `UnboundLocalError`, fix your code instead. Please, read links on scopes, namespaces, naming, and binding  in Python provided in the answer http://stackoverflow.com/questions/575196/in-python-why-can-a-function-modify-some-arguments-as-perceived-by-the-caller-b/575337#575337
Comment: [How do i check if a variable exists in python](http://stackoverflow.com/questions/843277/how-do-i-check-if-a-variable-exists-in-python) has a title that is almost identical to this one. Are the two questions somehow distinct?
Answer: Why do you need to know? If the code breaks because of this, it's probably because the code is wrong anyway and needs to be fixed.
That said, try checking if 'x' in locals() or if 'x' in globals(), as appropriate to where you're expecting it to be.
Comment: While this is indeed the correct answer to your question, please also consider Karl's remark that your code is probably broken if you need to employ a check like this. You are currently treating the symptoms, not the cause, which is always a bad idea.
Comment: Just to clarify, you need to quote the name (`'avatarlink' in locals()`). But the first paragraph is the real solution. +1
Comment: @delnan Of course; added quotes to reflect that.
Comment: -1 You don't need the `if`. Just put the variable's name inside a `try` with and `except NameError:`. Beside being easier, you're checking for existence the way Python does, not restricting it to `locals`, 'globals`, etc.
Comment: @martineau I'm familiar with EAFP, but that seems like a pretty extreme application of the principle :)
Comment: +1: "the code is wrong anyway and needs to be fixed."
Comment: @S.Lott: The code has been fixed...but who/what are you up-voting and quoting -- some deleted comment?
Comment: @Karl Knechtel: Since this is something that obviously shouldn't be happening in the first place, I think using such an "extreme" application of EAFP is completely warranted. It's more *lines* of code, but does the exact same sequence of of lookups that Python normally uses for any name which is what is failing and causing the error. It would also rule-out the possibility that the `'key' in whatever` approach in the answer just looked in the wrong place.
Comment: @martineau: "who/what are you up-voting"?  This isn't a sensible question.  One upvotes an answer.  What else *could* be upvoted?  "some deleted comment"?  This isn't a sensible part of the question.  The quoted words are part of the answer.  Please clarify this comment -- it's really hard to parse.
Comment: @S.Lott: It's possible to up-vote comments as well as answers. I asked the question because I didn't see the words you quoted in the answer probably due to the way it was word-breaking in my browser -- so I didn't know what code was being referred to. Sorry for the confusion and thank you for ultimately telling me what I wanted to know.
Comment: Why should the code be wrong - you are expecting a next page cursor from a remote api, which will not be there if there isnt a next page. It is expected that it shouldnt be there when there isnt a next page. Otherwise remote api would not be JSON compliant.
Answer: As they say in Python, "it's better to ask forgiveness than permission". So, just try and access the variable, and catch the error if it doesn't exist.
try:
    x
    print "x exists"
except UnboundLocalError:
    print "x doesn't exist"

However, I would really like to know why you think you need to do this. Usually, you would always set the variable before checking its value.
Comment: `UnboundLocalError` is a subtype of `NameError`. It would only be raised if `x` was determined at compile time to be a local variable, but hasn't yet been assigned. This can only happen inside a function, and only if there is an assignment to the name elsewhere in the function *and* there is no corresponding `global` or `nonlocal` declaration. Otherwise, a generic `NameError` will result.
Answer: try:
  variable
except NameError:
  print "It doesn't Exist!"
else:
  print "It exists!"

Answer: You may check if x is in globals() or locals().
Answer: In python you really shouldn't be using variables which haven't been set. If need be you can set avatarLink to None.


Await things but make things run in concurrent manner

Question: I'm building an android app with xamarin but this question is related mostly to C# .
In my code I need few things to happen, some of them don't need the other parts and can happen in concurrency manner. some of them should wait until previous action to bring results. I'm doing everything I can in an async manner. Currently it seems that I'm always waiting (in an async manner) for things to finish before the next action.
Here is an example of what I'm trying to do:

Bring the user image from the phone.
Get list of recent phone calls.
Get list of specific contacts from phone.
Get data from the server about number #2 and #3.

Item #1 is not connected to anything else. I need it to happen in concurrent with the others. they don't need to wait until it returns. when it ends it should  update the UI.
Item #2 & #3 should happen in concurrent. When they both end they should update the UI
Item #4 can only happen when #2 and #3 finish.
My  Question is what do I need in order for this kind of requirement to happen. I only ask for guidelines.
Comment: Start t1, t2 and t3 then `await t2; await t3; t4; await t1;` ? Awaiting a series of things in order will work as expected because awaiting a completed task will return immediately, so you'll always only be "awaiting" the longest task.
Answer: The word parallel is mostly used for CPU intensive execution using multiple threads. My guess is that you really mean concurrent, which means that the asynchronous operations are executed simultaneously and not sequentially.
This is a simple layout of how your async methods should interact using Task.WhenAll that enables asynchronously waiting for multiple task to complete:
async Task Foo()
{
    var t1 = First();
    var t2 = SecondAndThirdAndFourth();

    await Task.WhenAll(t1,t2);
}

async Task First()
{
    // Bring the user image from the phone.
    // update UI
}

async Task SecondAndThirdAndFourth()
{
    var t2 = Second();
    var t3 = Third();

    await Task.WhenAll(t2, t3);

    // Update UI

    await Fourth();
}

If you do mean parallel execution then you need to offload work to a ThreadPool thread using Task.Run, but that would only parallelize the synchronous parts of the asynchronous methods.

There's no actual reason to store these tasks in a variable, it's just for clarity. In reality I would write await Task.WhenAll(Second(), Third()) (with proper names)
Comment: I fixed to "concurrent",you are right (hope I wrote it correctly in the sentence)
Answer: I would do something like
var t1 = StartTask(t1);

var t4andUIupdateAfterT2andT3 = new List[ CreateAndNotStart(t4) , CreateAndNotStart(UIUpdateAfterT2andT3) ];

var t2andt3 = new List [ StartTask(t1) , StartTask(t1) ];

t1.ContinuteWith(UpdateUI);

t2andt3.Continuewith(t4andUIupdateAfterT2andT3)

and you do not await for anything


Kernel function from polynomial basis functions

Question: In chapter 3 & 6 of Bishop's Pattern Recognition and Machine Learning, he showed that the equivalent kernel based on eqn (3.62)
$$ k(x,x') = \beta \phi(x)^T (\alpha I + \beta \Phi^T \Phi )^{-1}\phi(x')$$
and the standard kernel based on the feature space mapping eqn (6.10),
$$ k(x,x') = \phi(x)^T \phi(x') = \sum_{j=1}^M \phi_j(x)\phi_j(x') $$
both of which have a sinc like behavior corresponding to Figures 3.11(left) and 6.1(left), see below.

This is quite impossible given that when $x=0$, all $\phi_j(x)=x^j=0$, which implies $\phi(x)^T\phi(x')=0\ \forall x'$.  Is my assumption that $\phi_j(x)=x^j$ wrong?
My understanding is that polynomial basis are global functions, so how can one arrive at the conclusion that its kernel have a local behavior, it's not obvious to me at this point.
Comment: This question will not be answerable unless you reproduce the necessary context, such as equations and figures.
Comment: Added equations and figures.
Comment: Thank you!  The question is now in the "reopen" queue, where reviewers will voted on whether the question is sufficiently clear to be re-opened. (I have voted to re-open the question.)
Answer: I had the same question, and it turns out that the figure is wrong! The corrected one appears on the book errata: Link


How do you customise the Group subscription format

Question: I have assigned user profiles the field Group Type and set it to default as "is group type" so that users can subscribe to each others profiles. This is all fine but i would like to customise the link that allows the users to subscribe, i.e. the display format 'Group subscription'. It currently says: "Subscribe to group", "Unsubscribe from group" or "You are the group manager". Is it possible to customise this text?
Answer: You can make use of the string override module

Provides a quick and easy way to replace any text on the site.


Valor dos Inputs de um formulário

Question: Estou desenvolvendo um formulário com javascript/jquery em que de um pergunta para outra vai para outra pagina e na última página eu tenho que vê todos os dados digitados nas questões anteriores, já tentei com o serializearray(),mas ele só pega os dados da última página, gostaria de saber se tem algum outro método ou mesmo com o serializearray.
Comment: cria um imput hidden com o value do serializearray e passa pra proxima pagina
Comment: Já tentou com localStorage?
Comment: Acredito que a melhor forma para você fazer isso seja com o LocalStorage.
https://developer.mozilla.org/pt-BR/docs/Web/API/Web_Storage_API_pt_br/Using_the_Web_Storage_API
Comment: apenas com JS??
Comment: Sim, tem que ser com javascript, você poderia me mostrar um exemplo?
Comment: Não, na verdade não sei usar o localstorage, pode me dá um help? algum exemplo ou página que me mostre como usar, dei uma pesquisada mas não entendi direito
Answer: Você pode usar o localStorage como falaram!
Para exemplificar fiz esse Codepen para te ajudar!
Segue dois artigos muito bom para entender como funciona o localStorage:
Artigo 1
Artigo 2
Answer: Cara vou te dar um exemplo básico aqui e espero que lhe ajude.
Página que você pega o valor para transferir para outra página:
<input type="text" id="texto">
<button type="button" onclick="setaValor()">Pegar</button>

Página que recebe a váriavel com o valor da página anterior:
<input type="text" id="recebeTexto"> Valor trazido da página anterior

<button type="button">Voltar</button>

Valor dos Inputs de um formulário


WordPress - Added action to a hook disappears in list of callbacks

Question: Encountered a very frustrating bug after many hours of debugging through xDebug. A function that was added to a hook through add_action is missing or inaccessible when do_action is fired from within a plugin(BuddyPress).
The function I am referring to in my theme folder: UpdateSalesForceAvatar
Action: 'bp_members_avatar_uploaded'
Theme code where add_action for the above function is added:
<code>       public static function RegisterActions(): void {
            add_action( 'xprofile_data_after_save', [self::class, 'UpdateSalesforce'] );
            add_action( 'xprofile_data_after_delete', [self::class, 'UpdateSalesforce'] );
            add_action( 'bp_members_avatar_uploaded', [self::class, 'UpdateSalesForceAvatar'], 10, 3);
            add_filter( 'bp_core_avatar_folder_dir', [self::class, 'HandleAvatarFolderDir']);

        }
</code>
Function prototype for UpdateSalesForceAvatar:
<code>public static function UpdateSalesForceAvatar($item_id, $type, $avatar_data) {
</code>
Here are the screenshots and debug information that will hopefully allow someone to help me understand why it is missing when the global $wp_filters is accessed from the plugin.
1st screenshot after add_action

2nd screenshot after future execution of code within BuddyPress

Any and all feedback is appreciated!
Comment: Going to search for remove_all_actions() calls within the theme and attached plugins
Comment: Nope that wasn't it. Going to move the add-action to functions.php instead
Answer: Sometimes you have to try another location, potentially because of plugins interacting with that action.
The solution was more of a workaround, moved the registration of the action instead to functions.php


apache users linux

Question: I'm working with Apache on an ec2 box. I'm trying to generate keys for a user, apache on the system.
However, I don't have permission, because it's ec2. So, I sudo - and get asked for a password for sudo apache. I have no password. I can not set a password.
I use keys to access the systems via these users.
How on earth am I meant to generate a key for apache to use?
Answer: Keys are associated with users by storing them in the authorized_keys file in the .ssh directory of the user's home folder.

Generate your key using ec2-create-keypair
Save the private key (and move it off the server)
Sudo to root (either preface the following commands with sudo, or try sudo -i) - on Amazon's Linux AMI you do not need a password (I don't know what AMI you are using).
Append the public key to the /users/home/folder/.ssh/authorized_keys file.

If the .ssh folder doesn't exist, create it (mkdir /users/home/folder/.ssh) and set permissions to 700.
If the file (authorized_keys) does not exist, you can simply move the public key created by ec2-create-keypair to the correct folder (and rename it authorized_keys). Permissions should be set to 600 or less.
If there is already an authorized_keys file, append to it, using something like cat ec2_public_key.pub >> /users/home/folder/.ssh/authorized_keys

The key is associated with the user by virtue of the fact it is within the user's home folder, and accessible only by that user. You may also need to permit SSH access for the specified user in etc/ssh/sshd_config as well as to change the shell associated with that user.
Comment: Thanks for this particularly helpful guide. I've certainly got further. But, I'm not constantly getting asked for passphrase, which my normal one doesn't work. Just as a side note, I didn't have a home dir for apache. So have created one and chown'd chmod'd as appropriate - I'm getting further here by trying logged into bash and then php -a > still doesnt seem to work in script. But, I can come to that.
Comment: You shouldn't be asked for a passphrase if you didn't set one - ideally, you should pipe the output of the command directly to file to avoid any stray characters. Also, if you are just trying to setup user accounts on the one machine, you can use `ssh-keygen` instead of the ec2 command (the difference being that the keypair won't be registered with AWS). I don't think you mentioned why you were trying to login as Apache - offhand, it seems like an unusual task.
Answer: As described in the manual: http://docs.amazonwebservices.com/AWSEC2/latest/CommandLineReference/ApiReference-cmd-CreateKeyPair.html
Comment: Hmm, this is for creating a generic key pair. Not one attached to a particular user, no? I mean, I have a pem file it can use. This is coming from the fact that apache user is not able to ssh. Ah I dunno. Round in circles. Thanks.

apache users linux


Permission to edit orders, but not delete

Question: The title is mostly self-explanatory: I need a user to have permission to edit an order, but not be allowed to delete it. I don't think the currently defined permissions for orders allow this.
Am I wrong? Is there a workaround/extra module/hackneyed solution you can think of?
Answer: Here's the proper way to do it with
hook_commerce_entity_access

Allows modules to deny or provide access for a user to perform a
  non-view operation on an entity before any other access check occurs.
Modules implementing this hook can return FALSE to provide a blanket
  prevention for the user to perform the requested operation on the
  specified entity. If no modules implementing this hook return FALSE
  but at least one returns TRUE, then the operation will be allowed,
  even for a user without role based permission to perform the
  operation.
If no modules return FALSE but none return TRUE either, normal
  permission based checking will apply.

Example
/**
 * Implements hook_commerce_entity_access
 */
function MODULE_commerce_entity_access($op, $entity, $account, $entity_type) {
  if ($entity_type == 'commerce_order' && $op == 'delete') {
    // Require administer orders permission to delete orders
    if (!user_access('administer commerce_order entities', $account)) {
      return FALSE;
    }
  }
}

Answer: There is a module for that™:
https://www.drupal.org/project/commerce_deletepermissions
Have fun!
Answer: In the end I settled on the worst kind of solution. I added a little jquery script that selects the "Delete" link (Drupal commerce helpfully gives it its own css class) and hides it. It's stupid, but the customer is happy.
Comment: Using the `hook_commerce_entity_access()` is the right way and should be accepted answer above.


How to use ks test for 2 vectors of scores in python?

Question: I am trying to figure out how to determine whether to reject or not the null hypothesis using ks-test.

In matlab there is a function named kstest2 decides if it should reject $H_0$. I want to use python scipy function
ks_2samp but it returns the p-value and the $\alpha$, how can I
determine if one should reject $H_0$ given those 2 parameters ?
If I have 2 vectors of scores per day, how can I use Matlab/python kstest2 to see if the are distributed the same?
Is there a clean way to change the scores vector to a continuous distributed vector?
Comment: Simply compare the p-value to your significance level. If your p-value is lower than (or equal to) your significance level (your chosen type I error rate), you should reject the null hypothesis.
Comment: @Glen_b do you mean if $\alpha > p-value$ reject $H_0$ ?

Does $D statistic$ is the same as $alpha$
Comment: Yes and no. Or more strictly, since $\alpha$ is fixed (chosen by you prior to the test), the $\alpha$ is the thing being compared against, so it's the way around I initially stated. And if they happen to be equal you also reject. So I mean it as I said it in words before: if $\text{p-value}\leq\alpha$ you should reject $H_0$. No, $D$ is NOT $\alpha$. $D$ is something you calculate from the sample, while $\alpha$ is something you would normally choose before you even collect the sample and certainly before you look at it. http://en.wikipedia.org/wiki/Statistical_significance
Answer:
Simply compare the p-value to your desired significance level. If your p-value is less than (or equal to) your significance level (your chosen type I error rate, $\alpha$), you should reject the null hypothesis. (You may need to brush up your understanding of how hypothesis testing works.)
If you mean you want to combine information across many days, it depends on whether the days are going to share a distribution (within the two different groups of things being compared in the test) or not, but one approach that works in either case would be to test the distribution of p-values for uniformity against the alternative that it's typically smaller. That would give an overall test that would apply over many days. However, if you're testing every day, you may want to consider the properties of such a procedure.
No. If you don't have continuous distributions you probably shouldn't be doing a KS test at all; it won't have the usual properties (e.g. type I error rates will be too low, power will be low).
Comment: Which test can be used for discrete distributions instead of ks-test?
Comment: The search function will find you answers related to this, like [this](http://stats.stackexchange.com/questions/48317/kolmogorov-smirnov-with-discrete-data-what-is-proper-use-of-dgofks-test-in-r) or [this](http://stats.stackexchange.com/questions/13326/can-i-use-kolmogorov-smirnov-to-compare-two-empirical-distributions). There are other possibilities, but it's really a new question.


Preenchimentos de campos obrigatórios

Question: Como eu faço para obrigar que entre dois campos, pelo menos um deles seja obrigatório (esteja preenchido)? Por exemplo, os campos Celular e Telefone não podem ser salvos vazios, somente um deles.
Meu código:
//..
}
else ((txtNome.Text == "") || (maskedCPF.Text == "") || (maskedCEP.Text == "") || (txtNum.Text == "") || (maskedCelular.Text == "") || (txtTelefone.Text == ""))
{
  MessageBox.Show("Os Campos com * são de Preenchimentos Obrigatórios!");
}

Neste caso ele está obrigando os dois campos (Celular e Telefone) a serem preenchidos. Eu quero que seja possível salvar com o campo celular preenchido e o campo telefone vazio ou vice-versa.
Answer: Seria algo assim:
else ((txtNome.Text == "") || (maskedCPF.Text == "") || (maskedCEP.Text == "") ||
    (txtNum.Text == "") || ((maskedCelular.Text == "") && (txtTelefone.Text == "")))

Usando o operador de and (&&) só se os dois estiverem vazios é que há algum problema.
Ou, dependendo do caso:
if ((txtNome.Text != "") && (maskedCPF.Text != "") && (maskedCEP.Text != "") &&
    (txtNum.Text != "") && ((maskedCelular.Text != "") || (txtTelefone.Text != "")))

Coloquei no GitHub para referência futura.
Comment: É isso mesmo.vlw.
Comment: @enzo dê uma olhada no [tour] além de aceitar uma resposta você pode votar em tudo que achar interessante no site todo.
Comment: @Maniero por qual motivo as condições estão entre parenteses?
Comment: @MateusDaniel Provavelmente porque a pessoa quer deixar mais explícito, eu não faria.
Comment: @Maniero ops, perdão, pensei que isso fazia parte da sua solução, agora que vi que já tava assim rs'
Answer: Eu consegui de uma maneira diferente, ficou assim:
protected void Page_Load(object sender, EventArgs e)
{
 if(!IsPostBack)
 {
   txtNome.Attributes["required"] = "true";
   masked.Attributes["required"] = "true";
 }
}

Preenchimentos de campos obrigatórios


Area under bijective decreasing function

Question: Let $ f:[2,4]\to[3,5]$ be a bijective decreasing function,then find the value of $\int_{2}^{4}f(t) dt-\int_{3}^{5}f^{-1}(t) dt.$
I am not sure whether $\int_{2}^{4}f(t) dt=\int_{3}^{5}f^{-1}(t) dt$ or not.As $f(t)$ and $f^{-1}(t)$ are inverse of each other,so they must be symmetric about line $y=x$.Will this concept be used here or some other method be used.Can someone guide me through?
Comment: Try drawing a single diagram showing the area of both integrals. Now compare with the area of the natural rectangles.
Comment: Following Simon S's suggestion informally: The area under the graph of $f$ over $[2,4]$ is $\int_2^4 f(x)\,dx$. The area to the left of the graph of $f$ and to the right of $[3,5]$ on the $y$-axis is $\int_3^5 f^{-1}(x)\, dx$. The difference will leave you with two rectangles.
Answer: As $f$ is a bijective decreasing function.Therefore,using basic definition of decreasing functions i.e.if$x_1<x_2\Rightarrow f(x_1)>f(x_2)$.Therefore,$f(2)=5,f(4)=3$
$\int\limits_{2}^{4}f(t)dt-\int\limits_{3}^{5}f^{-1}(t)dt=\int\limits_{2}^{4}f(t)dt+\int\limits_{5}^{3}f^{-1}(t)dt=4\times 3-2\times 5=2$
Using,$\int\limits_{a}^{b}f(t)dt+\int\limits_{f^{-1}(a)}^{f^{-1}(b)}f^{-1}(t)dt=bf^{-1}(b)-af^{-1}(a)$


expected value of money for coin toss

Question: I play the following game using a coin that lands heads with probability $p$. I start with
$X_0$ = $1$ and at each stage I gamble all I have on the toss of the coin. If it lands heads I end up
with twice what I started with; if it lands tails I lose everything. All coin tosses are independent.
(1) With $X_n$ denoting how much money I have after the nth toss, find
$E[X_{n+1}|X_n = k]$
in terms of k.
(2) Find $E[X_n]$ for all $n$.
My attempt at solution:
(1) If we know that $X_n = k$, and the $n+1$ toss will be either H or T with probability $p$ and $1-p$ respectively, that means Xn+1 will be either 2k or 0 respectively. So $$E[X_{n+1}|X_n = k] = (p)(2k) + (1-p)(0) = 2pk$$
(2) Not sure if I have the right thought process but $E[X_n] = 2p(X_{n-1})$ because there's a $p$ probability of doubling $X_{n-1}$ and $1-p$ probability of getting $0$. So using the same logic as in (1), it would be $2p(X_{n-1})$.
I think my reasoning for (2) is correct, but I'm not sure if that's the final answer.
Answer: Your both answers are correct (ignoring the abuse of notation in the second part that $E[X_n]$ cannot be equal to $2p X_{n-1}$ since $X_{n-1}$ is random, but $E[X_n]$ is not).
For (1), you've already written the correct solution. For (2), we'll just use Law of Iterated (Total) Expectation:
$$E[X_n]=E[E[X_n|X_{n-1}]]=E[2pX_{n-1}]=2pE[X_{n-1}]$$
Going towards $n=0$, we have:
$$E[X_n]=2pE[X_{n-1}]=(2p)^2E[X_{n-2}]=\ ...\ =(2p)^nE[X_0]=(2p)^n$$
I can suggest another solution for the second part by the way:
In $n$-th toss, you'll have either $2^n$ dollars or $0$ dollars. And, you'll get $2^n$ only if your all tosses are success, i.e. with probability $p^n$. In any other case, i.e. $1-p^n$, you'll get $0$ dollars. So, the expectation will be $p^n2^n+(1-p^n)0=(2p)^n$.

expected value of money for coin toss