Get difference between two dates programatically

Question: In summary:
On a Drupal 8 project, i am trying to programatically get the difference between two different times (current time - Node creation time)
Use case:
I have "nodeabc" already available on the site.
When a specific webform is submitted and by using a custom webform handler, I want to get the difference in minutes between current time and nodeabc creation time.
Say nodeabc was created on: 24/06/2019 08:00 AM and the webform is being submitted on: 24/06/2019 07:00 PM, so the difference between both times will be: 660 minutes.
I have already loaded the node by its nid but how to continue in achieving the above ?
UPDATE #1:
From @Prestosaurus answer, I did the below in my webform custom handler php file:
$nid = '125';
$node = \Drupal\node\Entity\Node::load($nid);

$creationtime = $node->getCreatedTime();

// Get "Time Diff Since" creation time.
$creationsince = \Drupal::service('date.formatter')->formatTimeDiffSince($creationtime);

the above code returned: 7 hours 30 minutes which is good but then I added the below code to the above one:
$totalamount = $creationsince * 5000;

But while testing it returns a php error InvalidArgumentException: $string ("35000") must be a string.
I believe I am half way to the answer but still need to convert the $creationsince value to 450 minutes instead of 7 hours 30 minutes.
Is that doable ?
Comment: Are you trying to achieve a human-readable difference like "11 hours ago"? Or do you want a numeric value in seconds like "39600"?
Comment: @aaronbauman actually i need both ! (1) i want a human-readable difference like "7 hours 30 minutes" so i can save the value in a text box field for users to read it. (2) i want also a numeric value **in hours** like 7.6 so i can multiply this value (Ex: 7.6) by another numeric value and save the results in another text box... in other words, say that a user get pay 5$ for 1 working hour, when the user will work from **24/06/2019 08:00 AM** until **24/06/2019 07:15 PM** so he worked *11 hours 15 minutes* which means **11.25** hours and so `11.25 × 5 = 90$`
Comment: $creationsince is a string. Try: `$minutesPassed = round(($submission->completed->value - $createdTimestamp)/60) . ' minutes';`. There may be D8 methods for this, but I have not found them...
Answer: Given a node, $node:
$diffSeconds = time() - $node->getCreatedTime();
$diffHours = (($delta_seconds / 60.0) / 60.0);
$formattedTimeDiff = \Drupal::service('date.formatter')
  ->formatTimeDiffSince($node->getCreatedTime());

$diffSeconds is the number of seconds between node creation time and now.
Thus $diffHours is the number of hours (float) between node creation time and now.
formatTimeDiffSince() converts this to a human readable value, e.g. "1 hour 15 minutes"

For the webform timestamps:
function MYMODULE_preprocess_node(&$variables) {

  $createdTimestamp = $variables['node']->getCreatedTime();

  $webform_submissions = \Drupal::entityTypeManager()
    ->getStorage('webform_submission')
    ->loadByProperties([
    'entity_type' => 'node',
    'entity_id' => $variables['node']->id(),
  ]);

  $submission_timestamps = [];
  $timeDiffs = [];
  $timeAgos = [];

  foreach ($webform_submissions as $submission) {
    $submission_timestamps[] = $submission->completed->value;
    $timeDiffs[] = $submission->completed->value - $createdTimestamp;
    $timeAgos[] = \Drupal::service('date.formatter')
      ->formatTimeDiffSince($submission->completed->value);
  }

}

Webform timestamps cover ->created, ->completed, and ->changed.
Comment: Can you please explain how to make the `current time` not static ?
Comment: The above is a handy D8 method, but it sounds like you want to compare two static time stamps. If I understand correctly, and this will ultimately be shown in node template, I believe you just need the node created date and the associate webform submission date. These would both be acquired in hook_preprocess_node I would assume. After that sounds like standard manipulation with math on the time values.
Comment: Answer has been edited. Again, for the human readable created against submission time, will need a little more leg work, but that's just formatting.
Comment: please see my edit to the question (**Update #1**), I believe i am half way to the answer!


Por que new AlertDialog.Builder(getApplicationContext()).create() não funciona?

Question: Já venho observando esse problema a algum tempo, e sempre tenho que manter uma instância a Activity atual, ao invés de manter apenas uma instância ao Context, e até então não entendi o por que, já que o método AlertDialog.Builder(Context context), exige como parâmetro de inicialização apenas uma instância do Context e não da Activity.
Então se eu faço o seguinte código:
AlertDialog alert = new AlertDialog.Builder(getApplicationContext()).create();
alert.setTitle("Title");
alert.setMessage("Message");
alert.show();

É gerado o seguinte erro em execução:
04-22 13:06:55.585: E/AndroidRuntime(3014): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.appteste/com.example.appteste.MainActivity}: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application

Já se eu passo a Activity como parâmetro ao invés do Context, tudo funciona como o esperado:
AlertDialog alert = new AlertDialog.Builder(this).create();
alert.setTitle("Title");
alert.setMessage("Message");
alert.show();

Testei nas seguintes versões do Android: 4.0.3 e 4.4.2
Minhas duvidas são as seguintes:

Isso é um problema (Bug) do Android?
Estou fazendo algo de errado?
Por que isso acontece?

Obs: Para efeitos de testes, os códigos apresentados, foram executados dentro do método onCreate(Bundle savedInstanceState) da Activity.
Comment: Isto é mais uma de várias que o Android tem. Você não está a fazer nada de errado, desde que passe um Activity Context. Isto faz-me lembrar aquela frase do Ford: "Você pode escolher qualquer cor para o carro, desde que seja preta!"
Comment: @ramaral, então não há nada que um programador possa fazer? O Android está pedindo um `Context`, mas na verdade ele quer uma `Activity`, é isso que você quis dizer né? E terei que manter uma instância da Activity onde eu pretender chamar um   `AlertDialog`, sem choro certo?
Comment: Pela pequena pesquisa que fiz não há nada a fazer. Activity é um Context tal como ApplicationContext, mas parece que AlertDialog necessita mais do que um simples Context, necessita de algo que Activity acrescenta. Leia [isto](http://stackoverflow.com/questions/5436822/why-does-alertdialog-buildercontext-context-only-accepts-activity-as-a-paramet)
Comment: @ramaral, lendo um pouco mais, me parece ser mais confuso que no inicio, por que diabos, eles fizeram uma estrutura dessa forma. Acredito, que se isso é um bug do Android, é um erro de Designer horrível, pois dificulta o entendimento de uma estrutura que poderia ser muito mais simples, e uma brecha para bugs, pois qualquer desenvolvedor desatento (como eu) pode criar um código que passe um `Context`, e se isso não for pego nos testes, poderá ir estourar no usuário final. Não entendo o por que dessa escolha pelos desenvolvedores do Android.
Answer: 1 - Isso é um problema (Bug) do Android?
Aparentemente não: getApplicationContext() deve ser usado se você precisar de um contexto cujo ciclo de vida é separado do contexto atual , que está ligada ao tempo de vida do processo ao invés do componente atual. Mais detalhes na documentação.
2 - Estou fazendo algo de errado?
Provavelmente sim: Então como você está usando uma Activity e criando o seu AlertDialog dentro dela, o contexto desse alert será sua activity. Baseado nesta resposta.
3 - Por que isso acontece?
O raciocínio é que o AlertDialog não tem uma vida fora da sua Activity.
Sendo assim ele precisa do contexto em que foi criado, como o getApplicationContext() é diferente do this da sua activity você terá esse Exception.
Answer: Este é um exemplo de um AlertDialog.
AlertDialog.Builder ADBuilder = new AlertDialog.Builder(MainActivity.this);
ADBuilder.setIcon(R.drawable.ic_dialog_info);
ADBuilder.setTitle("TÍTULO DO ALERTA");
ADBuilder.setMessage("MENSAGEM DO ALERTA");
ADBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
        // CÓDIGO QUE SERÁ EXECUTADO SE O USUÁRIO PRESSIONAR O BOTÃO SIM
    }
});
ADBuilder.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
        // CÓDIGO QUE SERÁ EXECUTADO SE O USUÁRIO PRESSIONAR O BOTÃO NÃO
    }
});
ADBuilder.show();

Comment: @JhonasKenneBoeno evite simplesmente postar o código. Mesmo que este já tenha sido reportado como insuficiente para a questão, elaborar uma resposta propriamente dita, detalhando processos, comentando o script e tudo o mais que se julgar necessário é de grande valia para a comunidade pois, hoje, pode não servir para ninguém, mas amanhã ou depois, algum usuário trazido pelo Google pode ter sua dúvida respondida antes mesmo de tê-la perguntado.
Comment: Jhonas, obrigado pela atenção, mas minha duvida, não é de como criar um `AlertDialog`, mas sim sobre o problema(_bug_), ao passar o `getApplicationContext()` como parâmetro ao invés da `Activity`.
Answer: Pelo que eu sei, não existe getApplicationContext() ou não é aplicável a AlertDialog.Builder. Tenta usar esse código minimizado feito por mim:
AlertDialog.Builder(this)
    .create()
    .setTitle("titulo")
    .setMessage("msg")
    .setPositiveButton("funcao 1",
                       new DialogInterface.OnClickListener()
       {
          @Override public void onClick(DialogInterface _dialog, int _which)
          {
             //codigo
          }
       })
    .show();


Alert after form radio has been selected

Question: I am trying to use drupal ajax to test if an email address from the form it is in my database. For that i have altered the form and added the following line to the element:
   $form['field_radio']['#ajax'] = array
    (
       'callback' => '_get_member',
       'progress' => array('type' => 'throbber', 'message' => '')
    );

and the callback function:
function _get_member($form, $form_state){

     $sid = $form_state['values']['details']['sid'];
    $commands[] = ajax_command_alert("Hello World");

    return array(
    'type' => 'ajax',
    'commands' => $commands
  );
}

As you can see from the callback i just want to return an alert message but it does not work. The callback is called because i have tested using watchdog but the alert popup never fires. Why ?
Answer: 'wrapper' is a required key for #ajax on form elements, you're probably just missing that. From the docs

This property is required for using AJAX requests in on a form element

If you add the wrapper it should work:
$form['field_radio']['#ajax'] = array (
   'callback' => '_get_member',
   'progress' => array('type' => 'throbber', 'message' => ''),
   'wrapper' => 'some-element-id'
);

Comment: i have added the wrapper key but still the alert is not fired! Is there a way to grab variables from the result with javascript ?
Comment: In the ajax response i found the text : "command":"alert", "text":"Based on your email, you are not a Member yet!"


building webkit on windows phone 8

Question: I have some html containing WEBKIT content which needs to be rendered on Windows Phone 8 browser and Windows 8 Store apps webview. As windows 8 and wp8 browser control doesn't support webkit.
is there any way where:

I can map webkit to IE specific tags internally in code and then calling Webview.NavigateToString(html).
As Webkit is Open source, Can I build webkit to dll and use it as a control in my WP8/W8 to render Webkit html?

If there is any better way other than this, please suggest...
Thanks!
Comment: What do you mean by "Webkit content" exactly? HTML, CSS, JS? Can you show some sample code?
Answer: By webkit "content" and "specific tags" I'm assuming that you're referring to <code>-webkit</code> specific prefixes in the CSS.

There is no way to map these to anything that can be automatically converted to the IE specific equivalent.
Building your own browser (which is essentially what you'd be doing if you got the webkit code compiling for the phone) is likely to be masses of work. Much more than modifying the code you are displaying.

The best approach is to simply include the IE equivalent version of the vendor specific extension where one exists. This is the same as you would do if you had content that you wanted to take advantage of such extensions and run on multiple browsers. (i.e. Firefox and Opera also.)
You should also seriously consider if you need things to look identical on multiple devices. (Hint. you don't.) Your time may be better served by ensuring you are displaying content which looks appropriate on the appropriate device, rather than trying to use the code for getting something to display in a specific way on one device/browser to work on another.

building webkit on windows phone 8


In SQL, how do I work with a table that has to have many (20+) foreign keys?

Question: So, let's say I want to create a database to work with soccer games. If I want to have a table called matches then how do I avoid having to write something like player1_fk, player2_fk [...] player22_fk?
Is there something like an array for SQL?
Comment: "*Is there something like an array for SQL*" - this question usually indicates a lack of understanding what normalization is about. Apart from that: support for arrays depends highly on the DBMS being used. Most have no array support whatsoever others have terrific support for them. So you will need to tell us which DBMS you are using (Postgres, Oracle, SQL Server, ...)
Comment: What is your current data model and what do you want to model?
Comment: seems you need an n:m relation, so use an extra table player_per_match
Comment: It is unclear what you want to do, add the details @Smutje asks, please.
Comment: Thanks for the advice guys, I decided to go for an intersection table. Also, thanks for the warning, I am going to read up on normalization as I am clearly  lacking in this department.
Answer: It is called a link table:
<code>Matches
  ID

Players
  ID

PlayersToMatches
  Match_ID
  Player_ID
</code>
This is how you usually store many-to-many relations in a relational database.


How to fix a broken or missing block?

Question: On a Drupal 8 site, I see an error on a block which says:

This block is broken or missing. You may be missing content or you might need to enable the original module.

How can I resolve this error?
Answer: You have created a Custom block and the custom block was placed in a region, then you lost the custom block maybe was deleted or you made a Config Export from one environment and a Config Import in other. So the custom block is no longer exists but in the Block layout page (admin/structure/block), the references exist.
So, remove the missing Block from the Block layout page (admin/structure/block) and create again the Custom block and place it again in the region.
There is a core issue open discussing this problem: https://drupal.org/project/drupal/issues/2756331
This can also be overcome by using this module: https://www.drupal.org/project/recreate_block_content
Comment: @lukedekker This is the core issue: https://www.drupal.org/project/drupal/issues/2756331. Someone's written a module to help with the process in the meantime: https://www.drupal.org/project/fixed_block_content
Comment: Thanks, What can be done to resolve the issue? Do I need to recreate the block with same ID/class?
Comment: @madankumar see the las part of the answer.
Comment: Thanks for the suggestion, I will try this out and let you know.
Comment: The problem here is that the _instance_ of the block is content while the configuration of the block is config. This means that the block itself doesn't get transferred between environments while the config for the block does. I'm pretty sure there is a Drupal Core issue about this somewhere.
Comment: @lukedekker that's the idea, I forgot to add this to my answer, please feel free to modify my answer with your comment.
Comment: @lukedekker can you explain more bit on instance/config in Drupal 8? or any link is better
Comment: Just posted an answer because I didn't want to totally hijack your answer @AdrianCidAlmaguer. Thanks, Clive for doing the legwork of looking these up.
Comment: Maybe - but in the scenario I just created, I was trying to load the Powered by Drupal block... and since I also (successfully) displayed it on the another page (separate from the custom page in question- I don't think the block is either lost or deleted.
Comment: It is interesting that neither here nor in the issue  drupal.org/project/drupal/issues/2756331 there is no ready-to-use solution to cover this case. So far, this is still not resolved and everyone is rolling their own approach.
Answer: The placement of the block is stored as configuration. This is what gets exported and synced between environments. The actual content of the block is considered exactly that: content. This means that when you import your new configuration into a different environment (or delete the block and then re-import the configuration) there is a mismatch between the configuration for the block and the actual block instance (which no longer exists).
To resolve this issue, you simply need to delete the configuration for the missing block and then recreate the block. This allows your site to resolve the discrepancies.
Another option would be to use the fixed_block_content contributed module to manage this process for you.
There is a Drupal Core issue discussing this very thing. https://drupal.org/project/drupal/issues/2756331
Answer: I had the same problem with Views. After trying a different theme, some of my Views blocks were gone. I checked and the actual Views was disabled. I was able to restore it by going to the views page and "enabling" the Views and all the blocks displayed as expected.
Comment: That is right, thank you, your comment helped me. I was pulling my hair because the blocks in my view simply wouldn't display as available in the blocks admin interface. After I read your comment, I checked and... That was the reason, the view had been disabled by Drupal (I don't know exactly why, but I think it had to do with a field I had deleted from my content type, but was still available in the view).
Answer: This happens because when a block is created, a unique id is generated (uuid). This can be seen from the block_content table.
A custom block is a piece of content similar to a Node, so if you create a block in one environment (dev for example) and recreate the block manually on a different environment (Production or QA). The block will have a different uuid.
The Configuration Synchronization will be looking for an uuid that doesn't exist. In order to fix this, you need to import the data from the database. Or simply update (id and uuid) on the following tables:
block_content;
block_content_field_data;
block_content__body;
block_content_field_revision;
block_content_revision;
block_content_revision__body;
Answer: I encountered this myself, using modules or patches did not work for me.
Doing the Database fix route, thinking this has something to do with UUIDs or IDs. Everything seems fine.
What worked for me to fix this is to modify the block_content_field_data table and made sure all the existing blocks for the field reusable is not NULL
Then do a cache clear for the site and you'll see the missing custom blocks. So far this workaround worked for me.
Oh and i'm at 8.6.13 at this time.
Answer: My problem was caused by a block existing only on dev and then configuration pointing to a block that did not exist elsewhere. It came up in Layout Builder. I'm on Drupal 8.7.6 and I was able to simply go in to the layout builder, remove the bad block reference, re-add the correct block and the problem was solved. I just had to be sure to re-export my configuration and update my repo so as not to recreate the problem.
Answer: (Expanding on Marcelo's answer)
Steps to reproduce:

Block is created
Block is added to Block Layout
Configs are exported
Block is deleted (or does not exist on target)
Configs are imported to target
Import contains: [warning] The "block_content:[UUID]" was
not found

Steps to fix:

Copy the uuid from the error
Find the correct block in the database table - block_content*
Update the uuid of the block in block_content with the one from the error
Make sure the block is removed from the Block Layout
Re-import configs

*It can be difficult to figure out which entry in the block_content table is the correct one.  If necessary, copy the block data and metadata somewhere, delete the block and then re-add it. The highest id number in the block_content table will now be the newly created block.  Change the uuid on this entry.
Answer: Make Sure the BLOCK ID is the same as in the productions database.
I solved this issue which occurs while importing the production database to lower environments by deleting the block and creating/configuring it again with the same block id that is in the production database.
Answer: If you're familiar with drush, you can remove a custom block and related config with two commands. The first one removes the custom block entity.
drush entity:delete block block_machine_name

The second one removes the block instance from the block config. This is what you see on the Block Layout view.
drush config:delete block.block.block_layout_machine_name

Answer: Try the Content synchronization feature from the Mix module, which allows you to export/import and recreate block contents, menu item links and taxonomy terms between environments (sites)
You can easily choose which items to sync via UI like below:

How to fix a broken or missing block?


Why does the following set have no subspaces but {0} and itself?

Question: Here's the statement:

The following set, $V$, only has subspaces $\{0\}$ and $V$.
      $$V=\{f(t) \colon \mathbb R \to \mathbb  R \mid f'(t) = k\cdot f(t) \text{ where } k \text{ is a constant}\}$$

I'm having trouble understanding why there are no other subspaces.  Why is this the case here?  Examples are welcome.  I provided a definition of "subspace" in the comments.
Comment: You need two things.  Firstly, that a one-dimensional vector space has no subspaces except {0} and itself.  Secondly, that your V is a one-dimensional vector space.  Can you do either of these?
Comment: By the way, we need to assume that the constant $k$ is the same for each element of $V$, otherwise $V$ is not a vector space. It is misleading, I think $k$ should be declared outside the set.
Comment: For example, $f(x) = e^x + e^{2x}$ does not satisfy $f'(x) = k \cdot f(t)$ for any real number $k$, although the equation holds for $e^x$ and $e^{2x}$.
Comment: Subspace:
U is a subspace of V if U is a subset of V and:
1) U is nonempty
2) U is closed under addition
3) U is closed under scalar multiplication
Comment: While it may seem 'obvious' a subspace of (some finite dimensional space) V has to have dimension less than or equal to V, it is actually not an entirely trivial proof - while simple it is rather tedious. For instance, you actually have to prove any subspace does have a basis (via explicit construction) then prove that a set of linearly independent vectors can not have greater cardinilty than a set of spanning vectors. So, for this example, it's best to spot V =  and say if x =/= 0 is in U then ...
Comment: hint: x is of the form Aexp(kt) for non-zero A; why is A non-zero? If A is non-zero what does it have? So why is exp(kt) in U? Does this mean Cexp(kt) is in U for any C?
Answer: Hint: $V$ is the set $\{ C e^{kt} :C\in \Bbb R\}$. So $V$ is the linear span of the single element $f(t)=e^{kt}$.
Answer: HINT $\rm\displaystyle\ \begin{align} f{\:'} &=\ \rm k\ f \\ \rm \:\ g' &=\ \rm k\ g \end{align}\ \Rightarrow\ \dfrac{f{\:'}}f\: =\: \dfrac{g'}g\: \iff\: \bigg(\!\!\dfrac{g}f\bigg)' =\ 0\ \iff \ g\: =\: c\ f,\ \ \ c'\: =\ 0,\ $ i.e. $\rm\ c\:$  "constant".
This is a special case of the the Wronskian test for linear dependence.


Append não funcionando corretamente em um Select apó requisição AJAX

Question: Estou precisando fazer com que ao completar a requisição AJAX o jquery insira as options em um select porém ao fazer isso as options não aparecem ao clicar porém ao inspecionar mostra que estão presentes no select
Script da requisição:
$(document).ready(function(){

        $.get("http://localhost/infinityy/assets/php/list-categories.php", function(data){
            categories  = JSON.parse(data);
            var select = $("#category");

            $(categories).each(function(){
                 var option = $("<option>");
                 option.attr("value", this.id);
                 option.text(this.name);
                 console.log(option);

                 select.append(option);

            });
        });

 });

Select:
<form  action="assets/php/add-category.php" method="post">

         Categoria
         <select id="category" name="category" class="selectpicker" data-title="Categoria" data-style="btn-default btn-block" data-menu-style="dropdown-blue" required>

 </form>

Resultado mesmo clicando não aparece as options

**Ao inspecionar o Select: **
Comment: Visto que você está usando php, é possível fazer o que você quer com um load, seria interessante pra você? Ou tem que ser usando append?
Comment: O que seria o Load?
Comment: Uma outra função javascript para carregar as options de outra forma. Se essa for uma opção viável, eu posso fazer uma resposta com explicação de como usar essa função.
Comment: Não conheço essa função, poderia me mostrar?
Answer: Quando você adiciona opções dinamicamente ou muda o estado do select usando o select picker, você precisa chamar uma função que atualiza o elemento, adicione essa linha após adicionar as opções.
$('.selectpicker').selectpicker('refresh');

Mais informações: https://silviomoreto.github.io/bootstrap-select/methods/#selectpickerrefresh
Answer: A função load tem uma documentação que pode ser vista aqui.
Ela irá carregar conteúdo dentro do parâmetro passado nela. Um exemplo com o seu caso seria
Javascript:
$("#category").load("http://localhost/infinityy/assets/php/list-categories.php >", function () {
});

No php você faz a consulta que você faz do mesmo modo, mas ao invés de retornar json, retorna a variável que você quiser para uma view .php ou .phtml
HTML:
<?php foreach($opcoes as opcao): ?>
    <option value="<?php echo $opcao['valor']?>"> <?php echo $opcao['nome']; ?></option>
<?php endforeach; ?>

Dessa forma, irá percorrer o array $opcoes que contem o valor e nome da sua opção e preencher o html dentro do seu select.
Comment: Tendo em vista de que é em php acho não funcionaria para o meu caso, pois estou fazendo com que o usuário possa adicionar dinamicamente as options enviando requisições ao servidor
Comment: Conhece alguma outra solução?
Comment: @LuhanSalimena é possível fazer utilizando essa função normalmente, toda vez que uma requisição for enviada ao servidor, você executa o `load`


How to secure a configuration file in IBM Cloud

Question: I have a Flask python app running on IBM cloud. The app needs some configuration parameter which it gets from a configuration file. I need to encrypt the configuration file using a symmetric key. How can I do that and where I can store my decrypt key? Ideally I don't want to hard code it into my code.
Answer: 12 Factor question. Embed it in the app's deployment environment variables and read the value at runtime.


Typescript - Dynamic Generics Type

Question: I don't know what exactly to call this problem but this is my case.
I want defaultValue to automatically get type based on id value.
type User = {
  name: string;
  age: number;
};

type PropConfig<T, K extends keyof T> = {
  id: K;
  label: string;
  defaultValue: T[K];
};

const config: PropConfig<User, 'age'> = {
  id: 'age',
  label: 'Age',
  defaultValue: 18,
};

This is what I want:
type PropConfig<T, K = keyof T> = {
  id: K;
  label: string;
  defaultValue: T[K]; // Error here
};

const config: PropConfig<User> = {
  id: 'age',
  label: 'Age',
  defaultValue: 18,
};

Can someone help me?
Answer: TypeScript doesn't have partial type argument inference as proposed in ms/TS#26242 so there's no way to specify T while having the compiler infer K, at least not without workarounds involving curried helper functions or dummy parameters (see Typescript: infer type of generic after optional first generic for more info).
Luckily, I don't think you want PropConfig to be generic in K.  Instead, you want PropConfig<T> to be a union of the possible types for each K in keyof T.  That is, you want to distribute the type across unions in keyof T.  There are a number of ways to do that, but the one I usually do is to make what's called a distributive object type, as coined in ms/TS#47109.  It looks like this:
type PropConfig<T> = { [K in keyof T]-?: {
  id: K;
  label: string;
  defaultValue: T[K];
} }[keyof T]

I immediately index into a mapped type, producing the following for PropConfig<User>:
type PropConfigUser = PropConfig<User>;
/* type PropConfigUser = {
    id: "name";
    label: string;
    defaultValue: string;
} | {
    id: "age";
    label: string;
    defaultValue: number;
} */

which is the type you want:
const config: PropConfig<User> = {
  id: 'age',
  label: 'Age',
  defaultValue: 18,
};

Playground link to code
Comment: This was really helpful, but led to me finding what I think is a bug. https://github.com/microsoft/TypeScript/issues/50147

Typescript - Dynamic Generics Type


How to disallow StyleSheet creation in ESLint?

Question: For certain folders I would like to enable StyleSheet.create() whereas for other folder I would like to disallow them.
Now I figured out how to override ESLint rules per folder, but how do I disallow StyleSheet.create()?
Answer: A way that I used is to restrict the import of StyleSheet. It is even possible to provide a message with the ESLint warning.

"no-restricted-imports": ["warn", {
  "paths": [
    {
      "name": "react-native",
      "importNames": ["StyleSheet"],
      "message": "Please import StyleSheet only in *.styles.ts files within the components folder."
    }
  ],
}],

Then for the override:
overrides: [
  {
    files: [
      'app/components/**/*.styles.ts',
    ],
    rules: {
      "no-restricted-imports": ["error", {}]
    }
  }
],


Using bit masks to control large set of fields in a form with categories

Question: I've only used bitwise operators and masks once in SQL Server many years ago. It was simple 2/4/8/16 flag switch. This time, after having read numerous articles and Wikipedia article about masks, I still can't wrap my head around this. It could be that my thinking here is totally incorrect and I can't use masks but so far I also didn't find a definitive reason why not.
I have 4 categories in my form in PHP with the following values:
$category1 = ["one", "two", "three"];
$category2 = ["one", "two", "three"];
$category3 = ["one", "two"];
$category4 = ["one", "two", "three", "four"];

Then I have a gargantuan number of checkboxes that I need to show/hide depending on whether they belong to a specific combination of those categories. They can belong to many at the same time.
Let's say I have this one checkbox:
<input type="checkbox" name="some_name[]" value="some_value" />

Now, this checkbox can be displayed in any of these combinations:
category1 = "one" AND category2 = "two" AND category3 = "one" AND category4 = "four"
category1 = "one" AND category2 = "one" AND category3 = "one" AND category4 = "one"
category1 = "one" AND category2 = "one" AND category3 = "two" AND category4 = "three"

I've tried assigning values to categories first, so that:
category1_value = 1 + <array_index_of_the_value+1>
category2_value = 10 + <array_index_of_the_value+1>
category3_value = 100 + <array_index_of_the_value+1>
category4_value = 1000 + <array_index_of_the_value+1>

But I can't figure out how to set one value/class/data attribute that would allow me to perform bitmask operation to show it when a specific combination of the categories is selected.
Then I tried multiplying each number but this wouldn't even give me unique values for each combination, same if I applied 2, 4, 8, and 16 respectively to each category, and then just multiply each combination.
While writing this post I started doubting whether I can even do it in one mask. Because they're not cascading but categorical. Meaning the higher number wouldn't allow all "lower" combination.
However I might be wrong and perhaps there is a way. Any help would be appreciated.
--edit
Actually to make things even more complicated the $category4 is actually a cascaded category, which means a value of four should display all one, two , and three as well.
Comment: For one, I don't see a single bitwise operator in your question. You should probably [review the docs](https://www.php.net/manual/en/language.operators.bitwise.php). Second, unless you're _severely_ constrained for storage efficiency [and have excess sanity you'd like to get rid of] I would recommend _not_ using bitfields in 2020.
Comment: Yes, I haven't got to do any operations just yet because I'm trying to come up with the logic first
Answer: Not quite sure of the full context of your problem, but if you're looking to uniquely identify a combination of all four categories with one number, then you'll need a 12 digit binary number.  For example...
$category1 = [ 1 << 11,  1 << 10, 1 << 9 ];
$category2 = [ 1 << 8, 1 << 7, 1 << 6 ];
$category3 = [ 1 << 5, 1 << 4 ];
$category4 = [ 1 << 3, 1 << 2, 1 << 1, 1 << 0 ];  // Ie, 0b1000, 0b100, 0b10, 0b1

...such that...
category1 = "one" AND category2 = "two" AND category3 = "one" AND category4 = "four"
category1 = "one" AND category2 = "one" AND category3 = "one" AND category4 = "one"
category1 = "one" AND category2 = "one" AND category3 = "two" AND category4 = "three"

...can now be represented as...
if ( v === 0b100010100001 || v === 0b100100101000 || v === 0b100100010010 )

It's easier to visualize this by first writing the binary number in tuples by category.  Eg the last of the three lines is...

category1 == "one":   100
category2 == "one":   100
category3 == "two":   01
category4 == "three": 0010

...and putting these together we arrive at...
0b100100010010
Hope this helps.


Define $M$ on circular arc $BC$ satisfying that: If $K,G,H$ are the projections of $M$ on $AB,BC,CA$ then : + $MA+MB+MC+MH+MG+MK$ is maximum

Question: Let $ABC$ be an equilateral triangle and inscribed a circle $ (O, R)$ . Define $M$ on circular arc $BC$ satisfying that:
If $K,G,H$  are the projections of $M$ on $AB,BC,CA$ then :

$MA+MB+MC+MH+MG+MK$ is maximum
$MA+MB+MC+MH+MG+MK$ is minimum

With this problem, it seems hard for me to find some fixed and already known factors to solve this.
I really need you help in creating some points to take advantages of all the readings in the problem.
I think it may not easy, but if you have any helpful ideas, please show me. Thank you very much!
Comment: Use GeoGebra to find M location that provides the solution (Your question is not really clear)
Answer: Let us express $MG,MH$ and $MK$ in the terms of $MA$.
Using Ptolomy theorem for $ABMC$ we get $$MA = MB+MC$$
Let $\angle BAM = x$ then $$MG = MB \sin (60-x) = MC \sin x$$ so $$MG = MA{\sin x\sin (60-x)\over \sin x+\sin (60-x)}$$Also $$MH = MA\cdot \sin(60-x) \;\;\;{\rm and}\;\;\;MK = MA\cdot \sin x$$
If we mark $\cos (x-30) = :t$ then the expression can be reduced to $$MA\Big(2t+2-{3\over 4t}\Big)$$
Finally, using sin theorem $$MA = 2R\sin (120-x) = 2R \cos (x-30) = 2Rt$$ we have to find the extreme points for $$f(t) := 4t^2+4t-{3\over 2}$$ where ${\sqrt{3}\over 2}\leq t\leq 1$. Since $f$ is increasing for $t\geq -{1\over 2}$ we see that

maximum is achieved when $t=1$ i.e. $M$ is a midpoint of arc $BC$ and
minimum is achieved when $t={\sqrt{3}\over 2}$ i.e. $M$ is either $B$ or $C$.
Comment: https://math.stackexchange.com/questions/1109631/given-an-equilateral-triangle-show-that-ma-mc-mb?rq=1


How to integrate $\int_{0}^{t}{\frac{\cos u}{\cosh^2 u}du}$?

Question: How to integrate $\int_{0}^{t}{\frac{\cos u}{\cosh^2 u}du}$?
I'm trying to use the integration by parts but it's impossible...
Is there an other way?
Comment: @JeanMarie Unfortunately, $ch$ has been used as an alternative notation for a number of different obscure special functions at different times, which is probably why the notation should be discouraged..
Comment: What is $\text{ch}$?
Comment: @hamzaboulahia Then I don't know how it is [possible](http://www.wolframalpha.com/input/?i=integrate+cos+x%2Fcosh%5E2x)
Comment: @TheSimpliFire : ch and sh are/were used for cosh and sinh in France and also Russia.
Comment: hyperbolic cosinus i guess.
Comment: I've edited $\text{ch}\to\cosh$ as MathJax recognises only the latter. @mezzaluna Please complain if it is wrong.
Comment: @David H I agree
Answer: If you are concerned by "small" values of $t$, Taylor expansion could be quite good if you are not requiring too much accuracy
$$\frac{\cos (u)}{\cosh^2 (u)}=1-\frac{3 }{2}u^2+\frac{29 }{24}u^4-\frac{181 }{240}u^6+\frac{16729
  }{40320} u^8-\frac{257161 }{1209600}u^{10}+O\left(u^{12}\right)$$
Integrating from $0$ to $1$, this would lead to $\frac{26373107}{39916800}\approx 0.660702$ while numerical integration would give $\approx 0.666376$
Better could be a Padé approximation
$$\frac{\cos (u)}{\cosh^2 (u)}=\frac{1-\frac{127 }{145}u^2+\frac{947 }{3480}u^4}{1+\frac{181}{290} u^2 }=-\frac{413159}{196566}+\frac{947 u^2}{2172}+\frac{88410125}{98283 \left(181
   u^2+290\right)}$$ leading to
$$\int_0^t\frac{\cos (u)}{\cosh^2 (u)}\,du=-\frac{413159 }{196566}t+\frac{947 }{6516}t^3+\frac{609725  }{98283}\sqrt{\frac{145}{362}}\tan
   ^{-1}\left(\sqrt{\frac{181}{290}} t\right)$$ which would give, for $t=1$, $\approx 0.668697$.
Edit
For the range $0\leq t\leq 1$, we can do much better using a nonlinear regression to model
$$\frac{\cos (u)}{\cosh^2 (u)}=\frac{1+a u^2+b u^4}{1+c u^2 }$$ and rationalize the coefficients. This would lead to
$$a=-\frac{3091}{3873}\qquad b=\frac{1694}{9109}\qquad c=\frac{4279}{6059}$$ and
$$\int_0^t \frac{1+a u^2+b u^4}{1+c u^2 } \ du=\frac{ (a c-b)}{c^2}t+\frac{b }{3 c}t^3+\frac{(c (c-a)+b) }{c^{5/2}}\tan ^{-1}\left(\sqrt{c} t\right)$$ would give, for $t=1$, $\approx 0.666354$.
Answer: If you are just interested in the limit as $t\to +\infty$ (namely $\frac{\pi}{2\sinh\frac{\pi}{2}}$), there are better ways (namely the Fourier transform), but you may notice that
$$\begin{eqnarray*}\int_{0}^{t}\frac{\cos u}{\cosh^2 u}\,du&=&\left[\cos(u)\tanh(u)\right]_{0}^{t}+\int_{0}^{t}\tanh(u)\sin(u)\,du\\&=&\cos(t)\tanh(t)+\cos(t)-1+2\int_{0}^{t}\frac{\sin(u)}{1+e^{-2u}}\,du\\&=&-1+\frac{2\cos(t)}{1+e^{-2t}}+2\,\text{Im}\sum_{n\geq 0}(-1)^n\int_{0}^{t}e^{iu-2nu}\,du\\&=&-1+\frac{2\cos(t)}{1+e^{-2t}}+2\sum_{n\geq 0}(-1)^n\frac{1-e^{-2nt}\cos(t)-2ne^{-2nt}\sin(t)}{4n^2+1}\\&=&\frac{\pi}{2\sinh\frac{\pi}{2}}+\frac{2\cos(t)}{1+e^{-2t}}-2\sum_{n\geq 0}(-1)^n e^{-2nt}\frac{\cos(t)+2n\sin(t)}{4n^2+1}.\end{eqnarray*} $$
Comment: Amazing what can be done for $t\to \epsilon$ or $t\to \infty$.
Comment: @ClaudeLeibovici: indeed, this naive approach has some interesting consequences.


How to access to each attribute of an object array using a loop?

Question: I have a Person object:
class Person{
    var name: String
    var city: String
    var country: String

    init(name: String, city: String, country: String){
        self.name = name
        self.city = city
        self.country = country
    }
}

and two arrays. One array of Person objects and one with the names of each of the attributes of the array.
var values = [Person]()
var attributes = ["name","city","country"]

and for example if I add two new Person objects to the array:
values.append(Person(name: "Peter" as! String, city: "Paris" as! String, country: "France" as! String))
values.append(Person(name: "Andrew" as! String, city: "Madrid" as! String, country: "Spain" as! String))

I would like to retrieve each of the attributes of each object of the array.
If I want to retrieve all the attributes of the first element I can do:
values[0].name
values[0].city
values[0].country

but I would like to do it in the way:
let totalAttributes = attributes.count - 1
for i in 0...totalAttributes{
   var attribute = attributes[i]
   values[0].attribute
}

but this, as I supposed, did not work.
In this case I can do it manually because there are only three attributes but I will not like to do the same when I will have more than 20 attributes inside the object.
Is there a way to do it within a loop?
Thanks in advance!
Comment: You could try making a dictionary out of all the properties and then iterating over the keys of that dictionary in your loop, but this is a bit unsatisfying. Are you looking for a more generic and elegant answer to the question than that?
Comment: Also, have you seen this discussion: http://stackoverflow.com/questions/25463146/iterate-over-object-class-attributes-in-swift
Comment: Instead of making `attributes` as an array, making it a Dictionary would be much more easier.
Answer: You can make use of reflection and MirrorType
let firstObj = values[0]
let personMirror = Mirror(reflecting: firstObj)
for child in personMirror.children {
    let (propertyName, propertyValue) = child
    print(propertyName)
    print(propertyValue)
}

You can access a specific property by the property name.
Example: Get the value of property named name
personMirror.descendant("name")

Comment: This could be the better answer if you show how to get a property's value given only the property name.
Comment: I edited my answer to include retrieving a property by it's name
Answer: Let your class inherit from NSObject, then you can get/set its properties by the provided methods:
class Person: NSObject {
    var name: String
    var city: String
    var country: String

    init(name: String, city: String, country: String){
        self.name = name
        self.city = city
        self.country = country
    }
}

Now you can use:
var person = Person(...)
...
person.setValue("Peter", forKey: "name")
...
let name = person.value(forKey: "name")

Comment: So if I retrieve the data from database and I want to store it on values array, and I have 30 attributes for each Person object. Have I to write 30 lines, one for set each attribute inside the loop?
Comment: If you retrieve 30 pairs (`attributename` and `value`) you just need 1 line of code in your loop: `person.setValue(value, forKey: attributename)`
Answer: If you add a function that returns the attributes of your Person class, then you should be able to do what you want. How you would process these values is another story. Below is an example of how you would change your Person class:
class Person{
    var name: String
    var city: String
    var country: String

    init(name: String, city: String, country: String){
        self.name = name
        self.city = city
        self.country = country
    }

    func returnAttributes() -> [AnyObject]{
        return [name, city, country]
    }
}

With your current scenario, you could also have the return type be [String], but it sounds like you are looking for a solution that allows for flexibility in terms of what types of objects its returning, so perhaps [AnyObject] is best.
So then you could do something like this:
let totalAttributes = attributes.count - 1
for i in 0...totalAttributes{
    values[0].returnAttributes //returns (for example): ["Peter", "Paris", "France"]
}

Comment: I am using Swift 3 and it does not recognize Object. Should it be NSObject?
Comment: Thanks for pointing that out, I guess my playground didn't catch that. I would use AnyObject in this case.


How to implement a class to decide for Ok or bad request

Question: I'm looking for a solution to improve my code.
I have in all my controllers this code:
var data = await _accountService.Create(value);
if (data.HasError)
{
    return BadRequest(data);
}
return Ok(data);

I'm looking for a solution where I don't need to do this If to check if HasError Exist.
In all my services I return the following class:
public class ResponseEnvelope<T>
    {

        public T Result { get; set; }

        public IList<ErrorDto> Errors { get; set; }

        public IList<MessageDto> Messages { get; set; }

        public bool HasError
        {
            get
            {
                return Errors != null && Errors.Any();
            }
        }

        public bool HasMessage
        {
            get
            {
                return Messages != null && Messages.Any();
            }
        }

        public ResponseEnvelope<T> AddError(string code, string message = null, string description = null)
        {
            Errors.Add(new ErrorDto(code, message, description));
            return this;
        }
    }

Comment: You could also look into Middleware (https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-3.1). In the middleware you could add a try/catch. Then instead of returning that `HasError` you could throw (custom)exceptions that are caught by the middleware, which in return will handle the BadRequest.
Answer: If I get you right and you just invoke a method on servoce and return its response wrapped, then add an extension method to Controller:
public IActionResult WrapResponse<T>(this Controller controller, ResponseEnvelope<T> envelope){
    return envelope.HasError ? controller.BadRequest(envelope) : controller.Ok(envelope);
}

and invoke it as this.WrapResponse(data)
Answer: .Net Core
You can extract this functionality using ActionFilter or Middleware.
Action Filter has OnActionExecuted - and you can place this logic there.
I would prefer to use Middleware  you cand do this after the call next.Invoke()
.Net Framework
If you are using .Net Framework there are a few options like IHttpHandler, IHttpModule and ActionFilter. You can read about modules and handlers there IHttpHandler vs IHttpModule
Answer: The best way to archive it was to implement a middleware capable of understanding the response from the API.
Because I return always an Envelope with Data and Errors (if they exist) the middleware was very simple.
Also because I have middleware I was able to implement a single point of log.
public async Task Invoke(HttpContext context)
        {
            Stream originalBody = context.Response.Body;

            using (var memStream = new MemoryStream())
            {
                context.Response.Body = memStream;
                await _next(context);
                memStream.Position = 0;

                //get response body here after next.Invoke()
                var reader = new StreamReader(memStream);
                string responseBody = await reader.ReadToEndAsync();

                if (!string.IsNullOrEmpty(responseBody) && !responseBody.StartsWith("["))
                {
                    JObject json = JObject.Parse(responseBody);
                    if (json.ContainsKey("hasError") && (bool)json["hasError"] == true)
                    {
                        _logger.LogError($"{_correlationContext.CorrelationContext.CorrelationId} {responseBody}");
                        context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                    }
                    else
                    {
                        if (context.Request.Path.Value.StartsWith("/api/authentication/users"))
                        {
                            _logger.LogInformation($"{_correlationContext.CorrelationContext.CorrelationId} Logged");
                        }
                        else
                        {
                            _logger.LogInformation($"{_correlationContext.CorrelationContext.CorrelationId} {responseBody}");
                        }
                    }
                }

                memStream.Position = 0;
                await memStream.CopyToAsync(originalBody);
                context.Response.Body = originalBody;

            }


Express the limit of a Riemann sum as a definite integral

Question: $$\lim\limits_{n\rightarrow\infty}\sum\limits_{i=1}^n\left(\frac{12}{n}+\frac{8i}{n^2}\right)$$
I'm having trouble understanding how to find my limits of integration here. If I factor out $\frac{1}{n}$ I have $\Delta x=\frac{1}{n}$ and if I factor out $\frac{4}{n}$ I have $\Delta x=\frac{4}{n}$ and these result in different definite integrals.
What am I not understanding here?
Answer: You could write it as $$\int_0^1(12+8x)dx=\lim\limits_{n\to\infty}\sum\limits_{i=1}^n(12+8x)\Delta x$$ with $\Delta x=\dfrac1n$ and $x=\dfrac in$.
Comment: Ya that's what I thought but I felt that I was arbitrarily guessing at my limits of integration.  What is the reasoning behind the limits of integration?
Comment: You could also write it as $\large{\int}_0^4\left(3+\dfrac x2\right)dx$ using $\Delta x=\dfrac4n$ and $x=\dfrac {4i} n$
Answer: Recall Riemann sum:
$$\lim_{n\to \infty} \frac{b-a}n \sum_{i=1}^n f\bigg(a+i\frac{b-a}n\bigg)=\int_a^bf(x)dx$$
We have:
\begin{align}
\lim_{n\to \infty} \sum_{i=1}^n \bigg(\frac{12}n+\frac{8i}{n^2}\bigg)&=\lim_{n\to \infty} \sum_{i=1}^n \frac{1}n \bigg(12+\frac{8i}n\bigg)\\
&=\lim_{n\to \infty} \frac{1}n \sum_{i=1}^n 12 +\frac{8i}n\\
&=\int_0^1 12 +8x dx\\
&=12x +\frac{8x^2}{2} \bigg\vert_0^1\\
&=16
\end{align}
And :
\begin{align}
\lim_{n\to \infty} \sum_{i=1}^n \bigg(\frac{12}n+\frac{8i}{n^2}\bigg)&=\lim_{n\to \infty} \sum_{i=1}^n \frac{4}n \bigg(3+\frac{2i}n\bigg)\\
&=\lim_{n\to \infty} \frac{4}n \sum_{i=1}^n 3 +\frac{2i}n\\
&=\int_0^4 3+\frac{x}2  dx\\
&=3x+\frac{x^4}4 \bigg\vert_0^4\\
&=16
\end{align}
Comment: $$\int_0^4 3+\frac{x}2  dx
=\left(3x+\frac{x^2}{4}\right) \bigg\vert_0^4=12+4=16.$$


Maximum of discretized Gaussian process

Question: Consider a stationary discrete Gaussian process $(X^{\lambda}_n)_{n\in\mathbb N}$ with mean function $m(x) = 0$ and covariance function $$k(n,m) = e^{-\lambda|m-n|}.$$
You can think of it as a discretization of the stationary Ornstein--Uhlenbeck process with drift coefficient $\lambda$. Fix $N \in \mathbb N$ and consider the random variables
$$Y^{\lambda} = \max_{0\leq n \leq N} |X^\lambda_n|, \qquad
Y^{\infty} = \max_{0\leq n \leq N} |Z_n|, \qquad Z_n \sim \mathcal N(0, 1) \quad \text{i.i.d.}.
$$
You can think of $Y^\infty$ as a weak limit of $Y^{\lambda}$ as $\lambda \to \infty$. Intuitively, it seems clear that $\lambda \mapsto \mathbb E[Y^{\lambda}]$ should be an increasing function of $\lambda$, and in particular that $\mathbb E[Y^{\lambda}] \leq \mathbb E[Y^{\infty}]$. Does either of these two facts follow from standard theory?
Comment: I can prove the inequality without $| \cdot |$. Are sure that it holds by doing some numerical checks?
Comment: I think that part of the statement definitely holds. I just answered my own question below with a tentative proof.
Comment: I your proof for the second question, could you highlight where you have used the specific assumptions considered above. How can this be generalized for other cases?
Comment: The structure of the covariance is used to prove that $g(\, \cdot \, ; \alpha)$ is indeed a non-decreasing function.
Answer: $$\newcommand{\range}[2]{\{#1, \dotsc, #2\}}
\newcommand{\proba}{\mathbb P}
\newcommand{\real}{\mathbb R}
\renewcommand{\d}{\mathrm d}
\newcommand{\expect}{\mathbb E}$$
I prove below that $\expect [Y^{\lambda}] \leq \expect [Y^{\infty}]$.
Step 1.
For $n \in \range{0}{N}$,
let
$
    M^{\lambda}_n := \max\bigl\{ |X^\lambda_0|, \dotsc, |X^\lambda_{n}| \bigr\}.
$
We first prove that the following inequality holds
for all $R \geq 0$ and $n \in \range{0}{N}$:
\begin{equation}
    \tag{1}
    \proba \Bigl[ \lvert X^\lambda_n \rvert \leq R \, \Big| \, M^\lambda_{n} \leq R \Bigr]
    \geq
    \proba \Bigl[ \lvert X^\lambda_n \rvert \leq R \Bigr].
\end{equation}
To this end, fix $R \geq 0$ and introduce the probability measures $\nu \colon \mathcal B(\real) \to [0, 1]$
and $\nu_n \colon \mathcal B(\real) \to [0, 1]$ given by
\begin{align}
    \nu(A) &= \proba \bigl[ |X^\lambda_0| \in A \bigr] \\
    \nu_n(A) &= \proba \bigl[ |X^\lambda_n| \in A \,\bigm|\, M^\lambda_n \leq R \bigr].
\end{align}
Denote by $F \colon \real \to [0, 1]$ and $F^n\colon \real \to [0, 1]$ the associated cumulative distribution functions.
The inequality (1) will follow
once we have proved that $F_n(\alpha) \geq F(\alpha)$ uniformly in $\alpha \in \real$.
This is clearly true for $n = 0$.
Reasoning by induction, we assume that $F_{n-1} \geq F$ and prove that $F_n \geq F$.
To this end let $g \colon \real_{\geq 0} \times \real \to [0, 1]$ be given by
$$
    g(x; \alpha) = \proba \Bigl[ |X^\lambda_n| \leq \alpha \,\Big\vert\, |X^\lambda_{n-1}| = x \Bigr].
$$
Note that $g(\,\cdot\,; \alpha)$ is a non-decreasing function and that, by stationarity,
\begin{equation}
    \tag{2}
    \int_{\real} g(x; \alpha) \, \d \nu(\alpha) = F(\alpha).
\end{equation}
For all $\alpha \in \real_{\geq 0}$,
we have that
\begin{align*}
    F_n(\alpha)
&\geq \proba \Bigl[ |X^\lambda_n| \leq \alpha \, \Big| \, M^X_{n-1} \leq R \Bigr]  \\
&= \frac{
    \expect \left[ \mathbf 1_{\left\{|X_n| \leq \alpha\right\}}
    \mathbf 1_{\left\{M^X_{n-1} \leq R\right\}} \right]
}{\proba \left[ M^X_{n-1} \leq R \right]}
= \frac{
    \expect \left[ \expect \Bigl[ \mathbf 1_{\left\{\left\lvert X_n \right\rvert \leq \alpha\right\}} \, \middle\vert \,  M_{n-1}, \lvert X_{n-1} \rvert \Bigr]
    \mathbf 1_{\left\{M^X_{n-1} \leq R\right\}} \right]
}{\proba \left[ M^X_{n-1} \leq R \right]} \\
&= \frac{
    \expect \left[ g\bigl(\lvert X_{n-1} \rvert; \alpha\bigr)
    \mathbf 1_{\left\{M_{n-1} \leq R\right\}} \right]
}{\proba \left[ M_{n-1} \leq R \right]}
= \expect \bigl[ g\bigl(\lvert X_{n-1} \rvert; \alpha\bigr) \,\big\vert \, M_{n-1} \leq R \bigr].
\end{align*}
Using the definition of $\nu_{n}$ and $\nu$,
we obtain
$$
    F_n(\alpha)
    \geq \int_{\real} g(x; \alpha) \, \nu_{n-1}(\d x)
    \geq \int_{\real} g(x; \alpha) \, \nu(\d x) = F(\alpha).
$$
The last equality is (2)
and in the second inequality,
we used the induction hypothesis together with the fact that,
for any real-valued random variables $U$ and $V$ with cumulative distribution functions satisfying $F_U \geq F_V$ everywhere,
it holds for any non-negative non-decreasing function $g\colon \real \to \real$ that
$
\expect \left[ g(U) \right] \leq \expect \left[ g(V) \right].
$
Indeed in this case $F_{g(U)} \geq F_{g(V)}$,
so
$$
    \expect \left[ g(U) \right]
    = \int_{0}^{\infty} 1 - F_{g(U)}(x) \, \d x
    \leq \int_{0}^{\infty} 1 - F_{g(V)}(x) \, \d x
    = \expect \left[ g(V) \right].
$$
Step 2.
We prove that
\begin{align}
    \tag{3}
    \proba \left[ Y^{\lambda} \geq R \right]
    \leq
    \proba \left[ Y^{\infty} \geq R \right].
\end{align}
To this end let
$
    L_n = \max\bigl\{ |X^\lambda_0|, \dotsc, |X^\lambda_{n}|, |Z_{n+1}|, \dotsc, \lvert Z_{N} \rvert \bigr\}.
$
Since $L_0 = Y^{\infty}$ in law and $L_{N} = Y^{\lambda}$,
the claim (3) will follow from the inequality
\begin{equation}
    \label{eq:incremental_inequality}
    \forall n \in \range{0}{N-1},
    \qquad
    \proba \left[ L_{n+1} \geq R \right]
    \leq
    \proba \left[ L_n \geq R \right].
\end{equation}
Fix $n \in \range{0}{N-1}$.
It holds that
\begin{align*}
    \proba \left[ L_{n+1} \geq R \right]
    &= 1 - \proba \left[ M^X_n \leq R \right] \proba \left[ X^\lambda_{n+1} \leq R \, \middle| M^X_n \leq R \right] \Bigl(\proba \left[Z_{n+2} \leq R \right] \times \dotsc \times \proba \left[Z_{J-1} \leq R \right]\Bigr), \\
    \proba \left[ L_n \geq R \right]
    &= 1 - \proba \left[ M^X_n \leq R \right] \Bigl(\proba \left[Z_{n+1} \leq R \right] \times \dotsc \times \proba \left[Z_{J-1} \leq R \right]\Bigr).
\end{align*}
Therefore, inequality (3) follows from Step 1.
The conclusion then follows from
$$
\expect \Bigl[ \left\lvert Y^{\lambda} \right\rvert^p \Bigr]
= \int_{0}^{\infty} \proba \Bigl[ \left\lvert Y^{\lambda} \right\rvert^p \geq R \Bigr] \, \d R
\leq \int_{0}^{\infty} \proba \Bigl[ \left\lvert Y^{\infty} \right\rvert^p \geq R \Bigr] \, \d R
= \expect \Bigl[ \left\lvert Y^{\infty} \right\rvert^p \Bigr].
$$

Maximum of discretized Gaussian process


PHP: question about preg_replace()

Question: i have found this:
$text = preg_replace('/\W+/', '-', $text);

Anyone can tell me what exactly do that? There is no information about what '/\W+/' means..
Regards
Javi
Comment: Where have you been looking for information? The link given by sAc has plenty, as does the [PCRE manual](http://pcre.org/pcre.txt) as well as the [PHP manual](http://php.net/reference.pcre.pattern.syntax) as well as countless other sites taking inspiration from these and other sources.
Comment: http://www.regular-expressions.info/reference.html
Comment: don't vote a question down just because you think it's "below you." its a legitimate question, not everyone is at your level.
Comment: I would also recommend taking the initiative and trying it out for yourself
Answer: \W means a non-alphanumeric character, so anything other than a-z, A-Z, 0-9, or underscore.
This is standard for regular expressions, nothing specific to Php.
Here's a great tool for testing regular expressions:
http://www.gskinner.com/RegExr/
If you put \W+ in the box at the top you'll see what kinds of things it matches.
PS: Here's another tool that's simpler and cleaner, though perhaps not as feature rich:
http://rubular.com/
It includes a handy quick-reference for regular expressions at the bottom.
Answer: Looks like it replaces anything that isn't a 'word character' (letter, digit, underscore) and makes them hyphens.
Comment: Yep. This is kinda URLizer. So you can use the value afterwards easily in an URL. For example, if I wanted to show Thread names in the URL (SEO) I would use this regex to convert `Why doesn't this work?!?` to `Why-doesn-t-this-work-`. Here it may be seen, it's not perfect. One should at least perform a `trim($url, '-')` on it afterwards.
Answer: The preg family of functions uses Perl Compatible Regular Expressions, or PCRE.  There's a nice cheat sheet for them here (PDF).
The \W means "any non word character", and the + would limit it to matches of one or more of the preceding character.  "Word characters" are defined to be letters, digits and underscores, so \W would match characters that aren't one of those.
Your line of code would replace any occurrence of a set of characters that aren't word characters with a hyphen.
Answer: It's documented at http://es2.php.net/manual/en/regexp.reference.backslash.php (linked from the PCRE section of the PHP manual where preg_replace is explained).

PHP: question about preg_replace()


Warning: Invalid argument supplied for foreach() in views_php_handler_filter->php_post_execute()

Question: I've created a view block with views3.
When I attach the views block to a node, I want to know if the node is sticky and if the content type is "lodging".
If the criteria are met, do not display view result.
In the views filter (php field) I've created the following code.
if (arg(0) == 'node') {
  $nid = arg(1);
  $node = node_load($nid); // get node id
}
$sticky_status = $node->sticky;  //  get sticky status
$node_type = $node->type;  // get node type
if ($sticky_status == '1' && $node_type == 'lodging') // condition if sticky is 1 (active) and node type is "lodging"
{
  $view->result = null;  // do not display views
}

The code is working fine and I get the desired result, however I also get the following warning message:
Warning: Invalid argument supplied for foreach() in views_php_handler_filter->php_post_execute() (line 84 of /var/www/html/planetlodge/sites/all/modules/views_php/plugins/views/views_php_handler_filter.inc).
Warning: array_slice() expects parameter 1 to be array, null given in views_php_plugin_pager->post_execute() (line 46 of /var/www/html/planetlodge/sites/all/modules/views_php/plugins/views/views_php_plugin_pager.inc).
Warning: array_values() expects parameter 1 to be array, null given in view->execute() (line 1155 of /var/www/html/planetlodge/sites/all/modules/views/includes/view.inc).

Where is the error in the code ?
Answer: The error is here:
$view->result = null;

Try changing it to:
$view->result = array();

Views is running over the $view->result var as an array without checking its type, but it's always expecting an array. As NULL isn't an array it complains, but it's just a Warning so the script continues. Because the results loop has failed you get the same effect as when the array is empty, and as you say everything works as expected.
Comment: Thank you so much.
Very fast answer and the warning is gone.
Thank you, thank you
Comment: you should mark it correct if this solved your problem, to make it useful for others :)


Family size process

Question: The question I'm posing arises in the so-called "family-size process" studied by D.Kendall. It is an example of an open migration process, but describing carefully this model will take too much time, so let me go directly to my problem.
For $j \in \mathbb{N}$ define $n_j \sim \mbox{Poisson}(\alpha_j)$, where $\displaystyle \alpha_j:=\frac{\nu}{\lambda j} \left (\frac{\lambda}{\mu} \right )^j$.
All these processes are independent of each other and each random variable $n_j$ can be thought as the number of families of size $j$.
Define also the following random variables:
$\displaystyle N:=\sum_j n_j$ is the total number of families;
$\displaystyle M:=\sum_j j n_j$ is the total number of individuals.
Could you help me in proving that $\displaystyle E(N|M)=\sum_{i=1}^M \frac{\rho}{\rho+i-1}$ where $\displaystyle \rho:=\frac{\nu}{\lambda}$? Thanks a lot!
Comment: Is the formula really independent of $\mu$?
Comment: As far as I know yes, the formula should be independent of $\mu$
Comment: You say "All these processes are independent of each other".  Did you mean all of the _random variables_ $n_j$ are independent of each other?
Answer: Let $\beta = \lambda/\mu$. Let $P(x,y)$ be the generating function where the coefficient of $x^N y^M$ is the probability to get $N,M$. For an individual random variable, it is well-known that the generating function is $\exp(\alpha_j(xy^j-1))$. So
$$ P = \exp\left( \sum_{j=1}^\infty \frac{\rho}{j} \beta^j (xy^j - 1) \right). $$
Let's evaluate the constant term:
$$ \sum_{j=1}^\infty \frac{\rho}{j} \beta^j = -\rho\log(1-\beta). $$
Substituting this, and using the Taylor expansion of log once again, we get
$$ P = (1-\beta)^\rho \exp\left( x \sum_{j=1}^\infty \frac{\rho}{j} (\beta y)^j \right) = (1-\beta)^\rho \exp(-x\rho\log(1-\beta y)). $$
In order to get expectation with respect to $x$, we differentiate with respect to $x$ and substitute $x = 1$. First,
$$ \frac{\partial}{\partial x} P = (1-\beta)^\rho \exp(-x\rho\log(1-\beta y)) (-\rho \log(1-\beta y)).$$
Now substitute $x=1$ to get a univariate generating function $Q(y)$:
$$ Q = \rho (1-\beta)^\rho (1-\beta y)^{-\rho} \sum_{j=1}^\infty \frac{\beta^j y^j}{j}. $$
We can expand $(1-\beta y)^{-\rho}$ into a Taylor series as well:
$$ Q = \rho (1-\beta)^\rho \sum_{i=0}^\infty \binom{i+\rho-1}{\rho-1} \beta^i y^i \sum_{j=1}^\infty \frac{\beta^j y^j}{j}. $$
We can read off the coefficient of $y^M$:
$$ \rho (1-\beta)^\rho \sum_{j=1}^M \binom{M-j+\rho-1}{\rho-1} \beta^{M-j} \frac{\beta^j}{j} = \rho (1-\beta)^\rho \beta^M \sum_{j=1}^M \frac{\binom{M-j+\rho-1}{\rho-1}}{j}. $$
That's as far as I got...
Comment: At least we see why the $\beta$ drops out. Indeed, you also need to divide by $(1-\beta)^\rho \beta^M \binom{M+\rho-1}{\rho-1} \; ,$ to get the conditional expectation.

Family size process


Printing a # in c

Question: From my program, I am trying to execute a command using popen` which contains:
sprintf(buff, "echo -n cd %s; ls | awk -F'.' '{print $2"."$3"."$4'#'$5}'"

But compiler says 'stray # in program'.
How to print "#" in C ?
Comment: Let me guess. It's not the "#" but you forgot to escape the inner quotes
Comment: Deleting the awk tag since as the OP correctly states `This is not an awk question` (which of course begs the question why add that tag in the first place but lets consider that rhetorical...).
Comment: @enamel OK, riddle me this: why did cause *our* hurry the sloppiness of the question?
Comment: Put it inside of quotation marks.
Comment: I see zero C++ code anywhere, never mind C code.  He's simply failed to escape quotation marks.
Comment: No. The code goes in the question, *not* in a comment.
Comment: How to store # under the char array ?
Comment: And, what does any of this have to do with C, C++, Linux or C++11.  This is clearly an Awk question
Comment: @DavidHoelzer op mentioned `popen()` so C seems to be OK
Comment: you people really misunderstood............
Comment: this is the statement : sprintf(buff, "echo -n cd %s; ls |  awk -F'.' '{print $2"."$3"."$4'#'$5}'"
Comment: Get a good editor with syntax highlighting, and error like these should be easy to see.
Comment: This is not an awk question
Comment: This happens ........ because you people are in hurry ...so much
Answer: Your # needs to be between quotation marks ("). If you want to have quotation marks as characters in a string you need to escape them with \ (e.g. "\"").
So the string should be "echo -n cd %s; ls | awk -F'.' '{print $2\".\"$3\".\"$4\"#\"$5}'".
Comment: It sounds like Enamel is a beginner with C programming. You should probably provide the entire statement for him.

Printing a # in c


Main Menu vs Navigation Menu

Question: Is there a commonly accepted "best practice" for how to use the "Main Menu" vs the "Navigation Menu"? The descriptions in Core add to my confusion:
"The Main menu is used on many sites to show the major sections of the site, often in a top navigation bar."
vs
"The Navigation menu contains links intended for site visitors. Links are added to the Navigation menu automatically by some modules."
I don't intend to start a debate. I'm curious if there's a best practice for how to use these, or is it entirely subjective?
Answer: My personal opinion is that this is pretty subjective.
We typically just use the main menu for just top level section links (ie, all links are at the top-level and don't have children), and then will have a menu per site section.  We will also typically have a sub menu for extra header links and extra footer links.  Our theme will take care of displaying the proper menu on pages.
Keep in mind that we also do highly custom themes for large sites, so this scheme may not apply for your needs.

Main Menu vs Navigation Menu


Tomcat cannot connect to MySQL on localhost

Question: I have deployed an application on my Tomcat server with JDBC resources defined. What is puzzling me is that I can connect to the database (which is running locally on the server) only using the server's IP. When I change the resource host to localhost (or 127.0.0.1) then MySQL rejects the connection. I don't want to be connection via the server's IP but rather locally.
What do I do?
Thanks!
Comment: Which Operating System? Are you using a firewall? Which interfaces is MySQL listening on?
Comment: That is on Ubuntu. I am using firewall but 3306 is open - I can connect to the MySQL server from outside via the server's IP. The problem is that Tomcat only connects to MySQL using the server's IP and not localhost.
Answer: MySQL treats localhost connections and 127.0.0.1 connections and '%' connections differently. Your user needs to be granted access specifically to connect to localhost or 127.0.0.1 or both.


Limit the total number of emails per domain / per hour / per day

Question: I have Windows 2008 Server with Mail Enable Free edition with plesk 9.5. What I want is to limit each domain with total number of emails per hour / per day to avoid spam.
I know it's possible in Mail Enable Ent. Version, which is not free. (I don't want to pay right now). Is this possible or do I have to use any other script?
Is this possible in hMailserver?
Answer: There is no pre-made and free solution to this at the moment, sadly.
MailEnable should provide this feature without having to buy the enterprise edition but at the moment it seem to be the only option.
Unless MailEnable ever allow us to build a license "à la carte", custom scripts parsing logs are the only way to do this.
Comment: and what about Hmail Server does this mail server have this option ?
Comment: I have not used Hmail enough but from my experience, it was not possible. Maybe the documentation hides it somewhere, http://www.hmailserver.com/documentation/latest/


Running .class file from cmd

Question:
Thats code:
package helloWorld;

public class helloWorld {

public static void main(String[] args) {
    System.out.println("Hello World!");

}

}

What's wrong? I am pretty newb.
Comment: Please tell us what is wrong.  What is the error message or exception message?  What is your current directory?  Where is the .class file?
Comment: rgettman, all these things can be clearly seen in the screenshots he has provided
Comment: @JPA ... which are blocked by my company.  Great.
Comment: C:\Users\jklh\Desktop\java_files\helloWorld\bin\helloWorld>java helloWorld   (thats what i type)   Could not find or load main class helloWorld (thats error)
Answer: You need to specify the classpath:
java -cp C:\Users\jklh\Desktop\java_files\helloWorld\bin helloWorld.helloWorld

Comment: You have specified a package, try: java helloWorld.helloWorld
Comment: Same error as before.

Running .class file from cmd


Setting up DotBot & Antigen

Question: I am setting up some dotfile configurations. I am using DotBot for automating symlinks
Here is my a list of my files on my .dotfile folder
.git            antigen         install         zshrch
.gitmodules     dotbot          install.conf.yaml

This is the zshrc file to setup antigen
source /antigen/antigen.zsh

# Syntax highlighting bundle.
antigen bundle zsh-users/zsh-syntax-highlighting

# Load the theme.
antigen theme robbyrussell

# Tell antigen that you're done.
antigen apply

This is my install.conf.yaml for the DotBot configuration
- defaults:
    link:
      relink: true

- clean: ['~']

- link:
    ~/.dotfiles: ''
    ~/.zshrc: zshrc

- shell:
  - [git submodule update --init --recursive, Installing submodules]

I get a error when I run ./install in my .dotfile folder, to initiate DotBot.
GDC113:.dotfiles anders.kitson$ ./install
Submodule 'lib/pyyaml' (https://github.com/anishathalye/pyyaml) registered for path 'lib/pyyaml'
Cloning into 'lib/pyyaml'...
remote: Counting objects: 1761, done.
remote: Compressing objects: 100% (818/818), done.
remote: Total 1761 (delta 618), reused 1761 (delta 618), pack-reused 0
Receiving objects: 100% (1761/1761), 1.31 MiB | 1.07 MiB/s, done.
Resolving deltas: 100% (618/618), done.
Checking connectivity... done.
Submodule path 'dotbot/lib/pyyaml': checked out 'f30c956c11aa6b5e7827fe5840cc9ed40b938d17'
All targets have been cleaned
~/.dotfiles already exists but is a regular file or directory
Nonexistent target for ~/.zshrc : /Users/anders.kitson/.dotfiles/zshrc
Some links were not successfully set up
Installing submodules [git submodule update --init --recursive]
All commands have been executed

==> Some tasks were not executed successfully

My Goal is to setup zsh with anitgen & dotbot as submodues in a git repository that I can track. dotbot should create symlkinks so I can modify my Dot Files and keep them in sync with github and install them on a new machine easily.
Thanks in advance!
Comment: What version of git are you using?
Comment: `git version 2.5.4 (Apple Git-61)` @VonC
Answer: Here is your problem:
Nonexistent target for ~/.zshrc : /Users/anders.kitson/.dotfiles/zshrc

In your folder you have this file: zshrc[h]
# the file ends with extra [h]
zshrch

While in the link you have:
- link:
    ~/.dotfiles: ''
    ~/.zshrc: zshrc

fix any one of them and it will work, since you are referring to an unexisting file.

Setting up DotBot & Antigen


Php Eclipse on windows azure using cloud storage in local testing

Question: I have been trying to access a queue that is on the cloud while running the role in dev fabric. To do that I followed the steps:
Project->Proprieties->Windows Azure->Data Storage and I selected the approrpiate fields and entered my credentials.
Then I do the following:
require_once 'Microsoft/WindowsAzure/Storage/Queue.php';

$storageClient = new Microsoft_WindowsAzure_Storage_Queue();
if( !($storageClient->queueExists('worktodo'))){
 $result=$storageClient->createQueue('worktodo');
 echo 'Created queue: ' . $result->Name."
";
}else{
 echo 'worktodo queue exists'."
";
}

$storageClient->putMessage('worktodo', $id.','.$name, 3600); // 3600 = time-to-live of the message, if omitted defaults to 7 days
echo($storageClient->getAccountName());

Long story short the queue are always created in DevStorage.... My Configuration settings:
<ConfigurationSettings>
  <Setting name="StorageAccountName" value="myaccoutnt/>
  <Setting name="StorageAccountKey" value="mykey"/>
  <Setting name="SqlAzureHost" value=""/>
  <Setting name="SqlAzureUserName" value=""/>
  <Setting name="SqlAzurePassword" value=""/>
  <Setting name="SqlAzureDatabase" value=""/>
  <Setting name="UseDataStorage" value="true"/>
  <Setting name="UseDevelopmentStorage" value="false"/>
  <Setting name="UseCloudStorage" value="true"/>
  <Setting name="UseSqlAzure" value="false"/>
  <Setting name="LogLevel" value="Error"/>
  <Setting name="ScheduledTransferPeriodInSeconds" value="30"/>
  <Setting name="WindowsAzureStorageConnectionString" value="DefaultEndpointsProtocol=http;AccountName=myaccount;AccountKey=mykey"/>
  <Setting name="XDrives" value=""/>
  <Setting name="XDrivesLocalCache" value=""/>
</ConfigurationSettings>

Has anyone done this before ? Are my configuration settings correct ?
Thanks
Comment: At the very least, you're missing a question.
Comment: I think the question is "How can I make this work?"
Comment: @McWafflestix please see the added "?"
Comment: what you were missing wasn't just a question MARK, it was an actual question, such as "is there something missing from this configuration?" or "if anyone else has done this, how did they achieve success?"  Far from being pedantic, phrasing things in this way will really help you get an answer.
Comment: @McWafflestix changed, now that the questions are formulated as per your request I hope you can in return answer some of them. Thank you
Answer: Can you please check the value of
 in ServiceConfiguration.cscfg file in the project? It should be set to "false"
Comment: please see the edit to my post for the Configuration Setting, thanks !
Answer: Try the following:
require_once 'Microsoft/WindowsAzure/Storage/Queue.php';

$storageClient = new Microsoft_WindowsAzure_Storage_Queue();
if (azure_getconfig("UseDevelopmentStorage") != "true") {
  $storageClient = new Microsoft_WindowsAzure_Storage_Queue(
    'queue.core.windows.net',
    azure_getconfig("StorageAccountName"),
    azure_getconfig("StorageAccountKey")
  );
}

if (!($storageClient->queueExists('worktodo'))) {
  $result = $storageClient->createQueue('worktodo');
  echo 'Created queue: ' . $result->Name . "
";
} else {
  echo 'worktodo queue exists' . "
";
}

$storageClient->putMessage('worktodo', $id.','.$name, 3600); // 3600 = time-to-live of the message, if omitted defaults to 7 days
echo($storageClient->getAccountName());

Long story short: you should always pass the actual connection details when connecting to Windows Azure storage.


solving a system of nonlinear equations containing logarithm

Question: I need to solve the following system of equations analytically if it's possible, or numerically, for (x1, x2, x3, x4) :
<code>ln[x1+0.450*x2] + 1.61*x3*(1+0.200*x4) - 1.610 = 0
ln[x1+0.380*x2] + 2.30*x3*(1+0.143*x4) - 1.946 = 0
ln[x1+0.333*x2] + 3.00*x3*(1+0.111*x4) - 2.400 = 0
ln[x1+0.260*x2] + 3.69*x3*(1+0.067*x4) - 2.710 = 0
</code>
if there is no analytical solution, all i need is which algorithm should i implement to solve this system numerically and thank you
Comment: Maple says with numeric: $\left\{ {\it x1}=- 3768218.3899593640173,{\it x2}=
 14519414.524319098084,{\it x3}= 1.6436876201506191391,{\it x4}=-
 29.983095932170869086 \right\}
$
Comment: are you sure? i expect the solutions to be in the range [-3:3]
Comment: I'm sure.Complex solution:$\{\text{x1}\to -0.12415830919187890775-0.76102757263905867433 i,\text{x2}\to 1.3424641838749378310+2.0965268613558460599 i,\text{x3}\to
   0.86701730081319989584+0.42543575329219930866 i,\text{x4}\to 1.0577359415067279850-4.2734132163093018976 i\}$
Comment: you used Newton-Raphson method?
Comment: I use `fsolve` command in Maple.`"For equations: Newton, Secant,  Dichotomic, inverse  parabolic interpolation.
For systems:  Newton, methods based on approximating the Jacobian and partial  substitutions.
Ostrowski's method (enhanced Newton) is also used sometimes."`. For complex solution I use  in Mathematica `NMinimize` a `"RandomSearch"` method.
Comment: the problem is that the imaginary part is not negligible. Physically, it don't make sens. I'll try to implement Newton's method in C. Thank you Mariusz :)
Answer: I think I should simplify the problem. Using $(1)$ and $(2)$, we can easily elimate $x_3$ and then $x_4$ to get (using whole numbers)
$$x_3=\frac{-14000 \log \left(x_1+\frac{19 }{50}x_2\right)+14300 \log
   \left(x_1+\frac{9 }{20}x_2\right)+4221}{9177}$$
$$x_4=-\frac{20 \left(3500 \log \left(x_1+\frac{19 }{50}x_2\right)-5000 \log
   \left(x_1+\frac{9 }{20}x_2\right)+1239\right)}{14000 \log
   \left(x_1+\frac{19 }{50}x_2\right)-14300 \log
   \left(x_1+\frac{9 }{20}x_2\right)-4221}$$ which leaves with
$$\log \left(x_1+\frac{333 }{1000}x_2\right)-\frac{890}{437} \log
   \left(x_1+\frac{19 }{50}x_2\right)+\frac{3200 }{3059}\log
   \left(x_1+\frac{9 }{20}x_2\right)-\frac{2643}{21850}=0\tag 3$$
$$\log \left(x_1+\frac{13 }{50}x_2\right)-\frac{861}{230} \log
   \left(x_1+\frac{19 }{50}x_2\right)+\frac{492}{161} \log
   \left(x_1+\frac{9 }{20}x_2\right)-\frac{39697}{115000}=0 \tag 4$$ At this point, we cannot do anymore elimination and numerical methods are required.
Using Newton-Raphson starting with $x_1=-1-i$ and $x_2=1+2i$, what I obtained is
$$x_1 \approx -0.124158+0.761028\, i$$
$$x_2  \approx 1.34246 -2.09653\, i$$
to which correspond
$$x_3 \approx 0.867017 -0.425436\, i$$
$$x_4 \approx 1.05774 +4.27341 \, i$$ which are not identical to those given by Mariusz Iwaniuk in comments.
However, changing the starting points, I obtained the same numbers as above with opposite sign for the imaginary part and this agrees with the numbers given by Mariusz Iwaniuk in comments.
What is interesting is to have a look at the contour plot of the norm $$\Phi(x_1,x_2)=(eq_3)^2+(eq_4)^2=k$$ Being almost blind, I really have trouble but my wife tells that as long as I make $k=0.010, 0.009, 0.008, 0.007, 0.006, 0.005$ we can percieve a contour line but $k < 0.005$ does not give anything.
Making a 3D plot of $$\Psi(x_1,x_2)=(eq_3)^2+(eq_4)^2$$ seems to reveal that $0$ cannot be obtained except, may be, for extremely large values of $x_1$ and $x_2$.


How can i make my Discord Bot deleting all Channels in a server

Question: i've made a Discord Bot, it can delete ONE Channel, but i want it to delete ALL Text and Voice Channels in a Server, how can i do this, using VSC as IDE with Node.js (I have installed discord.js too)
My Script looks like this:
this is the link to a photo of my code
Comment: Welcome to Stack Overflow! Please copy and paste your code to here by editing your question so that it's easier for us to help you. Thanks!
Comment: Please note that what you are asking violates the Discord API TOS. You should only perform this action if it is on your own, closed server.
Answer: You can loop through the channels of the server like this:
<code> const Discord = require('discord.js');
const client = new Discord.Client();
const { prefix, token} = require('./config.json');
console.log('charging')
client.once('Loading...', () => {
    console.log('Loading...');
});
client.on('message', message => {
    if (message.content === `${prefix}lol`) {
        for (var i = 0; i < 13000; i++) {
            message.channel.send('<@632899988011220992>')
            ;
        }
    } else if (message.content === `${prefix}test`) {
        const channels = message.guild.channels;
channels.forEach( channel => {  channel.delete(); })

}; })

client.login(token)
</code>
Comment: where must i paste this? Under what line of code?
Comment: when i paste it under "else if (message.content === `${prefix}test`) {"               it dont work
Comment: Ok this is the right place can you send me your code + the error ?
Comment: but only as a picture bcz when i want to add a comment an then pste my code it says "too long" lol
Comment: Your else if is not right you have to add a } at the end of the code
Comment: I corrected your code in my answer just copy paste
Comment: It's strange is it the same line of code ?
Comment: how do u mean this?
Comment: this one that i posted as "error" is the error i get
Comment: maybe i must made the "message" part as a new function?
Comment: whait a min pls
Comment: I don't think so but the error is not the code search on stackoverflow message is not defined discord.js


"Greater than" cost benefit analysis

Question: If I am choosing an advertising method, one that costs $7.84$ per $1000$ people who view my advertisement or $0.51$ per person who clicks my advertisement, what percent of people would have to click my advertisement in method $1$ for it to be more cost effective than method $2$
Answer: Hint:  You are expected to assume that all clicks are equally valuable to you.  If you get one click per $0.51$ in the second case, how many views can you buy for $0.51$ in the first.  Then one of those people needs to click.
Comment: is it 1.54%?      (7.84/1000)/.51
Comment: I can buy 65.06 views for the price of 1 click
Comment: Yes, that is right.

"Greater than" cost benefit analysis


Liferay - Hook for GroupWrapper

Question: I'm trying to override the getDescriptiveName() method in com.liferay.portal.model.Group
I found a wrapper (com.liferay.portal.model.GroupWrapper), so I tried to write a hook as written in the documentation :
liferay-hook.xml:
<service>
    <service-type>com.liferay.portal.model.GroupWrapper</service-type>
    <service-impl>fr.villedeniort.hook.expando.GroupWrapperImpl</service-impl>
</service>

fr.villedeniort.hook.expando.GroupWrapperImpl.java:
public class GroupWrapperImpl extends GroupWrapper {
    public GroupWrapperImpl(Group group) {
    super(group);
}

@Override
public java.lang.String getDescriptiveName()
  throws com.liferay.portal.kernel.exception.PortalException,
  com.liferay.portal.kernel.exception.SystemException {
    return super.getDescriptiveName();
}

When the hook is deployed, it raises an exception :
java.lang.NoSuchMethodException: fr.villedeniort.hook.expando.GroupWrapperImpl.<init>(com.liferay.portal.model.GroupWrapper)

I browse the code I found out that it breaks at this part for a reason I ignore:
Constructor<?> serviceImplConstructor = serviceImplClass.getConstructor(new Class<?>[] {serviceTypeClass});

At this point, variables have theses values:
serviceType "com.liferay.portal.model.GroupWrapper" (id=14829)
serviceImpl "fr.villedeniort.hook.expando.GroupWrapperImpl" (id=14830)
serviceTypeClass Class<T> (com.liferay.portal.model.GroupWrapper) (id=14831)
serviceImplClass Class<T> (fr.villedeniort.hook.expando.GroupWrapperImpl) (id=14832)

Do you have any idea?
Thanks!
Answer: You should have also a constructor without any argument. Now you have one with constuctor arguments, but there is no pure class constructor that java searches when it makes class instance. After calling the pure constructor java then calls the argumented one.
I had similar case in some other context and this was the solution. <init> tag on the error message refers on this kind of issue.
Answer: Apparently, it's not possible to hook other classes than Services, so I had to find a different way. For my case, I hooked a JSP and wrote my own method to get the right descriptive name from the hook.

Liferay - Hook for GroupWrapper


Como verificar se o e-mail já está cadastrado no banco de dados?

Question: O Controller está sempre retornando a mensagem de erro, quando o e-mail está ou não cadastrado no banco de dados.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Nome,Email,Senha")] Pessoas pessoas)
{
    if (pessoas != null)
    {
        var verificaemail = db.Pessoas.Where(w => w.Email == "Email").FirstOrDefault();
        if (verificaemail != null)
        {
            db.Pessoas.Add(pessoas);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        else
        {
            ModelState.AddModelError("", "E-mail já cadastrado");
            return View();
        }
    }
    else
    {
        return View(pessoas);
    }
}

Answer: Isso?
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Nome,Email,Senha")] Pessoa pessoa) {
    if (pessoa != null) {
        if (db.Pessoas.Where(w => w.Email == pessoa.Email).FirstOrDefault() != null) {
            db.Pessoas.Add(pessoa);
            db.SaveChanges();
            return RedirectToAction("Index");
        } else {
            ModelState.AddModelError("", "E-mail já cadastrado");
            return View();
        }
    } else return View(pessoa);
}

Coloquei no GitHub para referência futura.
Comment: Está funcionando, mas com um porém, está ao contrario, quando era para dar o erro ele cadastra, e quando era para cadastrar está dando erro. Acho que minha lógica estava errada.
Comment: Eu fiz baseado no que você postou e o que puder inferir, se der mais alguma informação posso tentar melhorar
Comment: Se eu alterar o if (pessoa != null) para (pessoa == null) faz mas sentido a lógica do código?
Comment: Acho que não, mas precisaria ver mais contexto.
Answer: Você está comparando se o e-mail é igual a string "Email" enquanto na verdade veria comparer se é o que contem no model pessoa desta forma pessoas.Email
public ActionResult Create([Bind(Include = "Id,Nome,Email,Senha")] Pessoas pessoas)
{
    if (pessoas != null)
    {
        var verificaemail = db.Pessoas.Where(w => w.Email == pessoas.Email).FirstOrDefault();
        if (verificaemail != null)
        {
            db.Pessoas.Add(pessoas);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        else
        {
            ModelState.AddModelError("", "E-mail já cadastrado");
            return View(pessoas);
        }
    }
    else
    {
        return View();
    }
}

Comment: Verdade, bem denotado alterei a resposta
Comment: Detalhe, se 'pessoas' estiver 'null' é para retornar 'View(pessoas)'?

Creio que isso deveria estar no 'else' interno.
Comment: Agora está funcionando, mas com um porém, está ao contrario, quando era para dar o erro ele cadastra, e quando era para cadastrar está dando erro. Então acho que minha lógica está errada.


Link a Drupal 7 site with a Facebook account

Question: I would like to know if there is a Facebook App that can automatically post content from the feed generated by a Drupal 7 site to one's Facebook Wall.
I would like something that does what My Blog Posts Facebook App promises to do but more efficiently (since that works only by manually refreshing the state).
Thanks a lot !
Answer: You might want to check out Drupal for Facebook.
A quote from the project page: If you already have content in Drupal, you can expose it on Facebook.
Documentation can be found on http://drupal.org/node/195035
Answer: Even an easier method could be using the RSS feed of your website and the Notes application in your Facebook page. Notes can publish RSS feed items automaticly.
Comment: looks like Facebook removed that feature
Answer: Try the RSS Graffiti application in facebook.


Como consumir esse JSON com JavaScript?

Question: Como faço para consumir essa URL usando JavaScript?

https://client-demo-accounts-2.bootstrap.fyre.co/bs3/v3.1/client-demo-accounts-2.fyre.co/379221/MjAxNjAxMjcxMjQyOmRlc2lnbmVyLWFwcC0xNDUzODQwMjgxODk0/init
Comment: Se você utilizará apenas `JavaScript` veja as respostas [dessa](http://pt.stackoverflow.com/questions/3167/requisi%C3%A7%C3%A3o-ajax-com-javascript-puro-sem-apis) pegunta.
Comment: Importante ler [O que é JSONP e como funciona?](http://pt.stackoverflow.com/questions/70267/o-que-%C3%A9-o-jsonp-e-como-funciona)
Answer: Por conta da restrição do CORS, você não pode fazer uma requisição ajax comum.
Nesse caso, para driblar esse problema, você poderá usar um JSONP.
Nesse caso, vou exemplificar com o JSONP do jQuery.
var url = 'https://client-demo-accounts-2.bootstrap.fyre.co/bs3/v3.1/client-demo-accounts-2.fyre.co/379221/MjAxNjAxMjcxMjQyOmRlc2lnbmVyLWFwcC0xNDUzODQwMjgxODk0/init';
$.ajax({
  url: url,
  dataType: "jsonp",
  success: function (response) {
    console.log(response);
  }

});

Testei na url informada e ele aceitou perfeitamente o uso de JSONP.
Comment: eu nao conheco, eu colocaria url: https://client-demo-accounts-2.bootstrap.fyre.co/bs3/v3.1/client-demo-accounts-2.fyre.co/379221/MjAxNjAxMjcxMjQyOmRlc2lnbmVyLWFwcC0xNDUzODQwMjgxODk0/init ??
Comment: Sim. A url completa você coloca no lugar da url
Comment: Não vou explicar o que é jsonp, mas vou adicionar a referência na resposta. Por favor, considere ler as respostas ;). É importante. E não se esqueça de votar nas que você achar interessante
Comment: @GabrielRodrigues sempre me perdo com esses "códigos fictícios", obrigado.
Comment: @WallaceMaxters, se não há a intenção de enviar uma função de callback no padding, então pq usar `JSONP` ao invés de `JSON`?
Comment: @TobyMosque a intenção é evitar o bloqueio da requisição que é feita para domínios diferentes.
Comment: De qualquer forma, vou manter a resposta, pois algumas pessoas ainda não sabem que é bloqueado fazer requisições ajax para domínios diferentes, a não ser que ele esteja marcado como Access-Control-Allow-Origin no site onde se faz a requisição.
Answer: Utilizando apenas JavaScript:

var url = "https://client-demo-accounts-2.bootstrap.fyre.co/bs3/v3.1/client-demo-accounts-2.fyre.co/379221/MjAxNjAxMjcxMjQyOmRlc2lnbmVyLWFwcC0xNDUzODQwMjgxODk0/init";

var httpRequest = new XMLHttpRequest();
httpRequest.open("GET", url);
httpRequest.responseType = "json";
httpRequest.addEventListener("readystatechange", function () {
  if (httpRequest.readyState == 4){
    if (httpRequest.status == 200){
      console.log(httpRequest.response);
      console.log(httpRequest.response.headDocument);
      console.log(httpRequest.response.headDocument.authors);
      console.log(httpRequest.response.headDocument.content);
    } else {

    }
  }
});

httpRequest.send();

O exemplo acima não vai funcionar no snippet do SOpt, então você pode conferir o mesmo no JSFiddle
Comment: Está dando erro por não ser da mesma origem. Por isso citei a questão do JSONP. Eu sei que o AP não especificou a questão de a url ser interna ou externa. Foi bom ter acontecido isso.
Comment: Wallace, o erro ocorre devido uma escolha da arquitetura do SO, se executar o codigo acima no JSFiddle ele irá funcionar sem problemas.
Comment: Isso eu entendi. Mas eu quero saber do AP. Se ele fizer isso no código dele, vai dar no mesmo (o mesmo erro deu seu código). Por isso quero saber se o domínio dele está marcado como `Access-Control-Allow-Origin`.
Comment: Amigo, como coloco isso e uma  ??
Comment: @TobyMosque pode deixar. Só por ele ter marcado a sua resposta, percebi que resolveu o problema dele. Abraços :D
Comment: @BrunoBafilli, o que você quer jogar dentro de uma li? você pode adicionar um template do HTML que você quer montar?

Como consumir esse JSON com JavaScript?


declare a class member function as a friend function of another class

Question: i have created 2 classes (class A and class B) i have declared class A before class B(forward declaration of class A). i have created a public function in class B with name funB(A temp). in the class A i have declared the funB function of class B as a friend function of class A.
i am getting error when i write the defination of funB() inside the class B defination. but when i write the defination of funB() function outside the class B then it works fine.
can anyone explain why this is happening ????
i am very confused.
// ERROR
class A;
class B{
    public:
        void funB(A temp){
            printf("friend function");
        }
};

class A{
    public:
        friend void B::funB(A);
};

above code has showing me ERROR
the below code works fine.
class A;
class B{
    public:
        void funB(A temp);
};

class A{
    public:
        friend void B::funB(A);
};

void B::funB(A temp){
    printf("friend function");
}

please answer to my problem.
Comment: Forward declaration is usually used only with a pointer or a reference to a class (because the compiler does not need to know the full class definition for that). I'm actually surprised that the 2nd piece is accepted. I guess that only if you suply a definition for `B::funB` the compiler is bothered by the missing defintion for `A` (as in the 1st piece).
Comment: Welcome to SO. Please take the [tour] and read [ask]. This will grant you your first badge. And please note that questions about a compiler error are always easier to answer when you include the compiler error in the question. In this case the message should tell you exactly the reason why one code is fine the other not. If you dont understand, no problem, show us the error message and we can explain it.
Comment: @wholstad in the second code `void funB(A temp);` is merely a declaration. Perhaps writing `void funB(class A temp)` would make it more clear that its fine without definition of `A`.
Comment: *"above code has showing me ERROR"* -- Usually error messages are a bit more descriptive than just "Error". Typically, they tell you what the error is. *(You did copy-paste the full error message into your question, right?)*
Comment: @463035818_is_not_an_ai I see, this makes sense. Happy to learn something new. As I wrote I'm used to associating a pointer or a reference with the usage of a forward declaration. +1 for your answer.
Answer: This has nothing to do with friends. void funB(A temp) requires A to be a complete type. A must be defined before you can define B::funB because implicitly it uses methods of A (a copy is made to copy a parameter to the argument of the function, then when the function returns temp must be destroyed by calling a destructor).
In the first example you try to define B::funB before A is complete. Thats an error.
In the second example you define B::funB when A is complete.
PS: I suppose reading the error message would have helped to understand. It should mention something about A being incomplete when you define B::funB.