What is the expected value of half a standard normal distribution?

Question: You have a normal distribution with mean of 0 and variance of 1.  Keeping the same probabilities and focusing only on half of the distribution (other half has it's original probabilities but x values of 0) what is the expected value of this?
Im trying to teach myself expected outcomes with weird constraints.  I got 0.3989, hopefully this is right.
Comment: this may help https://en.wikipedia.org/wiki/Half-normal_distribution
Comment: Welcome to CV, vt_og. Which half?
Comment: well the positive half.  I would assume the negative half woudl just be -0.3989
Comment: There are two parts to answering this question: (1) finding a formula for the distribution and (2) computing the integral.  With which part do you need help?
Answer: If we let $Z \sim \text{N}(0,1)$ denote a standard normal random variable, the random variable $|Z|$ follows a standard half-normal distribution (the positive half of the standard normal distribution)  and has $\mathbb{E}(|Z|) = \sqrt{2/\pi}$.  This means that:
$$\mathbb{E}(\max(Z,0)) = \frac{1}{2} \cdot \mathbb{E}(|Z|) = \frac{1}{2} \cdot \sqrt{\frac{2}{\pi}} = \frac{1}{\sqrt{2 \pi}} \approx 0.3989423,$$
$$\mathbb{E}(\min(-Z,0)) = \frac{1}{2} \cdot \mathbb{E}(-|Z|) = -\frac{1}{2} \cdot \sqrt{\frac{2}{\pi}} = -\frac{1}{\sqrt{2 \pi}} \approx -0.3989423.$$


While displaying Complete database in jupyter notebook instead it shows few starting and ending rows

Question: While displaying Complete database in jupyter notebook instead it shows few starting and few ending rows I tried setting set.maxrows but it doesn't work
Answer: I assume you are using a pandas DataFrame. Then you can do this:
<code>import pandas as pd
pd.options.display.max_rows = None
display(<your data frame>)
</code>


I'm trying to get a report about how many emails have gone through our exchange server today

Question: Is it possible to run a query or maybe some PowerShell command, which will show me the exact number of e-mails which have been gone through our Exchange server today and and exactly one week ago on the same day?
Our Exchange server's version is 2003 on a windows server 2003.
Comment: Have you tried looking in perfmon?
Comment: Yes, I have. Thank you for that, it helped me.
In addition, I've also checked the exchange log file and was able to find the exact number there.
Answer: You should be able to find this information in Perfmon and in your Exchange Message Tracking log files:
Program Files\Microsoft\Exchange Server\TransportRoles\Logs\MessageTracking
Answer: In the end I used perfmon with TotalMessages counter and it gave me the information i needed.


Accesing a RESTORED db from Data Studio

Question: I have restored a db from db2 express-c 11.1 version to a db2 developer version. I can access the tables and data from db2 cmd but when I'm getting the following error message when trying to access tables/view/... in IBM DATA Studio.
com.ibm.db2.jcc.am.SqlException: DB2 SQL Error: SQLCODE=-20249, SQLSTATE=     , SQLERRMC=NULLID.SYSSH200, DRIVER=3.69.56
at com.ibm.db2.jcc.am.gd.a(Unknown Source)
at com.ibm.db2.jcc.am.gd.a(Unknown Source)
at com.ibm.db2.jcc.am.gd.a(Unknown Source)
at com.ibm.db2.jcc.am.yo.c(Unknown Source)
at com.ibm.db2.jcc.t4.bb.p(Unknown Source)
at com.ibm.db2.jcc.t4.bb.h(Unknown Source)
at com.ibm.db2.jcc.t4.bb.b(Unknown Source)
at com.ibm.db2.jcc.t4.p.a(Unknown Source)
at com.ibm.db2.jcc.t4.vb.i(Unknown Source)
at com.ibm.db2.jcc.am.yo.ib(Unknown Source)
at com.ibm.db2.jcc.am.yo.a(Unknown Source)
at com.ibm.db2.jcc.am.yo.a(Unknown Source)
at com.ibm.db2.jcc.am.yo.executeQuery(Unknown Source)
at org.eclipse.datatools.connectivity.sqm.internal.core.connection.StatementAdapter.executeQuery(Unknown Source)
at com.ibm.datatools.internal.core.prs.PRSDatabaseLoader.processQuery(Unknown Source)
at com.ibm.datatools.internal.core.prs.PRSDatabaseLoader.initiateQuery(Unknown Source)
at com.ibm.datatools.internal.core.prs.PRSQueryInfo.getSlice(Unknown Source)
at com.ibm.datatools.internal.core.util.PersistentQueryCache.getSlice(Unknown Source)
at com.ibm.datatools.internal.core.util.PersistentResultSet.createSlice(Unknown Source)
at com.ibm.datatools.internal.core.util.PersistentResultSet.isClosed(Unknown Source)
at com.ibm.datatools.internal.core.util.PersistentResultSet.checkNotClosed(Unknown Source)
at com.ibm.datatools.internal.core.util.PersistentResultSet.absolute(Unknown Source)
at com.ibm.datatools.internal.core.util.PersistentResultSet.relative(Unknown Source)
at com.ibm.datatools.internal.core.util.PersistentResultSetAdapter.next(Unknown Source)
at com.ibm.datatools.core.db2.luw.load.catalog.LUWCatalogDatabase.loadSchemas(Unknown Source)
at com.ibm.datatools.core.db2.luw.load.catalog.LUWCatalogDatabase.getSchemas(Unknown Source)
at com.ibm.datatools.uom.internal.content.loadmgr.LoadUtility$9.basicLoad(Unknown Source)
at com.ibm.datatools.uom.internal.content.loadmgr.ChildrenLoader.load(Unknown Source)
at com.ibm.datatools.uom.internal.content.loadmgr.LoadManager$LevelLoader.load(Unknown Source)
at com.ibm.datatools.uom.internal.content.loadmgr.LoadManager$LevelLoader.doWork(Unknown Source)
at com.ibm.datatools.uom.internal.content.loadmgr.LoadManager$LevelLoader.access$0(Unknown Source)
at com.ibm.datatools.uom.internal.content.loadmgr.LoadManager$LevelLoader$1.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

Answer: I followed the answer written by mao here but it didn't help.
What helped is rebinding all packages and then re-validating them.
One can use below commands to rebind all packages:
db2 connect to SAMPLE

db2 -x "select 'REBIND PACKAGE ' || rtrim(pkgschema) || '.' || rtrim(pkgname) || ';' as command from syscat.packages" > rebind.sql

db2 -tvf rebind.sql

Post rebinding, re-validate all objects using below system store procedure:
CALL SYSPROC.ADMIN_REVALIDATE_DB_OBJECTS()

Comment: This helped me! But I had to rebind a specific package myself, because this command would give me the error "SQL20249N  The statement was not processed because the package named "NULLID.SQLC2P31" needs to be explicitly rebound." So I executed "db2 rebind package NULLID.SQLC2P31" and things started working.
Answer: After you successfully restore a Db2-LUW database to a new Db2-instance it is wise to ensure that you rebind all of the IBM supplied bindfiles to the database.
The CLI bindfiles are part of your Db2-client, and it's wise to ensure that your Db2-client version/fixpack matches that of the Db2-server.
Rebinding CLI utilities is essential if the Db2-version or Db2-fixpack of the restore-database differs from the original database.
To rebind CLI utilities, follow IBM's instructions for rebinding the CLI packages here.
Another useful activity is to revalidate database objects if the Db2 version or fixpack has changed. There's a stored procedure for that, see details here.
Note: if your database contains SQL PL stored procedures or static-SQL packages then you may also need to rebind those packages to take advantage of any Db2 version differences. There are different ways to do this, but one way is to use db2rbind , and this should only be done on development/testing environments where you can validate the results.
Comment: I executed this command

db2 bind "%DB2PATH%\bnd\@db2cli.lst" blocking all grant public

and it outputs the following result

LINE    MESSAGES FOR db2cli.lst
------  --------------------------------------------------------------------
        SQL0061W  The binder is in progress.
        SQL0091N  Binding was ended with "0" errors and "0" warnings.
db2 => bind db2schema.bnd blocking all grant public

but I'm still getting the same error message
Comment: You must also rebind the *other* supplied files, e.g. db2clipk.bnd as mentioned on the referenced documentation page.
Comment: There's also db2ubind.lst to be bound, see https://www.ibm.com/support/knowledgecenter/en/SSEPGG_11.1.0/com.ibm.db2.luw.admin.dbobj.doc/doc/t0004951.html

Accesing a RESTORED db from Data Studio


Linear regession problem

Question: I am doing a simple linear regression on SPSS and have run Spearman and Pearson tests which came out at .40's
Now on the linear regression my B and bets have come out negative
I am not sure what to infer from this?
Amy help would be appreciated, I am only doing a short course in this so my background knowledge is not much
Comment: Oh, I have just figured it out, my scales go in different directions (at least I think that's what it is)
Comment: Thank you for making this a new question, @Apple. You can also add that comment as an 'official' answer, if it resolved your issue, and mark it as accepted by clicking the check mark that you will see to its left when you post the answer.
Comment: "bets"? are you talking about a standardized coefficient?
Answer: Just a quick note on regression betas and correlation coefficients. Just because two variables have a positive spearman/pearson, doesn't mean that the correlation will still be positive after controlling for other variables (which is what you're doing in a multivariate regression).
For example, let's say we calculate correlation coefficients of mother smoking during pregnancy V. birth weight of child and mother drinking coffee V. birth weight of child.
Let's say that coffee drinkers are more likely to be smokers.
Then if we estimate this model:
birth weight = beta1*smoking + beta2*coffee + error
Both correlation coefficients will probably be negative. However, we will probably find that beta1 is significantly negative, but beta2 is insignificant (i.e. it's not negative, but 0).
This means that the positive correlation sign for coffee was positive only because coffee drinkers are more likely to smoke and, therefore, have babies with low birth weights. If we control for smoking, we may see that coffee drinking has no effect at all on birth weight.

Linear regession problem


Convergence of integral of multiplication of two positive functions

Question: I have two functions $f, g:\mathbb{R}\rightarrow \mathbb{R}_{\ge0}$, that are continuous. I know that $\int\limits_{-\infty}^\infty f(s) \, ds=C_1<\infty$, and $g(s)\le C_2$, with $C_1> 0$ and $C_2\ge0$, for all $s\in\mathbb{R}$.
For me, it is true that
$\int\limits_{-\infty}^\infty f(s)g(s) \, ds\le C_3<\infty$, with $C_3\ge0$. This statement would come from the fact that $f(s)g(s)\le C_2f(s)$, and then integrating on both sides.
This seems to be trivial, but I don't know if I should have additional conditions on the functions $f$ and $g$ so the previous statement is true. Any insights on this will be appreciated.
Comment: This looks fine to me.
Answer: g(s) could be equal to a constant value per your statement then the integral would not be bounded.
To be true g(s) integral must be bounded also.
Comment: This is not correct. $$0 \le \int_{\Bbb{R}} f(x)g(x)\,dx \le \int_{\Bbb{R}} C_2 f(x)\,dx = C_2\int_{\Bbb{R}} f(x)\,dx = C_1 C_2 <\infty.$$ That $f$ and $g$ are positive was crucial here since it allowed us to simply bound $fg$ above.
Comment: Yup, I should keep quiet.  Thanks
Comment: Don't be hard on yourself. Most of us on here have made mistakes (including myself - I've made lots). That's part of math. Take it as a learning experience.
Comment: Thank you, Cameron. It was very helpful.


use laravel + vue sanctum to apply authorization

Question: I have a laravel + vue project and using sanctum for authentication, but I want to use authorization in my project too, I am looking for a solution similar to (spate laravel-permission) But I haven't found anything yet.
Can anyone help me to use authorization in my project please?
Answer: Use middleware in your routes, or ACL-vue
Comment: I am working on ACL-vue but I don't know where the permits are coming from,if should I store them in the database?


How to fit parametric distribution to baseline hazard in cox PH model

Question: I develop Cox PH model with time-varying covariates to predict marginal probability of some event. The time frequency is measured in months and I have observations since 3 months to more than 160 months. However, number of observations is too low for later months (more than 130 months) and also events are very rare, if any (you can see survfit plot of my model on the figure below). Due to this fact, baseline hazard curve is too uneven especially for later months. So, I assume, it will be better to smooth baseline and fitting some parametric distribution to it. To extract baseline curve from Cox PH model I use hasehaz function in R. Then I can fit to it parametric distribution (Weibull, lognormal, etc.), however, I have not idea how to link this fitted curve to survival probability predicted by Cox model. I predict it with following code:
predict(cox_model, new_data, type = "survival").
I appreciate any suggestion regarding to merging fitted baseline curve with Cox model prediction.
p.s. I have tried AFT models from flexsurv packages, however, unfortunately, model did not converge.
Answer: Several thoughts:
First, even if you could generate a smooth baseline survival curve beyond 130 months, it would be unreliable. That's implicit in the large confidence bands around the survival curve at those times.
Second, the plateau in survival beyond 130 months is at about 85% survival! Furthermore, there are many censoring times along that plateau. It seems that you might need to model this as a "cure" model instead, in which there is "infinite" survival for a substantial fraction of cases. My initial reaction is that your data suggest no hazard of an event beyond about 130 months.
Third, your inability to fit simple accelerated failure time models might be due to the second thought. Such models assume that survival approaches zero at late times. Your data don't.
Fourth, the proportional hazard assumption makes it relatively straightforward to adjust a baseline hazard for covariate values. See this page among many others. For your approach to a smooth baseline curve, you could fit the estimated cumulative hazard $\hat H_0(t)$ for a defined baseline set of covariate values,* adjust the cumulative hazard for differences of covariate values from baseline, then use the relationship $S(t)=- \exp (H(t))$ to get the survival curve.
Fifth, it's possible to fit an arbitrary smooth baseline hazard as part of the modeling process. For example, the flexsurv package allows for the Royston-Parmar flexible spline modeling of baseline hazards; the scale = "hazard" parameter setting does that in a proportional hazards setting. I suspect that's a better approach than yours of first fitting a Cox model and then smoothing the baseline hazard, but I have no experience with it.
Sixth, even after you've dealt with those issues, you still have the fundamental problem of trying to make predictions based on time-varying covariates. This page and its links show the potentially circular reasoning that can be involved; such predictions might not make sense in some settings.
Seventh, none of this gets beyond the problems raised in the first thought.

*The baseline hazard reported for survival models is sometimes for a set of "average" values that might make no sense in practice when there are categorical covariates. Best to choose your own or to make sure that the software makes interpretable choices.


Effects of Oversampling on Linear Regression

Question: We often see that oversampling is a useful technique to combat skewed classes. But there is not much discussion about linear regression. If we just duplicate the original data, and train the linear regression model on the new larger dataset, are there any significant good/bad effects of it on the test set predictions?
In particular, will it cause the coefficient to change?
Advice or link to papers is appreciated.
Comment: The coefficients will be identical to those from the non-duplicated data. Ignoring standard errors, the predictions will be identical too.
Comment: Statistical analysis is used to analyze data, and not to generate data. "duplicate the original data" is totally wrong and very dangerous idea.
Answer: There is actually quite an expansive and rich literature on oversampling and linear regression. The general survey methods literature has discussed and explored many types of estimators. For starters, you might reference "Complex Surveys: A Guide To Analysis Using R" by Lumley.
Duplicating data is not oversampling. The point of oversampling is to increase generalizability (valid inference and predictions with better external validity). Copy-pasting data actually decreases these qualities significantly.
Skewness is a property of continuous variables. For categorical covariates, we might speak of the balance of their frequencies... but even then the goal of oversampling isn't to create balance. We just want to have adequate precision in the subgroups defined by the stratification variables.
For instance, suppose I want to estimate the efficacy of an Alzheimer's Disease preventative medication which I believe interacts with the apoe alleles that are overexpressed in American Indian (AIAN). In a sample of 500 at-risk US-based patients, I expect fewer than 5 AIANs. I might oversample to adequately estimate the AIAN-specific effect, then use marginal standardization to reweight the race-specific effects according to the known US-based distribution of race.


How do I disable "last pressed" Button state in Bootstrap?

Question: I'm using Bootstrap Button component in my React application.

The default Button has a special appearance after it was pressed and the mouse cursor is already out of it:

This appearance is changed to normal after any click. How do I disable this feature without disturbing any other states (pressed, mouse over, normal) of Bootstrap Button?
Answer: I think you are referring to the blue border. This is the outline on the :focus state.
try this in your css:
.btn:focus {
  outline:none;
}

for colour try (success btn example):
.btn-success:focus {
  background-color: #5cb85c;
  border-color: #4cae4c;
}

Comment: Not only `border`. As you see, the second picture is many ways different from the first one. I think, there may be a special attribute which disables this state.
Comment: note that the :focus and the :link state may cause that effect also
Answer: Hiding the focus state of buttons is a bad idea. Hitting the space/enter key whilst a clickable element has focus is the same as clicking it. A user should be able tonknow that. You're better off using script to blur() it or move focus to another element.
Answer: In addition to the @Brad response, maybe you can try to switch the class of the button after click with other of the button clases from bootstrap.
Check the Bootstrap Button documentation


Django - relação unique together

Question: Oi, pessoal. Estou mexendo com um banco de dados de livros legado + Django. Nesse banco de dados tem uma tabela principal com informações de livros, onde cada livro recebe um indice e volume únicos juntos. Há outra tabela de empréstimo de livros e nisso mostra o índice e o volume de cada livro emprestado. Porém, na página que estou desenvolvendo ao invés de mostrar o indice e volume gostaria de mostrar o nome do livro. Para isso precisaria ir na tabela principal e resgatar o nome do livro que tem aquele indice e volume para mostrar. Porém não sei como posso fazer isso. Tô quebrando a cabeça para tentar achar a solução.
Alguém poderia me ajudar indicando o que posso ler para conseguir resolver?
Answer: <code>seu model:

class Livro(models.Model):
    indice = models.CharField(unique=True)
    volume = models.CharField(unique=True)
    nome = models.CharField()

sua view:
from <seu_arquivo_model> import Livro
from django.shortcuts import get_object_or_404

class LivroViewSet():

.
.
.

    def retorna_livro(indice, volume):
        livro = get_object_or_404(Livro, indice=indice, volume=volume)
        return livro.nome

Se houver o livro com esse indice e volume, ele retornará o nome daquele objeto Livro, se não, retorna 404(Not Found)
</code>

Django - relação unique together


Run array check more than array count in Java

Question: I load such XML files for check of full sequences into Java and get a value from the XML. This value is saved into an array.
Then I will check which sequences are missing in the files, so I have to sort the values and check the minimum value against the first array value. Then check the minimum value + 1 against the second array value and so on.
The for loop, I can only run how often, are values saved into array. In example it's 6 times. But I need to run it 8 times.
Example:
XML files with SequenceNumber from 68 to 75.
XML files with SequenceNumber 73 and 74 are missing.

The check have to be done 8 times (68, 69, 70, 71, 72, 73, 74, 75) but it's only perfomed 6 times (I have only 6 files / 6 array values).
How can it be done to run the check if SequenceNumber is ok or missing how often its needed, so from minimum to maximum value?
ArrayList seqNrList = new ArrayList<>();
seqNrList.add(doc.getElementsByTagName("SequenceNumber").item(0).getTextContent());
Collections.sort(seqNrList);
int seqNr; //currentValue
int instanceCounter = Integer.valueOf((String) Collections.min(seqNrList));

int seqsizemin = Integer.valueOf((String) Collections.min(seqNrList));
int seqsizemax = Integer.valueOf((String) Collections.max(seqNrList));
int seqruns = seqsizemax - seqsizemin + 1;

System.out.println("first Sequence: " + Collections.min(seqNrList));
System.out.println("last Sequence: " + Collections.max(seqNrList));
System.out.println("max runs: " + seqruns);

for (int i = 0; i < seqNrList.size(); i++) {
    seqNr = Integer.valueOf((String) seqNrList.get(i));
    if (instanceCounter == seqNr) {
        System.out.println("Sequence " + seqNrList.get(i) + " ok");
    }
    else {
        System.out.println("Sequence " + instanceCounter + " Missing");
    }
    instanceCounter++;
}

When I run it this way, I got the following result:
first Sequence: 68
last Sequence: 75
max runs: 8
Sequence 68 ok
Sequence 69 ok
Sequence 70 ok
Sequence 71 ok
Sequence 72 ok
Sequence 73 Missing

expected is:
first Sequence: 68
last Sequence: 75
max runs: 8
Sequence 68 ok
Sequence 69 ok
Sequence 70 ok
Sequence 71 ok
Sequence 72 ok
Sequence 73 Missing
Sequence 73 Missing
Sequence 75 ok

How can this be done? Whats my error at the moment?
Thx in Advance
Toni
Comment: Variable names should start with lowercase.
Answer: Try looping from you minimum value to your maximum value and search with contains method like this:
for (int i = seqsizemin;i<=seqsizemax;i++) {
        if (SeqNrList.contains(i+"")) {
            System.out.println("Sequence " + i + " ok");
        } else {
            System.out.println("Sequence " + i + " Missing");
        }
    }


Como inserir uma List<> em uma Listview C#?

Question: Estou tentando inserir uma List<> (Gerada por outra classe que traz os dados do Banco), os dados chegam a ser inseridos porém a ListView só recebe a primeira coluna, e a outra fica com valor nulo.
Abaixo está o código do form onde está inserido a ListView, tentei algo com o foreach mas também não obtive sucesso
private void Form_Usuarios_Load(object sender, EventArgs e)
{
    List<Usuario> usuarios = new List<Usuario>();
    UsuarioDAO usuario = new UsuarioDAO();
    usuarios = usuario.MostrarUsuarios().ToList();
    foreach(var item in usuarios)
    {
        listViewUsuarios.Items.Add(new ListViewItem(new string[] { item.Nome}));
    }
}

Resultado:
Comment: Não se coloca a solução na pergunta e sim na resposta vou reverter isso e você coloque como resposta.
Answer: Como inserir itens em um componente ListView do Windows Forms?
No seu método ListViewData.Items.Add aceita uma instância da classe ListViewItem que deve ser carregado com as informações contidas em uma lista de valores, um exemplo básico e manual:
ListViewData.Items.Clear();
var item0 = new ListViewItem();
item0.Text = "pt.stackoverflow.com";
item0.SubItems.Add("Site");

var item1 = new ListViewItem();
item1.Text = "microsoft.com";
item1.SubItems.Add("Site");

ListViewData.Items.Add(item0);
ListViewData.Items.Add(item1);

onde a primeira coluna do seu ListViewItem na propriedade Text é o valor da primeira coluna da lista retornada, e as demais são SubItems que com o método Add e adicionado os próximo texto da próxima coluna e assim sucessivamente, a figura representa o código:

para cada coluna a ser adicionado mais um SubItems.Add precisa ser invocado e assim sucessivamente para ser carregados todos os itens dessa coluna.
No seu código é algo assim:
private void Form_Usuarios_Load(object sender, EventArgs e)
{
    UsuarioDAO usuario = new UsuarioDAO();
    List<Usuario> usuarios = usuario.MostrarUsuarios().ToList();
    foreach(var item in usuarios)
    {
        ListViewItem item = new ListViewItem();
        item.Text = item.Nome;
        item.SubItems.Add(item.Cargo);
        listViewUsuarios.Items.Add(item);
    }
}

Referencias:

ListView Classe
ListView.View Propriedade
C# - Usando ListView para exibição de dados - Macoratti
Listview Details view not displaying anything
ListView in C# - https://www.c-sharpcorner.com/
Answer: Consegui aqui pessoal, abaixo está o código com as alterações que fiz para o código funcionar.
private void Form_Usuarios_Load(object sender, EventArgs e)
{
    List<Usuario> usuarios = new List<Usuario>();
    UsuarioDAO usuario = new UsuarioDAO();
    usuarios = usuario.MostrarUsuarios().ToList();
    foreach(var item in usuarios)
    {
        ListViewItem lv1 = new ListViewItem(item.Nome);
        lv1.SubItems.Add(item.Cargo);
        listViewUsuarios.Items.Add(lv1);
    }
}

Comment: o alinhamento do texto no formato código é importante, verifique isso na hora de posta.
Comment: se esse retorno `usuario.MostrarUsuarios().ToList();` retornar um `List` porque antes você cria uma instância que é desnecessaria? dá uma olhada no código que eu implementei. Cuidado com os códigos desnecessários na codificação e instâncias sem necessidade é também um problema.


Add Language Switcher on admin toolbar

Question: What is the correct way for adding Language Switcher (Dropdown) or links on the admin toolbar menu from my custom module or from a contributed module?
Comment: That's a list of tabs, it's not designed to have arbitrary elements in it. Not that it couldn't, theoretically...have a look at core/themes/stable/templates/navigation/toolbar.html.twig, that should make it clearer which variable you need to get the render array for the language switcher into
Comment: There is tree ways to add items to the admin toolbar, take a look at [this question](https://drupal.stackexchange.com/questions/215394/how-can-i-add-items-to-the-admin-toolbar),
Comment: 4k4's answer is how to do it. You'll need to work out how to render the language switcher but that's a simple google search away
Comment: I've tried all of these ways, but I don't know how to add a language switcher on the top of admin menu
Comment: I know how I can render the language switcher or list of language but the issue with me that I've tried the code and the menu link was added but not added on the top beside (Manage, Shortcut, ..), I can only see it on the /admin/structure/menu/manage/admin
Answer: Well, I got something up and running via hook_toolbar. Only thing left is, that you can't click directly on the "Language: EN" string in the toolbar. You have to click slightly next to it. Maybe you can fix this.

Apart from that, please also have a look at the Devel module and their implementation of hook_toolbar where they have an extra src/ToolbarHandler.php class for everything. You better should rebuild the code below into a dedicated handler.

use Drupal\Core\Url;
use Drupal\Core\Link;

/**
 * Implements hook_toolbar().
 */
function MYMODULE_toolbar() {

  // Get languages, get current route.
  $current_language = \Drupal::languageManager()->getCurrentLanguage()->getId();
  $languages = \Drupal::languageManager()->getLanguages();
  $route = \Drupal::service('path.matcher')
    ->isFrontPage() ? '<front>' : '<current>';

  // Get links.
  $links = [];
  foreach ($languages as $language) {
    $url = new Url($route, [], ['language' => $language]);
    $links[] = [
      '#markup' => Link::fromTextAndUrl($language->getName(), $url)
        ->toString(),
    ];
  }

  // Set cache.
  $items['admin_toolbar_langswitch'] = [
    '#cache' => [
      'contexts' => [
        'languages:language_interface',
        'url',
      ],
    ],
  ];

  // Build toolbar item and tray.
  $items['admin_toolbar_langswitch'] += [
    '#type'   => 'toolbar_item',
    '#weight' => 999,
    'tab'     => [
      '#type'       => 'html_tag',
      '#tag'        => 'div',
      '#value'      => '' . t('Language') . ': ' . strtoupper($current_language) . '',
      '#attributes' => [
        'class' => ['toolbar-item-admin-toolbar-langswitch'],
        'title' => t('Admin Toolbar Langswitch'),
      ],
    ],
    'tray'    => [
      '#heading' => t('Admin Toolbar Langswitch'),
      'content'  => [
        '#theme'      => 'item_list',
        '#items'      => $links,
        '#attributes' => [
          'class' => ['toolbar-menu'],
        ],
      ],
    ],
  ];

  return $items;
}

Comment: Can you please tell me what you mean by `'contexts' => [
        'languages:language_interface',
        'url',
      ],`
Comment: @MohamedOsamaGbril – These are cache contexts. They should be sensitive enough to ensure the language string in the toolbar gets updated when switching through languages. But when the title of your toolbar item will just be "Language" you can probably remove that.
Answer: The example above for hook_toolbar is almost perfect.  I fixed it, see code below.
You just have to remove the span on the Language : EN then the click functionality works perfectly.
see my code:
/**
 * Implements hook_toolbar().
 */
function examplemodule_toolbar() {

  // Get languages, get current route.
  $current_language = \Drupal::languageManager()->getCurrentLanguage()->getId();
  $languages = \Drupal::languageManager()->getLanguages();
  $route = \Drupal::service('path.matcher')
    ->isFrontPage() ? '<front>' : '<current>';

  // Get links.
  $links = [];
  foreach ($languages as $language) {
    $url = new Url($route, [], ['language' => $language]);
    $links[] = [
      '#markup' => Link::fromTextAndUrl($language->getName(), $url)
        ->toString(),
    ];
  }

  // Set cache.
  $items['admin_toolbar_langswitch'] = [
    '#cache' => [
      'contexts' => [
        'languages:language_interface',
        'url',
      ],
    ],
  ];

  // Build toolbar item and tray.
  $items['admin_toolbar_langswitch'] += [
    '#type'   => 'toolbar_item',
    '#weight' => 999,
    'tab'     => [
      '#type'       => 'html_tag',
      '#tag'        => 'div',
      '#value'      => t('Language') . ': ' . strtoupper($current_language),
      '#attributes' => [
        'class' => ['toolbar-item-admin-toolbar-langswitch'],
        'title' => t('Admin Toolbar Langswitch'),
      ],
    ],
    'tray'    => [
      '#heading' => t('Admin Toolbar Langswitch'),
      'content'  => [
        '#theme'      => 'item_list',
        '#items'      => $links,
        '#attributes' => [
          'class' => ['toolbar-menu'],
        ],
      ],
    ],
  ];

  return $items;
}

Answer: Ok, nowadays there is https://www.drupal.org/project/toolbar_language_switcher for solving this problem
Answer: The link in the reply berramou posted doesn't mention the contrib module toolbar_menu, which makes adding stuff in the toolbar more convenient than what is mentioned in the link.

Add Language Switcher on admin toolbar


calculate element width based on first line of children

Question: So I have a code like this
This is supposed to be a responsive grid of images and for the last element on a line, the class .last is added by jQuery so it has no margin-right. (solution from here)
But now, I need to assign width to the
 based on the width of the first line of elements for margin: 0 auto to work.
I tried this:
var width = 0;
$('section.grid img').each(function() {
    width += $(this).outerWidth( true );
});
$('.grid').css('width', width);

but obviously that doesn't work as it sums all the elements, not just the first line. Also the number of images on a line is variable based on the screen width.
Thank you.
Comment: @J.Soukup you are right, you would need to use `:nth-of-type()`. see this codepen for an easy example using flexbox: https://codepen.io/dudleystorey/pen/Kgofa/left
Comment: first you can use the `:last-of-type` css selector to address the last image in your list, you don't need jquery for that. then there is `flexbox`, you can use it to create image grids (e.g. https://www.sitepoint.com/using-modern-css-to-build-a-responsive-image-grid/). it's better if your layout doesn't depend on javascript (aka [progressive enhancement](http://alistapart.com/article/understandingprogressiveenhancement))
Comment: but the img elements aren't :last-of-type, they are just last before a line break
Comment: Updated fiddle - https://jsfiddle.net/Pugazh/6d3bctex/4/
Answer: Here are the steps:

Get the width of window and outerWidth(width + padding + margin) of img
Calculate the no of img that can fit into the window.
Apply the calculated width (no of img's that can fit * it's width )

Updated fiddle
Width for
 can be calculated by parseInt(winWidth / width) * width
Comment: this does work, although you have to add -5 to `(winWidth / width) * width` to take into account the removed `margin-right: 5px`
thank you


Soma dos valores na View

Question: Gostaria de realizar uma simples soma de uns valores na minha View.
Tentei realizar dessa forma:
@foreach (ReceitaIndexVM receita in Model)
{
    decimal Total = 0;

Total de Receitas

                @{

                    int cont = receita.Id.ToString("C2").Count();
                    for (int i = 0; i < cont; i++)
                    {
                        Total += receita.Valor;
                    }

                }

@Total

}

Mas fica com este resultado:

Coloquei até uma Count do @receita.Id e ele traz o valor de 7. O que estou realizando errado?
Podem me auxiliar?
Obrigado!
Answer: Acredito que você poderia fazer simplesmente o seguinte:

Total de Receitas

@Model.Sum(x => x.Valor)

Pelo que entendi o Model da sua página já é uma lista, então você pode fazer o somatório usando Linq normalmente.
Usando
@Model.Sum(x => x.Valor)
 ao invés do foreach e o for.
Answer: Nesta parte do código você está iterando, mas não está passando o index
para o objeto:
for (int i = 0; i < cont; i++){
    Total += receita.Valor;
}

Você pode fazer:
for (int i = 0; i < cont; i++){
    Total += receita[i].Valor;
}

Ou:
receita.foreach(item=>{
Total += item.Valor}){

Comment: Obrigado pela ajuda Filipe, mas ele acusa este erro:

Error CS0021 Cannot apply indexing with [] to an expression of type 'ReceitaIndexVM'

Soma dos valores na View


How to reduce the server timeout in Internet explore

Question: I am developing a web application and published to a server. It's has some valid process so it's timed out in Internet Explorer and it ran in Mozilla. HOw to reduce the Internet Explore Time out.
Comment: Why bother, instead just don't use Internet explorer.
Comment: I don't think there are any browser aware timeout parameters, you seem to be having a different problem. Please check again
Answer: you can write this code in web config..
  <sessionState timeout="330"></sessionState>

even you can set it into
 global.asax

Comment: Is this maximum or not, If it's not, Please tell me the maximum time out seconds.
Comment: can you tell the maximum timeout seconds.
Comment: maximum timeout you can set for 1 year means 525600 minutes but its not reasonable to use that much timeout, but you can set it for hours/minutes
Comment: Thank you so much..How can i calculate this '525600';
Answer: Run
Regedit.exe

goto
HKEY_CURRENT_USER > Software > Microsoft > Windows > CurrentVersion > InternetSettings

right click the choose
new DWORD

name it: KeepAliveTimeout
give for example 120000 for two minutes then try if its enough.


Validar Datetime no cliente

Question: Tenho um model com uma propriedade do tipo DateTime:
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
[DataType(DataType.Date, ErrorMessage="Data em formato inválido")]
public DateTime? Date {get;set;}

E na View:
@Html.TextBoxFor(model => model.Date)
@Html.ValidationMessageFor(model => model.Date)

Ao se digitar uma data com o seguinte valor: 11/11/1111, é o valor não o formato, e mando o POST, ele passa no ModelState, mas no SaveChange ocasiona erro:

The conversion of a datetime2 data type to a datetime data type
  resulted in an out-of-range value. The statement has been terminated.

O que tenho feito até agora e não obtive sucesso:
1 - No meu Web.config o seguinte atributo:
 <globalization uiCulture="pt-BR" culture="pt-BR" enableClientBasedCulture="true" requestEncoding="UTF-8" responseEncoding="UTF-8" fileEncoding="UTF-8" />

2 - Instalação do jQuery globalize e jQuery Validate globalize.
A ordem de carregamento é essa:

3 - Tratamento de número e datas utilizando jQuery Validate + globalize, com o seguinte código:
jQuery.extend(jQuery.validator.methods, {
    date: function (value, element) {
        return this.optional(element) || /^\d\d?\/\d\d?\/\d\d\d?\d?$/.test(value);
    },
    number: function (value, element) {
        return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:\.\d{3})+)(?:,\d+)?$/.test(value);
    }
});

Qual a forma de validar essa entrada de data ou criar um "range" no cliente e não no server?
Comment: Por mais idiota que seja, tive um problema semelhante que se resolveu trocando de @Html.TextBoxFor(model => model.Date)
para @Html.EditorFor(model => model.Date)
Comment: @RafaelBarbosa pois é, mas eu utilizo TextBoxFor por causa do meu plugin do datepicker...usando EditorFor não funciona..
Comment: Alias, ele até abre o meu datepicker, mas aí abre também o do Html5 e não seta os valores com o meu datepicker, rs
Comment: @RafaelBarbosa na verdade kkk usando o datepicker do próprio html5 piora a situação, ele não aceita nem o formato que eu passo, sempre falando o campo .. deve ser uma data
Comment: @Rod Qual o valor definido na data antes do `SaveChanges`?
Comment: @CiganoMorrisonMendez na pergunta tem o valor, que é 11/11/1111, sei que é meio improvavel, mas é que sempre tem um usuário que quer preencher para teste tudo com 11 ou valor único 22...
Answer: @Rod, o seu problema aqui não é validação do Type DateTime, mas sim o Range permitido pelo tipo DateTime no SqlServer.
Para resolver este problema, você pode mudar o tipo da coluna no SqlServer para datetime2(7), que inclusive é o tipo recomendado para novas Tabelas.
Ou você pode colocar um DataAnnotations para validar o Range, de forma a ficar semelhante ao do SqlServer
[DataType(DataType.DateTime, ErrorMessage="Isto não é um data")]
[Range(typeof(DateTime), "01/01/1753", "31/12/9999")]
public DateTime Date { get; set; }

Comment: Fiz uma convention que todo datetime gera datetime2 obrigado era isso mesmo
Answer: O problema no .NET
A tradução de:

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.

Seria algo como:

A conversão do tipo de data "datetime2" para "datetime" resultou em um valor fora do intervalo/alcance.

O intervalo deve ser igual ou maior que "Janeiro 1, 1753" conforme o msdn Date and Time Data.

These data types only support dates that occur after the introduction of the Gregorian calendar in England in 1753.
PT: Estes dados suportam apenas datas que ocorrem após a introdução do calendário Gregoriano na Inglaterra em 1753.

Validação no front-end:
Vou supor que em 11/11/1111 seja dia/mes/ano, padrão usado no Brasil, o código deve ficar algo como:
date: function (value, element) {
    var data, dataObjeto, ano;

    if (this.optional(element) || /^\d{2}\/\d{2}\/\d{4}$/.test(value)) {
        data       = value.split("/");
        dataObjeto = new Date(data[2], data[1] - 1, data[0]);
        ano        = dataObjeto.getFullYear();

        return (
            ano == data[2] &&
            dataObjeto.getMonth() === parseInt(data[1]) &&
            dataObjeto.getDate() === parseInt(data[0]) &&
            ano > 1900 && ano < 2100
        );
    }
    return false;
}

Vou explicar o código:

data = value.split("/"); divide o data que é uma string
dataObjeto = new Date(data[2], data[1] - 1, data[0]);, data[2] é o ano, data[1] o mês e data[0] o dia, assim o construtor new Date irá poder fazer o comparativo se a data é "valida".
ano == data[2] verifica se o ano do value é igual ao ano que o new Date "entendeu", se for diferente é por que a data foi reajustada e o usuário provavelmente colocou um valor errado ou aleatório.
dataObjeto.getMonth() === parseInt(data[1]) compara se o mês foi o mesmo que recebido pelo value.
dataObjeto.getDate() === parseInt(data[0]) compara se o dia foi o mesmo que recebido pelo value.
ano > 1900 e ano < 2100 é o seu intervalo/range permitido, você pode alterar.

Neste código se o usuário adicionar uma data como está 29/02/2015 (não é ano bissexto, portanto não existe dia 29) o new Date irá gerar está data 2015-03-01T03:00:00.000Z (1 de Março de 2015), portanto a data inserida pelo usuário é inválida e o validador fica em false
Acaso o campo apresentar hora e data:
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy hh:mm}")]

Você pode usar a validação a RegEx assim:
/^\d{2}\/\d{2}\/\d{4} \d{2}[:]\d{2}$/

E o código deve ficar assim:
date: function (value, element) {
    "use strict";
    var horaData, data, hora, dataObjeto, ano;

    if (this.optional(element) || /^\d{2}\/\d{2}\/\d{4} \d{2}[:]\d{2}$/.test(value)) {
        horaData = value.split(" ");

        data = horaData[0].split("/");
        hora = horaData[1].split(":");

        dataObjeto = new Date(data[2], data[1] - 1, data[0], hora[0], hora[1]);
        ano = dataObjeto.getFullYear();

        return (
            ano === parseInt(data[2]) &&
            dataObjeto.getMinutes() === parseInt(hora[1]) &&
            dataObjeto.getHours() === parseInt(hora[0]) &&
            dataObjeto.getMonth() === parseInt(data[1]) - 1 &&
            dataObjeto.getDate() === parseInt(data[0]) &&
            ano > 1900 && ano < 2100
        );
    }
    return false;
},

Comment: @GuilhermeNascimento quase... editei ali com o que achei pertitente... verifica por favor... aqui funcionou... ;) (Y)
Comment: Olá @Guilherme,obrigado por responder, eu sei qual é o erro, é a tipagem que está no banco de dados, minha pergunta está relacionada, a como validar esse erro, mais precisamente na View
Comment: @Rod eu editei, agora me atentei a sua pergunta.
Comment: e quando for um campo de datetime mas que seja apresentado data e hora, acho q desse jeito não vai aceitar....
Comment: @rbrock Modifiquei a resposta, veja se o exemplo lhe ajuda.
Answer: O roteiro de resolução está em duas respostas que já escrevi:

Problema ao armazenar valores decimais no SQL Server
Jquery validate não valida corretamente
Comment: @GustavoAdolfo Ele fez a configuração se baseando em duas respostas minhas. Em teoria já devia estar funcionando.
Comment: eu possuo o globalize de forma correta, e também o culture no Web.config principal(não os da areas) e ainda ocasiona o erro que citei
Comment: Instalou os JS?
Comment: Sim, essa mesma lib do nuget que está no link
Comment: Bem, posso estar falando bobagem, mas o erro não se refere à conversão na hora de tentar gravar na base de dados? O campo da tabela não estaria no formato yyyy/mm/dd???
Comment: @GustavoAdolfo Penso que é isso mesmo. Em teoria é alguma coisa no formato apenas na hora de gravar.
Comment: @CiganoMorrisonMendez , penso a mesma coisa pela mensagem de erro. Já me aconteceu coisa parecida e fiquei procurando problema onde não existia, até perceber o detalhe... Mas não sei se é o caso aqui.
Comment: Olá @CiganoMorrisonMendez *Se* a resolução está em duas resposta que você já escreveu, então isto não tornaria está atual questão uma duplicata?
Comment: @GuilhermeNascimento Mais ou menos. Creio que o problema não esteja descrito em nenhuma delas, a julgar pelo que foi colocado aqui até então. Estou com pouco tempo para ajudar agora.

Validar Datetime no cliente


Error in Burnside's "Theory of groups of finite order"?

Question: In W. Burnside's "Theory of groups of finite order" on page 16 where is proposition that for all permutable $S_q$ and $S_r$ if $S_p=S_qS_r$ then $\text{order}(S_p)=\text{lcm}(\text{order}(S_q),\text{order}(S_r))$. But it is not true even in cyclic groups. What I do not understand?
Answer: You are wrong. Burnside does not write that. He writes
"and in that case the order of $S_p$ is equal to or a factor of the least common multiple of the orders of $S_q$ and $S_r$."
Comment: My personal recommendation is not to read Burnside's book unless you have an excellent command of the English language, particularly as spoken in the early 1900s. For example, to introduce the notation for the group generated by a set of elements, he states: "It is convenient here to explain a notation that enables us to avoid an otherwise rather cumbrous phraseology."
Comment: "Avoid an otherwise rather cumbrous phraseology": task failed successfully.


Newbie ask Swap Value: How much Swap do I have?

Question: When looking vmstat, this is what I got:
procs -----------memory---------- ---swap-- -----io---- --system-- -----cpu------
 r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa st
 1  0      0   2872      0      0    0    0     8    17    0   14  3  1 94  2  0

the cache is 0. I have no idea how much the whole swap I have.
But when not enough RAM (256 MB), the swap will be used and look like below:
procs -----------memory---------- ---swap-- -----io---- --system-- -----cpu------
 r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa st
 3  1   2468      0      0      0    0    0     8    17    0   16  3  1 94  2  0

Answer: Assuming this is on Linux - free -m will show you how much memory/swap you have in MB. Or cat /proc/meminfo
Answer: To see information about swap files currently in use on Linux:

cat /proc/swaps

or refer to swap information in meminfo for less detail:

cat /proc/meminfo | grep Swap
Answer: One of the header lines in top will be Swap info, and it's very clearly broken down.
This also has the advantage of working on any platform where top is installed (Every Linux/BSD I know of. Most Solaris, AIX & HP-UX machines (if it didn't come with the system some admin usually got around to installing it)).
Comment: Sounds like you don't have any swap configured (or it's not attached/enabled) -- that's a bit unusual but not impossible.  Are there any lines in /etc/fstab with type "swap"? If so try "swapon -a" (as root) & the system will try to enable them.
Comment: True that top is almost everywhere, but I was surprised to find it missing on Tru64. Not that anyone cares about that any more...
Comment: (I got from top) Swap:        0k total,        0k used,        0k free,        0k cached
Comment: `htop` is a more friendly version. :)
Comment: @EricR - True, but `htop` isn't everywhere (for that matter neither is `top`, but you know it will be there on the systems I listed).  I suppose the *truly* portable alternative is `swapinfo`, but that requires you to do your own math for totals if you have more than one swap partition - `top` does it for you :-)
Answer: Many systems have some command to detail this information outright: the commands are usually one of: swap or swapinfo or swapon (with appropriate option). Look up the man pages for these commands to find the specific information.
Answer: Execute
mkswap /path/to/dev

Then run
swapon -a


browscap.ini is not configured in php.ini

Question: In my status report I'm still getting this error:
<code>Browscap data   /   browscap.ini is not configured in php.ini.
</code>
When I searched on the internet I found this topic that suggested this:
<code>[browscap]
; http://php.net/browscap
browscap = "C:\xampp\php\extras\browscap.ini"
</code>
I've download full_php_browscap.ini file on browscap.org and placed it in the root where my php.ini is also located (also changed the name to browscap.ini).
Then I've placed this in my php.ini file:
<code>[browscap]
browscap = "/domains/mydomain.be/public_html/staging/browscap.ini"
</code>
But I'm still getting the error ... . My php.ini file is located in the same directory as the browscap.ini file.
Answer: I fixed this with the module Browscap.


Determining a group of duplicates and finding its max/highest no

Question: Unsure if the solution is VBA/Macro or a formula in excel. However the goal is copying Value of the Highest/Max Term # within a group of accounts having the same account name to it's corresponding AValue. [Image below]
Note: The accounts are already sorted and cannot be sorted to another format as it deals with 7000+ entries
Answer: You can solve your problem through 2 ways:
1: You can sort your data based on column A and column B both ascending. then you can insert the following formula in cell D3 and copy it down.
<code>=IF(A3=A4;"";C3)
</code>
2: You can also use the following formula in cell D3 and copy it down:
<code>{=IF(MAX($B$3:$B$15*IF($A$3:$A$15=A3;1;0)) = B3;C3;"")}
</code>
Note that first you must enter

=IF(MAX($B$3:$B$15*IF($A$3:$A$15=A3;1;0)) = B3;C3;"")

in cell D3 and after finishing the formula and while you are in edit mode, you must press Ctrl+Shift+Enter together. Excel automatically generate the above formula. If you write "{" and "}" manually, the formula won't work.


Retornar mensagem do else

Question: Estou fazendo um exemplo bem simples usando Django.
Na minha view tenho o seguinte :
def index(request,idade):

    string = '''
        {% if idoso >= 65 %}
            Você já é idoso
        {% else %}
            Você não é idoso
        {% endif %}
    '''
    t = template.Template(string)
    c = template.Context({'idoso':idade})
    return HttpResponse(t.render(c))

Mas mesmo que eu passe qualquer valor ele sempre retornará a mensagem do if, ou seja, se eu passar 10 ele retornará: você já é idoso.
Alguém sabe por que isso está  ocorrendo ?
OBS : Uso Django 1.11.
Comment: Beto , verifique se vc está passando de verdade algum valor para sua view, o if pode esta sendo acessado pois esta passando o valor errado.
Você tem o código antecessor desse ? aonde vc define os valores ?

Uma dica: Não seria melhor fazer esse procedimento direto no html ?
Comment: Otávio Reis Perkles, era o tipo da variável que não estava na forma correta para passar pro Context. Estava fazendo dessa forma somente como forma de aprendizado, mas realmente é melhor usar no html.
Answer: Provavelmente deve esta fazendo algo do tipo:
 url(r'^algo/(?P<idade>\d+)/$', views.index)

Ao passar o valor por uma regex possa ser que não seja no tipo desejado mesmo que se use o \d+, por exemplo.
Para solucionar esse problema é melhor certificar que ele estará no tipo desejado, logo faça :
int(idade)

Dessa forma o código abaixo funciona bem.
def index(request,idade):

string = '''
    {% if idoso >= 65 %}
        Você já é idoso
    {% else %}
        Você não é idoso
    {% endif %}
'''
t = template.Template(string)
c = template.Context({'idoso':int(idade)})
return HttpResponse(t.render(c))

Retornar mensagem do else


Find value from a search list in a cell ( Excel Formula; Sumif, sumproduct etc )

Question: I have a question as below:
I have a list of numbers in a different sheet ( INFO) in a column for example H:H:
Includes?
59701
59702
59744
59761
59774
59817

... and I have a details in different sheet (DB) at U:U:
3*58.00  Std - 7*17.40 N59020:
2*72.00 : Std - 7*21.60 N59020:
7*72.00 : Std - 7*21.60 N59020:
5*100.00 N59872:
71*100.00 N59872:

I write a formula in DB column "Z2":
=IF(SUMIF(U2;"*59701*")>0;"Yes";
    IF(SUMIF(U2;"*59702*")>0;"Yes";
       IF(SUMIF(U2;"*59744*")>0;"Yes";"No") ...

My question is top formula need to define all search details, I need to repeat every number that includes at search Info.
Is there a way to define this Info search list, in order not to repeat the formula for every different number?
Thank you for your supports and sorry for my English.
Comment: are they always 5 digits and always at the end like you examples?
Comment: BTW I think you translated the formula incorrectly.  You probably meant COUNTIF not SUMIF because SUMIF will try to sum it and if it is a string like you show it will always return `0` even if found.
Comment: @ScottCraner yes sorry countif, and for now  always 5 digits...
Comment: Then try: `=IF(ISNUMBER(MATCH(MID(U2;LEN(U2)-5;5);'Info'!H:H;0));"Yes";"No")`
Comment: @ScottCraner, i tried it but in U2 this number maybe starting at 13, sometimes 9, for example (3*58.00  Std - 7*17.40 N59020:) it starts 24, but searching number always 5digits.
Comment: That is why I asked if it is always at the end like your examples.  All your examples have it starting 6 places from the right.  If it always start 6 places from the right then this will work.  It does not matter the full length of the string just that the numbers are 6 places from the right.
Comment: @ScottCraner sorry for that, i tought you are asking about source search criteria, in U2 where searching number details always changing.
Answer: I found the answer,just sharing;
=IF(OR(COUNTIF(U2;Info!$I$2:$I$28));"Yes";"")

In column I:I i made formula to add wildcharacter "*"; for example now search become --

59701

thank you for all for helping :)


Strict order of points within a tolerance on a 2d plane

Question: I have a situation that I want to define a strict order of the points on a 2d plane, such that point1 < point2, which point is represented by (x, y) in real number. I also want that two points are equal if they are close enough, say, in a tolerance.
My initial intention is to use the dictionary order of x and y like below to define the order of points,

If x1 < x2, then point1 < point2
If x1 == x2 and y1 < y2, then point1 < point2
If x1 == x2 and y1 == y2, then point1 == point2
The equality is defined within a tolerance, e.g. a == b if a - b < tolerance

But, quickly I realize that strict order defined above will cause following contradiction, e.g. I have three points, p1, p2 and p3, satisfying

x1 == x2 and y1 == y2 both in a tolerance, then p1 == p2
x2 == x3 and y2 == y2 both in a tolerance, then p2 == p3
x1 < x3 (as x3 - x1 > tolerance), then p1 < p3
So, it turns to p1 == p3 and p1 < p3, which is wrong. The transitivity can't work.

Then, I come to another thought,

Define a many-to-one mapping from real number to integer number by a given tolerance, e.g. if the tolerance is 0.1, then any value ranging from (0 ~ 0.1] maps to 1, similarly (0.1 ~ 0.2] maps to 2, and so on.
Then, each coordinate of point (x, y) can map to (a, b) which a and b are all integers.
Finally, determine the order of points strictly based on the dictionary order of integer numbers.

I am not sure whether my though is feasible, especially I want to program them in real case. And, if it can work, what is the mapping should I take from real number range to a integer number? Or any other good suggestions on this problem?
Answer: It is easier to see the problem if we just work in one dimension.  There is the usual order on $\Bbb R$, but if you define $a==b$ if $|a - b|\lt t$, where $t$ is your tolerance, then the transitivity of equality forces all numbers to be equal.  Take a number $a$, let $b=a+\frac 34t, c=b+\frac 34t$.  Then $a==b==c,$ but $|a-c|=\frac 32t$
It gets even worse in 2D with the dictionary order, as you see.  In that order, points with different $x$ values are very far apart, no matter how small the difference in $x$.  You are collapsing them together.
For your idea of collapsing reals to integers, you will always have cases where reals that are close together map to different integers.  In your example $0.0999$ maps to $1$, but $0.1001$ maps to $2$, which is contrary to what you want everywhere else.
Comment: Yes, I see that reals are close but still map to different integers. I think this is something I have to compromise, so as to make the order relationship working consistently.


Are modes in jazz primarily a melody thing?

Question: I was wondering when jazz cats talk about how they'd use a Lydian scale to improvise over a major chord, or a Dorian scale to improvise over a minor chord they're mainly talking about the melody? So the harmony is generally diatonic chords of the scale (say ii7-V7-I7). So in the key of C major that'd be Dm7, G7, Cmaj7. The improvisation (as an example) would be D Dorian, G Mixolydian, C Lydian. So in a piano, that'd just be my right hand doing that modal stuff (and keep away from b9 avoid notes with whatever chord tone I'm currently on) and my left hand remains in C major.
Does that sound right? I think the improvised melodies are modal and sometimes altered modal scales. But we're just talking about the melody right? They keep the harmony pretty basic/diatonic chords?
Edit: the word 'modal' was used wrong here. I just meant modes.
Comment: To play in a mode is more than just playing the right notes. You need to make the root of the mode feel like home and that is the difference between playing in C major or D Dorian. Same notes but D sounds like home in one and C in the other
Comment: @robertbristow-johnson - that's exactly how the modes are perceived. The 3rds are defining. Can't have a *diminished key* though!
Comment: @robert bristow-johnson - funnily enough, I call it the 'Locrian mode'.  Rarely use it - same as most players, but it certainly is not a key. That's pretty well an accepted fact.
Comment: I think of the Dorian mode as a sorta *"Chanty"* variant of a minor (or Aeolian) key.  All the same except for that 6th.
Comment: just because of the major or minor third, i like to think of Ionian, Mixolydian, and Lydian as "major" modes, Dorian, Phrygian, and Aeolian as "minor" modes, and Locrian as a diminished key.
Comment: @b3ko exactly, I guess my question is does the harmony/left-hand change that root or does it keep it in the original scale. I've been looking at jazz standards and they all seem diatonic (except for secondary dominants) as far as whatever scale is currently being played harmony wise. the melody however, really changes things up when improvisation is concerned.
Comment: so @Tim , what do you call the Locrian mode?  B-to-B on the white keys.  diminished 5th.
Comment: yes @Tim , it's a *"mode"*, not a *"key"* (like C, D, E).  but i sometimes swap the usage of the two terms.  i am a little sloppy with terminology.  but it sounds like a diminished "mode" (or "key") or whatever because of that flat 5th (or augmented 4th).
Comment: @robertbristow-johnson - Yes, a *key* consists of a certain specified set of notes, while the *scale* is that set of notes in an ordered way - lowest>highest, and vice-versa. A key will always have a root (or *home*) note, and scales are played from that root note, generally. They're nearly interchangeable terms, but not exactly. Could be a good question to pose.
Comment: okay, one source says that the "B diminished scale" is B, C#, D, E, F, G, Ab, Bb, B.   seems to be 9 notes instead of 8.  so is the correct nomenclature is that the *"mode"* is "*diminished*"?  and if it's B, C, D, E, F, G, A, B would the scale be "B Locrian" and the mode is "Locrian"?  With minor 3rd and dim 5th, they both sound diminished.
Answer: The simple/traditional approach is for the chords to match the scales you're improvising over. You wouldn't improvise with C Lydian in your right hand and simultaneously play a CMaj11 chord--the F in your left hand would clash with the F♯ in your right hand. Similarly, if you improvise over the V7 chord using the G altered scale, you wouldn't simultaneously play a G9 chord--the A♭ in your right hand would clash with the A♮ in your left hand.
To your question "are modes in jazz primarily a melody thing?" the answer is: modes are simply fancy names for scales. These scales can be used to define the melody and the harmony. The straightforward approach is for those two things (melody and harmony) to agree with each other.
One small terminology note: just because you're using a mode to solo doesn't mean you're improvisation is "modal." The adjective "modal" usually refers to a style of composition that avoids traditional harmony, etc. Simply using a mode to construct an improvisation wouldn't qualify the solo as "modal."
Comment: @user45266, totally agree. I was trying to distinguish from those scenarios by using words like straightforward, simple, traditional, etc. but it didn't quite feel right because of how established it is to go out!
Comment: Yeah, and I think you did a good job doing it, but when I find an opportunity to be nitpicky, no force on this Earth can stop me! :)
Comment: @user45266 Haha, not nitpicky at all--a useful addition! foreyez, it's worth mentioning that there are many songs where the chords don't all fit diatonically into one key. There's a spectrum. On one end is e.g. Autumn Leaves, & on the other end is e.g. Giant Steps. As you spend more time studying jazz you'll encounter more songs with non-diatonic chords. Some of the first ones I ever encountered were **[I Love You](http://www.guitarcats.com/images/JazzStandardCharts/BEAUTIFUL%20LOVE-39.jpg)** and **[Beautiful Love](http://www.guitarcats.com/images/JazzStandardCharts/BEAUTIFUL%20LOVE-39.jpg)**
Comment: As an aside, if you want to break from the more traditional convention, you *could* play a left-hand chord that clashes with the right-hand improvisation.
Comment: Or you could play some melodic line way outside what your band is comping with, happens all the time. +1
Answer: At the risk of sounding over-critical, your example of Dm7 - G7 - Cmaj7 using the three modes of D Dorian - G Mixolydian - C Lydian (or maybe C Ionian?) would in fact be using the same 7 notes all through the sequence. With your change of #4 in C Lydian. That idea is as simple as one would use when improvising over those three chords in any case - obvious target notes being D, G and C in turn.
Since you're talking 'scales and modes', this will be essentially melody playing. Over existing chords, usually belonging to an already written song - a standard, maybe. So the harmony/chords are already there to be played over, denying them the pleasure of being labelled 'modal' anyway.
So, I don't think there is any particular 'modality' involved here.
Also, ♭9 isn't always an avoid note - I use it regularly - it has as much credence, being a semitone away from a potential target note, as the leading note has.
Comment: When both the lower chromatic neighbor and the upper chromatic neighbor are combined you get the _enclosure_. Definitely not always an avoid tone.
Comment: @MichaelCurtis, an enclosure doesn't have to us a half step above. Perhaps the most common enclosure in bebop is a half step below the target and a scale step above the target.
Answer: You're sort using mode and modal interchangeably, but you probably shouldn't. Modal implies a jazz style different from your ii V I type playing. The essence of this question was covered in questions you asked previously. I don't really understand why you've posted again.
Yes, you are describing the "chord/scale" approach correctly. The kind of thing you find from Jamey Abersold...

...on that page he uses Ionian for the I chord, and the solid note heads apparently are for the chord tones. This one just shows ii V I in all major keys.
I think it strange how the lesson is titled with "all major keys", but then it doesn't show key signatures, but spells out the scale with accidentals. I really don't understand this attitude from jazz teaching. It seems to me on one hand they acknowledge major/minor keys are in effect, but then don't want to use key signatures. Notice also Roman numeral analysis is used in the title ii/V7/I, but then some people say jazz harmony is chromatic and non-functional. I understand it, but from a teaching perspective it seems confusing for a beginner. The chord/scale system seems like an attempt to avoid learning functional harmony.
Anyway, Abersold has special lead sheet for jazz standards that look similar to this ii V I lesson where the chord changes are above the staff and the basic scale is notated. For example, he has Maiden Voyage with changes and notated scales. The idea seems clear: the chords come from an original song and scales are selected to match the given chords...

The other option - the historical way - is to play the arpeggios for the chord changes with embellishments like diatonic passing tones or lower chromatic neighbor tones.

EDIT
From these comments...

To play in a mode is more than just playing the right notes. You need to make the root of the mode feel like home and that is the difference between playing in C major or D Dorian. Same notes but D sounds like home in one and C in the other – b3ko

...and...

@b3ko exactly, I guess my question is does the harmony/left-hand change that root or does it keep it in the original scale. I've been looking at jazz standards and they all seem diatonic (except for secondary dominants) as far as whatever scale is currently being played harmony wise. the melody however, really changes things up when improvisation is concerned. – foreyez

...I get the sense you are confusing the idea of tonic and chord root.
The wording in those comments should be tonic of the mode when speaking of scales and tonal centers. Root should only be used when talking about chords.
When you play C: ii7 V7 I it is diatonic, the key is C major, the tonic is C.
The root of ii7 is D but it doesn't mean the tonic has changed to D Dorian. The tonality isn't switching from C major to D Dorian. The harmony is not modal. The chord root is D and the tonic is C. In such a case Dorian is just a fiction of the chord/scale system.
The similarity of playing a full octave scale from D4 to D5 in C major to D Dorian is coincidental. The real difference between the two is entirely a matter of how the harmony is handled.
At the risk of mixing styles, I think a classical example offers a good comparison. This is a famous passage, scale based, clearly diatonic, in C major...

https://imslp.org/images/4/48/TN-Mozart_Werke_Breitkopf_Serie_20_KV545.jpg
...conveniently the harmony is ii7 V4/2 I. The treble part is  a scale F4 to F5, but no sensible analysis would say the passage is in F Lydian. All the tones for F Lydian are there, and there is an F Lydian scale, but that is coincidental and doesn't matter. The harmony is what counts and it's clearly C major.
We can compare that to the follow from a handout from a jazz improvisation college course...

http://www.mikesteinel.com/resources/A-Guide-To-Change-Running.pdf
...the treble part plays the exact same descending line. It's all the tones for F Lydian, but it makes no sense to identify it that way. It's in C major.
The chord/scale system would describe this descending line as ^3 to ^7 of D Dorian followed by ^3 to ^7 of G Mixolydian ending on ^3 or C Ionian. All of which is coincidental to the completely obvious point that the whole line is F5 to E4 in C major.
That example is a bit unrealistic, because it's just part of a lesson. We can use another example that looks more like a real improvisation...

...the line over Dm7 certainly looks like it's a partial D Dorian scale. But the important point is the music is not in D Dorian. It doesn't matter that you played a nearly complete D Dorian scale starting on the purported D tonic. That D Dorian look-a-like scale is just a coincidence. The passage is simply in C major. It isn't even temporarily in D Dorian.

...I guess my question is does the harmony/left-hand change that [tonic] or does it keep it in the original scale?

No. When you play anything that is properly a ii7 or V7 you are not changing the tonic. Yes, it keeps to the original scale of C major. Playing D4 to D5 over a ii7 in C major is just playing the C major scale except your aren't starting on the tonic.
The chord/scale system notion that it is a D Dorian scale simply because you started on D and ascended step-wise can just be turned around. If we dont't do that and play something like this...

...why should be regard it as derived from D Dorian? There isn't a step-wise scale, there isn't even a D!
Of course the reply is: it is not derived from D Dorian. It is derived from C major and emphasizes the chord tones of ii7 with the E extending it to ii9 or it could be regarded as an anticipated appoggiatura to the chord tone D of G7.
I think you should really look at other jazz methods and not stick doggedly to the chord/scale system. That system has it's critics and there are people who teach a functional harmony/chord tone approach.
Comment: I never asked a question asking explicitly if modes are used in melody versus harmony.
Comment: Also on one hand you're saying I'm describing it correctly, but on the other hand jdjazz is saying that both the melody and harmony use modes. so I'm still confused.
Comment: I added an image of an Abersold lesson so you can see one way it is taught.
Comment: @foreyez, there's a phrasing here, but there's also something more substantive at issue. First the phrasing issue: a mode is just a scale. The mode we use to improvise can *influence* the chord we choose. But that doesn't change the fact that the mode is a scale, and it doesn't change the fact that a chord is a chord. That said, we can choose chords that match modes. If you want, you can often think of it as though we're building a chord using 1-3-5-7 (etc.) from the selected mode.
Comment: @foreyez, on the substantive issue. To me it seems like Michael Curtis & I disagree. I don't fully understand what he's looking at when he says "you are describing the 'chord/scale' approach correctly." I tend to disagree, and I think your original statement ("that'd just be my right hand doing that modal stuff--and keep away from b9 avoid notes with whatever chord tone I'm currently on--and my left hand remains in C major") does *not* describe the "traditional" approach. The traditional approach is: if you change the mode in the right hand, then make the corresponding change in the left hand.
Comment: If you listen to old live tracks with Brad Mehldau & Joshua Redman, you can hear Josh going out during his solo, & Brad deviating from the written chords to follow along. If you're comping while a horn solos, you're generally expected to listen for chord substitutions & follow along if you hear them occurring. A saxophonist I used to play with had favorites: on a ii-V-I at the end of a tune, he would frequently add another ii-V a minor third up, which is pretty common. He also liked to replace ii-V-I's with Coltrane changes. The expectation is that I'd hear this & play the substituted chords.
Comment: But if you listen to some of the free jazz that Coltrane produced near the end of his career, you'll hear the piano playing chords that clearly clash with the saxophone. Oftentimes, no attempt is being made by the pianist to match the melody that Coltrane is creating. That wasn't really the point, and that objective didn't exist in those tracks in the same way that it does on, e.g., a more straight-ahead Stan Getz track.
Comment: @MichaelCurtis, the Lydian example is the one foreyez specifically asks about. I see what he means, but a more dramatic example would be "do you play the G altered scale in your right hand and a regular G9 chord in your left hand?" That's the question he's asking: should the left hand stick to the written chords/key while the right hand is using modes to deviate. I don't think he's asking how to pair chords with scales in general, and when I read your answer, I wonder if we interpreted the question differently. Also, Maiden Voyage is a great example of the value of notating every accidental.
Comment: @foreyez, I see your question (a) describing a technique where you play "outside" of the written key in your right hand while simultaneously playing "inside" the written key with your left hand and (b) asking whether this is the typical approach. While it's not typical, I certainly don't want to suggest that the technique you describe is prohibited. It is more of a modern, edgy, or dissonant sound. But the common wisdom is for the harmony to follow the melody during instances where the melody deviates.
Comment: @jdjazz, the OP isn't asking about all those outside ideas. From the OP question and comments: "the harmony is generally diatonic chords of the scale (say ii7-V7-I7)" and " I've been looking at jazz standards and they all seem diatonic (except for secondary dominants)"
Comment: @MichaelCurtis, I disagree. "The improvisation (as an example) would be D Dorian, G Mixolydian, C Lydian. So in a piano, **that'd just be my right hand doing that modal stuff** ... and my left hand **remains in C major.**" The OP considers C Lydian to be outside of C Major, and is distinguishing the right hand (in C Lydian) from the left hand (which remains in C Major and doesn't follow the modal choice).
Comment: @MichaelCurtis, see also: "I think the **improvised melodies** are modal and sometimes **altered modal scales.* But we're **just talking about the melody** right? They **keep** the harmony [i.e., left hand] **diatonic** chords?" The OP says that the right hand (which plays melodies) uses the "altered modes" while the left hand (which plays chords) "keeps" with "diatonic chords." CMaj#11 is not diatonic to CMaj.
Comment: I read "I think... sometimes altered modal..." The OP is tentative about what is expected in the improvized melody. More importantly the OP does not include any example specifically about a conflict between scale and chord tones. _You_ are adding that complication. And using `#^4` (Lydian mode if one insists on using chord/scale terms) can be played over a plain `Cmaj7` without necessarily changing the chord to `Cmaj7#11`.
Comment: @jdjazz, can you put all those comments in response to foreyez in _your_ answer please? I read your reply to me about conflicting scales and chords. I don't think that is the main point of the OP.
Comment: Yes, I'll edit those in. I commented here too because the way you characterized my answer was different from how I was thinking about my answer, and different from how I was thinking about the question. @foreyez, can you clarify what you meant in your question?
Comment: @foreyez, can you pose that question to jdjazz on _his_ answer? (I deleted my comment about his answer) Let him explain it in his own words. I think you understand the essence of the chord/scale system. But I am also a critic of that system. You don't seem confused. That system has flaws.
Comment: @MichaelCurtis, the chord/scale system is the widest use approach to teach jazz improvisation by college professors. It's endorsed and utilized by many giants in jazz--not just Jamey Aebersold.


Arimax models : Differencing the xreg

Question: I am solving some time series problem. For this, I am using auto.arima function from forecast package in R. I noticed in many threads that auto.arima does the difference for xreg given y(the dependent time series), while auto.arima estimates the parameters. So that makes my life easier. I do not have to worry about the stationarity of y, auto.arima will handele it automatically.
https://stackoverflow.com/questions/38505159/auto-arima-not-differencing-while-it-should
My purpose is to understand how actually the forecast takes place in case of arimax models, so that I can explain the forecast to clients.
To explore the forecasting part, I went through the forecast function, and then to stats:::predict.Arima function. In both of these functions, xreg is not differnced. I want to understand why is this?
If while building models in auot.arima, we are differencing xreg for parameter estimation, why we are not differencing xreg, while predicting/forecasting.
I hope the question makes sense.
Answer: You asked ."My purpose is to understand how actually the forecast takes place in case of arimax models, so that I can explain the forecast to clients."
At the end of the day a useful model may look like  which can be restated as follows  ( possible lags in Y and the error process not shown for simplicity) and also this easily generalizes to multiple inputs both known and imputed via Intervention Detection
What I recognized a long time ago was the need to sell/explain the equation in a PDL/ADL manner in order for the client to fully understand the model/prediction thus I implemented ( and you can also ) an algebraic re-statement in AUTOBOX ( a forecasting package that I have helped to develop ).
The model that was automatically generated for the Leading Indicator example form Box and Jenkins is here

MODELS ARE PRESENTED:
1.PURE MODEL IN TERMS OF THE INPUTS
  Y=K1+[W(B)/D(B)]*X+[THETA(B)/PHI(B)]*A
2.AS A MIXED MODEL INCLUDING LAGS OF Y
  D(B)*PHI(B)*Y= K2
                =+PHI(B)*W(B)*X
                =+D(B)*THETA(B)*A
                 =+PHI(B)*W(B)*X
                 =+D(B)*THETA(B)*A
    WHERE K2 = K1*[D(B)*PHI(B)]
     OR   K1 = K2*/[D(B)*PHI(B)]

ESTIMATION IS ACTUALLY DONE AS A (2)
WHILE THE TABLE PRESENTS IT AS A (1).
IN THE TABLE THE CONSTANT IS K2 WHILE
PRESENTED IN FORM (1) THE CONSTANT IS K1
WE PRESENT IT HERE IN FORM (2).
MODEL EXPRESSED AS AN XARMAX
Y[t] =   a1Y[t-1] + ... + a[p]Y[t-p]
       + w[0]X[t-0] + ... + w[r]X[t-r]
       + b1a[t-1] + ... + b[q]a[t-q]
       + constant
So I delivered a report that was named RHSIDE.TXT.
For example using the leading indicator example of Box and Jenkins (sale data)
this is the report that you are (correctly) looking for

Another classic example the Gasx-Gasy data set from the same source yielded ...based upon a more complicated model .
I have found that this approach has been very successful in "easing the pain" of the customer.
Additionally if future X's have to be predicted you need to address how their forecasts are generated .
EDITED TO RESPOND SPECIFICALLY TO THE QUESTION ABOUT DIFFERENCING:
IF the ARIMA model contains a differencing operator this implicitely acts a differencing operator on any user suggest causals e.g.
     y(t)=w0*x(t) + a(t)/[1-B]

yields   y(t)=y(t-1) + w0*x(t) -wo*x(t-1) +a(t)
 or  y(t)=y(t-1) +[1-B]x(t) + a(t)

so in effect the x enters in terms of differences
Comment: This post comments on the question (and presents an interesting and noteworthy solution to a different problem about displaying prediction formulas), but it does not seem to acknowledge or answer the question itself, which is "In both of these functions, xreg is not differenced. I want to understand why is this?"  For this post to stand as legitimate reply (and not be turned into a comment, which would seriously truncate it) you will need to answer the question.
Answer: Rob Hyndman (developer of the forecast package in R) explains in his blogpost the difference between his R implementation of ARIMAX and the transfer function approach to ARIMAX.  The R forecast package is a regression of the X variables and an ARMA model applied to the regression errors, not a transfer function approach as you've described.
The ARIMAX Model Muddle

Arimax models : Differencing the xreg


How do I alter the options in the add menu link checkbox in the node edit form?

Question: I am hooking the node edit form with hook_form_node_page_edit_form_alter(). How can I alter the available options when adding a menu item for that node?
I need to only show menu items of given node ids:
if (isset($form['menu'])) {
  $node_ids = array(1,2,3);
  // only show those node's menu links in the options
}

Answer: $form['menu']['link']['menu_parent'] is the form array select box for the menu selector widget. $form['menu']['link']['menu_parent']['#options'] contains the key/value pairs for the menu select box.
In your given example, you can use unset($form['menu']['link']['menu_parent']['#options']['my_uneeded_menu_id_option']); to remove your  unneeded menu items.
Comment: I've came that far already, but how do I know which node id is behind each option?
Comment: You should edit your question to reflect what you know, and what you're specifically asking. The menu `#options` array keys are composite keys containing `:`. The `menu_tree` table contains these menu items. If a menu item contains a route referencing a node, it will be listed there. The Menu API might be a better way to retrieve menu items depending on what you're trying to accomplish.
Comment: I've found it out myself, nevermind :) Thanks anyways!


React Admin Saga after login

Question: Working with React-admin I want add a background task. Every 30 seconds or so, I want to check my API if there any new orders. If managed to set this up trough sagas. The downside is, I want it to run only after login, and only for a certain user type. I don't know how to access any authorization inside the saga and can't find anything about it in the docs or online. And on logout I want to cancel the interval.
Here is my saga so far:
import {call, put, takeEvery} from "redux-saga/effects";
import {eventChannel} from "redux-saga";
import {showNotification} from 'react-admin';

const countdown = () => {
    return eventChannel(emitter => {
            const iv = setInterval(() => {
                const req = new Request(`http://my.api.url/orders`, {
                    method: 'GET',
                    headers: new Headers(
                        {
                            'Accept': 'application/json',
                            'Authorization': `Bearer nice_token`,
                        }
                    ),
                });
                fetch(req)
                    .then((response) => {
                        if (response.status < 200 || response.status >= 300) {
                            throw new Error(response.statusText);
                        }
                        return response.json();
                    })
                    .then((response) => {
                        emitter(response)
                    })
                    .catch(error => {
                        console.log(error);
                        // emitter(END)
                    });
            }, 30000);
            // The subscriber must return an unsubscribe function
            return () => {
                clearInterval(iv)
            }
        }
    )
}

export default function* newOrders() {
    const channel = yield call(countdown);
    yield takeEvery(channel, function* (response) {
        if (response.data.length) {
            yield put(showNotification('New order received'))
        }
    });
}

Answer: Redux action declared in react-admin: USER_LOGIN, USER_LOGIN_SUCCESS, USER_LOGOUT.
Check that you have them, if not, you can use instead of them: REGISTER_RESOURCE, UNREGISTER_RESOURCE:
import {
    USER_LOGIN,
    USER_LOGIN_SUCCESS,
    USER_LOGOUT,
    REGISTER_RESOURCE,
    UNREGISTER_RESOURCE,
} from 'ra-core'

const startStopSaga = () => function* () {
  while (true) {
    yield take(USER_LOGIN_SUCCESS) // or REGISTER_RESOURCE

    let current_user = localStorage.getItem('current_user') // Manual rights check
    if (!current_user.rights) {
      continue
    }

    yield race({
      task: call(newOrders),
      cancel: take(USER_LOGOUT), // or UNREGISTER_RESOURCE
    })
  }
}

React Admin Saga after login


file name append with date in python

Question: I am trying to add date in my file name but it is not giving me the correct result. Here is my code.
dates=str(date.today())
f = open('C:Study\CSV'+dates+'output.txt','a')
f.write('\n' + results)
f.close

the file name is generated as CSV2018-01-25output.txt. how to create the file name without the word CSV?
Comment: At a guess, you'd like make the extense name of the file is 'csv'? if so , chanage it to f = open('C:Study\CSV'+dates+'output.csv','a').
Comment: I was able to  fix by giving f = open('C:Study\CSV',dates+'output.txt','a')
Answer: The error is here:
f = open('C:Study\CSV'+dates+'output.txt','a')

Because "CVS" in this case is your file name, i presume you wanna this:
2018-01-25output.txt
In this case try this:
name = 'C:Study\',dates+"output.txt"

f = open( name'a')

file name append with date in python


Alternatives to Hypothesis Testing in R

Question: I've been reading a number of articles and blog posts about issues relating to hypothesis testing. While these sources seem to put forth legit problems with hypothesis testing and it's interpretations, I'm not seeing anything in terms of alternatives to it (beyond bayesian hypothesis testing). What are some alternative to hypothesis testing in R?
Problems with the hypothesis testing approach
So-called Bayesian hypothesis testing is just as bad as regular hypothesis testing
Alternatives to Statistical Hypothesis Testing
EDIT:
For example, let's consider the following situation. We have monthly data for one year where
conversions_a is the control and conversions_b is the experimental data for conversion when using a different headline.
<code>df = data.frame(year_one_a = 1:12, conversions_a = rnorm(12),
                year_one_b = 1:12, conversions_b = rnorm(12)+5)
</code>
Comment: In many cases, intervals (which show effect sizes) are more meaningful that hypothesis tests.
Comment: I think the question needs some context to be answerable. As @Glen says, confidence intervals around a parameter estimate are often more useful than a test that the parameter's true value is exactly zero, but what kind of situations are you thinking of?
Comment: I think it depends on the kind of experiment you're doing, i.e. observational v/s experimental, and the kind of questions you're asking. Is there any kind of particular setting you're interested in?
Comment: I wasn't thinking of a specific situation, just looking to mimic the following question but for hypothesis testing.  http://stats.stackexchange.com/questions/2234/alternatives-to-logistic-regression-in-r
Comment: possible duplicate of [Effect size as the hypothesis for significance testing](http://stats.stackexchange.com/questions/23617/effect-size-as-the-hypothesis-for-significance-testing)
Comment: I am not sure why several people think this is unclear; @amathew is asking for alternatives to hypothesis testing. This might be too broad, or opinion based, but I think it's perfectly clear.
Comment: @Peter: I thought I voted to put on hold as too broad, but perhaps I ticked the wrong box. And it is very broad; after all there's not an R function `hyp.test` you can replace with something else. If his focus is on model selection (as suggested by the third link. which is about AIC & model averaging), then your answer isn't as relevant as it might be to another situation - say hypothesis tests that regression coefficients are equal to zero.
Comment: @Peter I voted to close as unclear because I could think of way too many different interpretations of "alternative." Would it mean (a) unconventional procedures for conducting hypothesis testing in the N-P framework; (b) a different framework for evaluating evidence against a null; (c) a different logical and statistical framework for formulating testable hypotheses; (d) abandoning a testing framework altogether in favor of some other approach (like EDA); (e) other possible interpretations of results in any of (a)-(d); or something else?
Comment: @PeterFlom, I voted to close as a duplicate because based on what I believe is the correct interpretation of this question (although I think whuber has a valid point), the answer is Glen_b's comment, which is discussed in the potential duplicate I linked to. I think your & DLDahly's answers were worthwhile, even though they don't answer the Q as I understand it. I upvoted both of them & think they should stay; I don't think this Q should be merged w/ the other thread.
Comment: @gung Merging the two threads seems sensible; that way, all the good answers (in this thread and the other) stay, and they are in one place. I don't remember how to merge two questions though; do you?
Comment: The "So-Called Bayesian" editorial is incorrect.  It assumes that Bayesians are interested in point null hypotheses, which is seldom the case.  Much more useful is the probability that an effect is greater than zero.
Comment: @PeterFlom, I don't think merging is ideal here, as the answers below wouldn't be a perfect fit under that question as it is stated. However, if you want to do it, merging is a task only moderators can perform; I don't know how it's done, you'd have to ask the other mods.
Answer: One alternative is to forgo p-values altogether and focus on what the results mean. In many situations, p-values answer a question we are not (or ought not be) interested in:

If, in the population from which this sample was drawn, there is no
  effect, how likely is it that, in a sample of this size, we would get
  a test statistic as big or bigger than the one we got?

Instead, we ought to be interested in what the statistics add to an argument about what is going on. This idea is fully developed in the book "Statistics As Principled Argument" by Robert Abelson (link goes to my review) but, essentially, we ought to be asking these questions about the effects we find:

How big are they?
How precise are they?
How widely do they apply?
How interesting are they?
How credible are they?

This can only be done if we are also substantive experts or if we work closely with experts. For example, sometimes small effects are quite interesting - so interesting that they are worth discussing. Indeed, sometimes effects are interesting because they are small - if the literature and theory suggests that they ought to be big.
Highly credible claims require less evidence than ones that are not credible, but credibility has non-statistical sources.
Comment: +1, this is the best statement of this point of view that I've seen from you on CV.
Comment: +1 Excellent suggestions! Of course, one need not forgo p-values in order to consider the answers to your questions. Instead one has to forgo the silly binary determination of 'significant' versus 'not significant'.
Comment: Attempts to face this issue without making clear the distinction between hypothesis tests and significance tests lead to throwing out the baby with the bathwater (p-values are the baby, hypothesis tests are the bathwater).
Comment: Then, @MichaelLew how do you propose testing hypotheses? I'd be eager to read it (would probably need to be a separate answer, not a comment).
Comment: When would you ever want a statistical test to dictate your actions in a manner that excludes addressing the types of questions that you list? If you, like I, would answer nearly never then you nearly never need a hypothesis test. For people interested in evidence the p-value from a significance test can be interesting, but the dichotomous result of a hypothesis test is not. I've addressed these issues in an extensive form in this paper: http://www.ncbi.nlm.nih.gov/pubmed/22394284.
Comment: I should also add a link to a paper of mine that details the relationship between significance test p-values and likelihood functions, as well as debunking many arguments about alleged flaws and inadequacies of p-values. (The paper has now been three times rejected but its arguments and evidence have not been refuted. Who would have thought that there would be unreasonable resistance to the notion that p-values are actually used because they are useful?) To P or not to P: on the evidential nature of P-values and their place in scientific inference: http://arxiv.org/abs/1311.0081
Comment: @PeterFlom Did you see my papers that you might have been "eager to read"? (I forgot to put your handle in the comments.)
Comment: I saw your note. I've read quite a lot on p values.
Answer: This is subjective, and doesn't directly address your question, but I hope it's helpful regardless.
I think people too often conflate a statistical hypothesis with a scientific one, which leads to problems. Regarding the former, the statistical hypothesis being tested is almost always whether the parameter being estimated is zero or not. But with any deeper thought on the matter, one realizes this is often trivial, for all the reasons Peter stated. But because it's called a hypothesis, and it is falsifiable, it seems to satisfy people that something scientific has been achieved.
It also tends to reduced a complex scientific question to the reporting of one key statistical hypothesis. This is further encouraged by how a lot of scientific research is published - thin-slice the bigger problem and report every slice/p-value in a different paper.
Where I am going is this, with respect to your question? I am not offended by statistical hypothesis tests per se, as long as they are applied thoughtfully. In other words, the solution is not just about finding a better statistical approach, but rather about applying a better scientific approach; by clearly specifying a complete theory that can be tested, collecting the relevant data, and then ensuring any statistical modelling or testing directly follows from these, rather than the other way around.
Answer: Following the ideas put forward here http://robjhyndman.com/working-papers/forecasting-without-significance-tests/, you can formulate two models: with and without a dummy variable. Then you can use AIC-like statistics (and start reading about their own problems and misunderstandings).

Alternatives to Hypothesis Testing in R