Prove that if $X\sim\mathcal{N}(0,1)$, then $X^2-1$ is subexponential

Question: Definition:
A random variable $X$ with $E[X]=0$ is called sub-exponential with parameters $(\nu,\alpha)$ iff for each $\lambda$ satisfying $|\lambda|<\frac{1}{\alpha}$, we have:
$$E[e^{\lambda X}]\le e^{\frac{\lambda^2 \nu^2}{2}} $$
We write this as $X\sim \mathrm{SE}(\nu,\alpha)$.

Question:
Prove that if $X\sim\mathcal{N}(0,1)$, then $X^2-1\sim \mathrm{SE}(2,4)$.

My try:
We are trying to prove that for each $\lambda$ satisfying $|\lambda|<\frac{1}{4}$, we have:
$$E[e^{\lambda (X^2-1)}]\le e^{{2\lambda^2}}$$
So, I tried to calculate $E[e^{\lambda (X^2-1)}]$ as follows:
$$E[e^{\lambda (X^2-1)}]=\int_{-\infty}^{\infty} e^{\lambda (x^2-1)}\frac{1}{\sqrt{2\pi}} e^{-x^2/2}dx=\frac{1}{\sqrt{2\pi}}\int_{-\infty}^{\infty} e^{\lambda (x^2-1)} e^{-x^2/2}dx=\frac{1}{\sqrt{2\pi}}e^{-\lambda} \int_{-\infty}^{\infty} e^{x^2(\lambda-\frac{1}{2})}dx$$
It seems to me like I should somehow make the terms inside the integral similar to the probability density function (PDF) of a normal random variable. However, I'm stuck at this stage.
Any idea on how to proceed?
Comment: I'm rather curious why this question got 7 upvotes in less than 30 minutes...
Answer: Your idea to make it similar to the normal PDF is good. With $\sigma^2 = \frac{1}{1-2\lambda}$, we have
$$\int_{-\infty}^\infty e^{-(\frac{1}{2}-\lambda)x^2} \, dx
= \sqrt{2 \pi \sigma^2} \underbrace{\int_{-\infty}^\infty \frac{1}{\sqrt{2 \pi \sigma^2}} e^{-\frac{x^2}{2\sigma^2}} \, dx}_{=1}
= \sqrt{\frac{2\pi}{1-2\lambda}},$$
so in the end you have $E[e^{\lambda(X^2-1)}] = \frac{e^{-\lambda}}{\sqrt{1-2\lambda}}$.
With some calculus you can show that $\frac{e^{-\lambda}}{\sqrt{1-2\lambda}} \le e^{2\lambda^2}$ as desired.

It suffices to show $f(\lambda) := e^{4\lambda^2 + 2\lambda}(1-2\lambda) \ge 1$ for $|\lambda| < 1/4$. By looking at the derivative $$f'(\lambda) = [(8\lambda+2)(1-2\lambda) - 2]e^{4\lambda^2 + 2 \lambda}
= 4\lambda (1-4\lambda) e^{4\lambda^2 + 2\lambda}$$
you can tell that the function is decreasing on $(-1/4, 0)$ and increasing on $(0, 1/4)$, so the minimum is achieved at $f(0)=1$.
Comment: Thanks for your help. Would you please elaborate more on the last part? How should I show that? (you said with some calculus... would you please explain it more?)
Comment: @ArmanMalekzadeh Updated my answer.


$p(x) = x^3 - 2x^2 + 4x - 8$ and $x = 2$ is a $0$, use synthetic division to obtain factorization of $p(x)$

Question: Here is what I have, and I would like to get it verified.
$$p(2) = 0 = x^3 - 2x^2 + 4x - 8\\
  \frac{(x - 2)} {(x^3 - 2x^2 + 4x - 8)}\\
    x^2 + 4 = x^3 - 2x^2 + 4x - 8$$
I think the synthetic division answer is $(x^2 + 4)$

Is this correct?
How do I take this to identify other solutions?

I need to factor the polynomial using synthetic division then I need to identify other solutions of $p(x) = 0$.
Comment: [MathJax tutorial](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference)
Answer: You can use synthetic division, or simply use inspection, to find that
$$
(x^3-2x^2+4x-8)=(x-2)(x^2+4) \, .
$$
Notice how the parabola with the equation $y=x^2+4$ does not touch the $x$-axis:

Hence, the equation $x^2+4=0$ has no real solutions.
Answer: Yes you factor is correct.
$x^3 - 2x^2 + 4x - 8 = (x-2)(x^2+4)$
Solutions for
$p(x) = 0$
$(x-2)(x^2+4) = 0$
$(x-2) = 0 \Rightarrow x=2$
$x^2+4 = 0 \Rightarrow x^2 = -4  \Rightarrow x = 2i ,x =-2i$
So three roots are $2,2i,-2i$


How to compute $\mathbb{E}[\text{ReLU}(pX-qY)] $ and $\mathbb{E}[pX\mathbb{1}(pX-qY>0)]$ where $X\sim B(K, q), Y\sim B(K, p)$?

Question: Let $X$ and $Y$ are two independent binomial random variables where $X\sim B(K, q), Y\sim B(K, p)$. I am wondering how to compute or estimate the following expectations:
$$ \ \mathbb{E}[|pX-qY|]\ \  \text{and}\ \ \mathbb{E}[\text{ReLU}(pX-qY)].$$
where ReLU($x$) = max($x, 0$) Furthermore, what does the distribution of $pX-qY$ look like?
Update: Actually I'm more interested in $\mathbb{E}[pX\mathbb{1}(pX-qY>0)]\  \text{and}\  \mathbb{E}[qY\mathbb{1}(pX-qY>0)]$, where $\mathbb{1}$ is the indicator function. We know that $\mathbb{E}[pX\mathbb{1}(pX-qY>0)]-\mathbb{E}[qY\mathbb{1}(pX-qY>0)]=\mathbb{E}[\text{ReLU}(pX-qY)]$ for which @PedroSebe has presented a nice idea below.
Comment: Cross-posted at https://math.stackexchange.com/q/3580440/321264.
Comment: There doesn't seem to be a closed form.
Comment: @gunes Thanks! I have modified the question a bit.
Answer: Although there is no closed form, if $K$ is big enough we can use Central Limit Theorem to approximate $X\sim\mathcal{N}(Kq,Kq(1-q))$ and $Y\sim\mathcal{N}(Kp,Kp(1-p))$. It follows that $pX-qY$ has asymptotically normal distribution with mean zero and variance given by:
$$\sigma^2=p^2\cdot Kq(1-q)+q^2\cdot Kp(1-p)
\\=Kpq\left[p(1-q)+q(1-p)\right]\\=Kpq(p+q-2pq)$$
Then, using a property of the normal distribution, we get:
$$\mathbb{E}[|pX-qY|]=\sqrt{\frac{2}{\pi}}\sigma=\sqrt{\frac{2Kpq}{\pi}(p+q-2pq)}$$
Now, for the ReLU, let us denote $Z=pX-qY$, for clarity. Then:
$$\mathbb{E}[\text{ReLU}(Z)]=\mathbb{E}[Z|Z>0]\cdot\mathbb{P}[Z>0]$$
Since $\text{ReLU}(Z)=0$ if $Z<0$ and $=Z$ otherwise. Then, using the fact that our distribution is symmetric around zero, we have:
$$\mathbb{E}[\text{ReLU}(Z)]=\frac{1}{2}\mathbb{E}[|pX-qY|]=\sqrt{\frac{Kpq}{2\pi}(p+q-2pq)}$$
Comment: Thank you for your answer! Actually I'm more interested in $\mathbb{E}[pX\mathbb{1}(pX-qY>0)]\  \text{and}\  \mathbb{E}[qY\mathbb{1}(pX-qY>0)]$. (I have updated my question a bit.) Do you have any advice for this?


Custom redirect for form-edit displayed in Views header

Question: I have a content type called 'Checklist' which I bring forward using Views, in it's node-edit form.
I wrote PHP code within the header in order to do this, here it is:
<?php

    $view = views_get_current_view();
    $arg0 = $view->args[0];

    $nodeToLoad = $view->result[0]->nid; //I get the node to load from Fields within my view
    module_load_include('inc', 'node', 'node.pages');

    $node = node_load($nodeToLoad);
    dsm($nodeToLoad);
    $edit_page = drupal_get_form('page_node_form', $node);

    $edit_page['additional_settings']['#access'] = FALSE;
    $edit_page['buttons']['submit']['#submit'][] = 'redirect_submit';
    print drupal_render($edit_page );

    function redirect_submit($form, &$form_state){
        $form_state['redirect'] = 'www.google.com';
    }
?>

Now what I want is to add a custom redirect upon saving this particular form.
I've tried this to no avail:
    $edit_page['buttons']['submit']['#submit'][] = 'redirect_submit';
    print drupal_render($edit_page );

    function redirect_submit($form, &$form_state){
        $form_state['redirect'] = 'www.google.com';
    }

Is it possible to this within the Views header?

Notes:

I have also done this with the Rules module but I'd like to learn
if it's possible to do with PHP code in the Views header so I don't
split functionality in 2 parts of my project.
This can also be easily done using a custom hook but again, if it's
possible to do this within the Views header then that's the trick I'm looking
for.

Thanks.
Answer: You could to use hook_form_FORM_ID. Something like this:
function mymodule_form_page_node_form_ater(&$form, &$form_state, $form_id){
   if(current_path() == 'page/where/my/view/is'){
     $form_state['redirect'] = 'page/to/redirect';
   }
}

If you don't want to use a hook, you can do something like this:
 $edit_page['buttons']['submit']['#submit'][] = 'redirect_submit';

Then,
 function redirect_submit($form, &$form_state){
  $form_state['redirect'] = 'path/to/rediect';
 }

Still it is bad practice to inlcude php in your views header. You should implement a custom area handler.

How to create a view area handler
https://api.drupal.org/api/views/handlers!views_handler_area.inc/group/views_area_handlers/7
https://oliverhuynh.wordpress.com/2011/06/23/custom-views-handler-drupal-7-template/
Comment: I appreciate the answer but I've clearly stated in the 'Notes' section of my question that I would like NOT to use custom hooks. Code that can fit in the Views header PHP code(*like the rest of my code*) is what I'm looking for.
Comment: It is very bad practice to write php code in your views header/footer/fields. I strongly recommend to review your approach to this problem. I will adjust my answer
Comment: Thanks, did not know that. Why do you consider it bad practice? I like the idea of having all the code located within that particular View, *if* the code is simple enough.
Comment: hm, I'm updating the question with the suggested code you gave me. It's still not redirecting for some reason..
Comment: Try redirecting to an internal page of your website
Comment: If that doesn't do the trick try adding $form_state['rebuild'] = TRUE
Comment: nevermind, i've used Rules module to redirect after the save


Erro MethodNotAllowedHttpException in RouteCollection.php line 218

Question:
Minha rota
    Route::put('equipes/insereAluno/{equipe}',['as'=>'equipes.insereAluno','uses'=>'EquipesController@insereAluno']);

Minha blade.
{!! Form::model($equipe,['method'=>'PUT','route'=>['equipes.insereAluno',$equipe->id]]) !!}

            {!! Form::label('disponivel', 'Alunos sem Equipes:') !!}

            {!! Form::select('disponivel',$disponiveis,null,['class'=> 'form-control chosen']) !!}
            {!! $errors->first('disponivel', ':message ') !!}

        @if($modalidades)

            {!! Form::label('modalidades', 'Selecione as provas que o aluno participará: ') !!}

            {{ Form::select('modalidades[]',$modalidades, null,['class'=>'form-control chosen','multiple'])}}
            {!! $errors->first('modalidades', ':message ') !!}

        @endif

            {!! Form::submit('Adicionar',['class'=>'btn btn-primary','title'=>'Adicionar aluno à equipe']) !!}

Minha controller
public function insereAluno(EquipeInsereAlunoRequest $request,$id)
{
    $equipe = $this->equipe->find($id);

    $modalidades = $request->input('modalidades');

    if($equipe)
    {
        if(count($modalidades) > $equipe->modalidade->limite_de_provas)
        {
            Notification::error("O aluno só pode participar de {$equipe->modalidade->limite_de_provas} prova(s) por vez.");
        }
        else
        {
            $alunoEquipe = new AlunoEquipe;
            $alunoEquipe->aluno_id = $request->input('disponivel');
            $alunoEquipe->equipe_id = $id;

            if($equipe->categoria == 'Infantil')
            {
                $num_max = $equipe->modalidade->num_max_infantil;
            }
            else //Juvenil
            {
                $num_max = $equipe->modalidade->num_max_juvenil;
            }

            if($equipe->total_alunos($id) >= $num_max)
            {
                Notification::error("Não é possível inserir mais alunos nesta modalidade.");
                return back()->withInput();
            }
            else{
                try {
                    if ($alunoEquipe->save()) {
                        Notification::success('Aluno inserido na equipe.');

                        if($modalidades){
                            foreach($modalidades as $modalidade)
                            {
                                $alunoEquipeModalidade = new AlunoEquipeModalidade;
                                $alunoEquipeModalidade->aluno_equipe_id = $alunoEquipe->id;
                                $alunoEquipeModalidade->modalidade_id = $modalidade;

                                try {
                                    $alunoEquipeModalidade->save();
                                } catch (Exception $e) {
                                    Notification::error($e->getMessage());
                                }
                            }
                        }

                        return redirect()->route('equipes.show',$id);
                    }

                    Notification::error('Não foi possível inserir aluno na equipe.');

                } catch (Exception $e) {
                    Notification::error($e->getMessage());
                }
            }

        }
    }
    return back()->withInput();

}

Comment: Seu formulário está sendo fechado? Senti falta da função `{{Form::close()}}`
Answer: O método PUT funciona somente quando o seu método de formulário é POST e, em seguida, você adiciona o campo de entrada _method com o valor PUT.
<form method="post">
    <input type="hidden" name="_method" value="PUT">
</form>

Você também pode usar
{{ method_field('PUT') }}

Answer: Experimente trocar de:
{!! Form::model($equipe,['method'=>'PUT','route'=>['equipes.insereAluno',$equipe->id]]) !!}
para
{!! Form::model($equipe,['method'=>'POST','route'=>['equipes.insereAluno',$equipe->id]]) !!}

@method('PUT')

// restande do form aqui

Comment: infelizmente continuou com o mesmo erro.


Spring MVC configuration and mapping

Question: Hate to ask a simple config question but I'm new to the spring mvc framework and for some reason struggling a little bit.  I am working on this just to learn it as I have used MVC in ruby and wanted to try it in java.
I have a sample app that talks to a DB and returns a full table from my controller out to a JSP it all works my table is displaying from the DB Correctly.  I still think I have my configs wrong though as my app only works if my web.xml is setup like so
<servlet-mapping>
    <servlet-name>foo</servlet-name>
    <url-pattern>/RunList.jsp</url-pattern>
</servlet-mapping>

I don't think I should have to use the full name of the JSP in my pattern.  if I just use /  I get
<servlet-mapping>
    <servlet-name>foo</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

Sep 01, 2015 10:53:02 AM org.springframework.web.servlet.PageNotFound noHandlerFound
WARNING: No mapping found for HTTP request with URI [/dyn-qa-qeb/] in DispatcherServlet with name 'foo'

Here is my controller
@RequestMapping(value="/RunList")
public ModelAndView listRun(ModelAndView model) throws IOException{
    //@ModelAttribute
    System.out.println("**** Controller ******");

    List<QAModel> listRun = runDao.list();
    model.addObject("RunList", listRun);
    model.setViewName("RunList");

    return model;
}

I also have an MVC Configuration file that I setup based on a tutorial but I am not sure if that just overrides the web.xml
@Configuration
@ComponentScan(basePackages="com.foo")
@EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter{

     @Bean
        public ViewResolver getViewResolver(){
            InternalResourceViewResolver resolver = new InternalResourceViewResolver();
            resolver.setPrefix("/WEB-INF/jsp/");
            resolver.setSuffix(".jsp");
            return resolver;
        }

        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
        }

Comment: I would love some suggestions here if anyone has ideas
Answer: This was a config issue long ago solved just cleaning up my questions

Spring MVC configuration and mapping


Neural network library for Python for Microsoft Windows

Question: I have been having trouble with selecting a good library for Neural network algorithms in Python.

TensorFlow isn't supported on windows.
Theano is still in the beta phase of development.
PyBrain too is in the beta phase of development.
Scipy supports machine leaning in terms of regression and clustering. But neural networks aren't present.

Please suggest me a reliable and robust library.
Comment: Tensorflow supports Windows
Comment: The latest verison is still listed as 0.8.2.
http://deeplearning.net/software/theano/
Comment: Where did you see that Theano  is still in the beta phase of development?
Comment: good catch :) I have been using it for years, the first time I realized it's technically in beta. (https://pypi.python.org/pypi/Theano lists it as "Development Status :: 4 - Beta")
Comment: Does this mean that there isn't an industry vetted, credible library for neural networks and machine learning in python?
Answer: The most commonly used neural network libraries are Caffe, TensorFlow, Theano, and Torch. TensorFlow officially supports Microsoft Windows.
https://en.wikipedia.org/wiki/Comparison_of_deep_learning_software and best python library for neural networks give a more comprehensive list.

FYI:

How to install Theano on Anaconda Python 2.7 x64 on Windows?
Installing pre-built mxnet packages on Windows
Microsoft's Caffe port for Windows
Comment: I see many of these libraries also provide support for mac OS. Is there a reason for leaving out windows specifically?
Comment: @AnkitBansal just easier to maintain a single OS.
Answer: You can use scikit-learn for neural networks with backpropagation
http://scikit-learn.org/stable/modules/neural_networks_supervised.html
Answer: You can use CTNK https://github.com/Microsoft/CNTK which is actively developed by Microsoft. Blog post: https://blogs.microsoft.com/next/2016/01/25/microsoft-releases-cntk-its-open-source-deep-learning-toolkit-on-github/
It supports Keras which means that you can manage to run a Keras script backed by CTNK. Thus, it is also easy to take a Keras script backed by Tensorflow and run with it CTNK.


Importing a library from (or near) a script with the same name raises "AttributeError: module has no attribute" or an ImportError or NameError

Question: I have a script named requests.py that needs to use the third-party requests package.  The script either can't import the package, or can't access its functionality.
Why isn't this working, and how do I fix it?
Trying a plain import and then using the functionality results in an AttributeError:
import requests

res = requests.get('http://www.google.ca')
print(res)

Traceback (most recent call last):
  File "/Users/me/dev/rough/requests.py", line 1, in <module>
    import requests
  File "/Users/me/dev/rough/requests.py", line 3, in <module>
    requests.get('http://www.google.ca')
AttributeError: module 'requests' has no attribute 'get'

In more recent versions of Python, the error message instead reads AttributeError: partially initialized module 'requests' has no attribute 'get' (most likely due to a circular import).
Using from-import of a specific name results in an ImportError:
from requests import get

res = get('http://www.google.ca')
print(res)

Traceback (most recent call last):
  File "requests.py", line 1, in <module>
    from requests import get
  File "/Users/me/dev/rough/requests.py", line 1, in <module>
    from requests import get
ImportError: cannot import name 'get'

In more recent versions of Python, the error message instead reads ImportError: cannot import name 'get' from partially initialized module 'requests' (most likely due to a circular import) (/Users/me/dev/rough/requests.py).
Using from-import for a module inside the package results in a different ImportError:
from requests.auth import AuthBase

Traceback (most recent call last):
  File "requests.py", line 1, in <module>
    from requests.auth import AuthBase
  File "/Users/me/dev/rough/requests.py", line 1, in <module>
    from requests.auth import AuthBase
ImportError: No module named 'requests.auth'; 'requests' is not a package

Using a star-import and then using the functionality raises a NameError:
from requests import *

res = get('http://www.google.ca')
print(res)

Traceback (most recent call last):
  File "requests.py", line 1, in <module>
    from requests import *
  File "/Users/me/dev/rough/requests.py", line 3, in <module>
    res = get('http://www.google.ca')
NameError: name 'get' is not defined

 For cases where you name your module the same as an existing one on purpose and want to handle that situation, see How can I import from the standard library, when my project has a module with the same name? (How can I control where Python looks for modules?)
Comment: Please note that this is intended as a canonical answer to a common question ... please don't close as duplicate unless you're sure the other question has a better, more complete answer.
Answer: This happens because your local module named requests.py shadows the installed requests module you are trying to use.  The current directory is prepended to sys.path, so the local name takes precedence over the installed name.
An extra debugging tip when this comes up is to look at the Traceback carefully, and realize that the name of your script in question is matching the module you are trying to import:
Notice the name you used in your script:
File "/Users/me/dev/rough/requests.py", line 1, in <module>

The module you are trying to import: requests
Rename your module to something else to avoid the name collision.
Python may generate a requests.pyc file next to your requests.py file (in the __pycache__ directory in Python 3).  Remove that as well after your rename, as the interpreter will still reference that file, re-producing the error. However, the pyc file in __pycache__ should not affect your code if the py file has been removed.
In the example, renaming the file to my_requests.py, removing requests.pyc, and running again successfully prints <Response [200]>.

Note: This doesn't only happen when naming your file as the module you are trying to import. This can also happen if you name your file the same as a module imported by a module you import directly. For example, having a file called copy.py and trying to import pandas from there, will give
ImportError: cannot import name 'copy' from 'copy'

That is because pandas imports copy. There is no magic solution here as you can't know all the modules' names in the world, but a rule of thumb is to try to make names of modules as unique as possible and try to change the name whenever you get such error.
Answer: The error occurs because a user-created script has a name-clash with a library filename. Note, however, that the problem can be caused indirectly. It might take a little detective work to figure out which file is causing the problem.
For example: suppose that you have a script mydecimal.py that includes import decimal, intending to use the standard library decimal library for accurate floating-point calculations with decimal numbers. That doesn't cause a problem, because there is no standard library mydecimal. However, it so happens that decimal imports numbers (another standard library module) for internal use, so a script called numbers.py in your project would cause the problem.
If you still encounter problems like this after tracking own and renaming or removing the appropriate .py files in your project, also check for .pyc files that Python uses to cache bytecode compilation when importing modules. In 3.x, these will be stored in folders with the special name __pycache__; it is safe to delete such folders and files, and possible to suppress them (but you normally won't want to).
Answer: Summary
Problems such as this occur when a Python source file in the project has the same name as some external library module (either in the standard library or an installed third-party package). When attempting to import from the external library (which requires using an absolute import), the project's own module is found instead, causing various errors depending on the exact details.
The easiest way to fix the problem, in ordinary cases, is to rename the affected file. It may also be necessary to locate and delete any corresponding .pyc files. (This is perfectly safe; the files are just a cache of the work that was previously done to translate Python source code into bytecode for the Python virtual machine, analogous to .class files in Java.)
When the project's own module is preferred, this is because of how Python searches for module source code for absolute imports. Depending on exactly how Python is started, the module search path defined in sys.path will usually start with a path that is within the current project. Python will look there first, before looking in any standard library or third-party library folders. This search process does not care about the folder where the importing module is located; any relative paths are relative to the process' current working directory, not the importing module. (However, the standard library paths will normally be absolute paths, and near the end of sys.path, anyway.)
AttributeError
An AttributeError occurs because the project's own module simply doesn't define the function, class etc. that the calling code wants to use from the external library module. As a result, the 'module' object that represents the project's module has no attribute with the specified name, so that's exactly what the error message claims.
In rare, unfortunate cases, the project's own module might happen to define something with the same name such that it does something different. This can cause any kind of exception or other logical error. For example, if the first example from the question is modified:
import requests

def get():
    pass

res = requests.get('http://www.google.ca')
print(res)

now a TypeError will be raised instead, because the code will attempt to call the locally-defined get function with the wrong number of arguments.
ImportError
Using a specific from-import causes the error to be reported differently because the problem is now detected during the importing process itself. In the example in the question, from requests import get means, instead of creating a new global name requests which names the module, there should be a new global name get which names the function from that module (the one which would be referred to as requests.get after a plain import). This requires looking up the get attribute from that module; but since the wrong module was loaded, that attribute lookup fails. More recent versions of Python report this as a probable circular import.
Other import attempts can cause different ImportErrors which complain that the imported module "is not a package". This is self-explanatory: in the example in the question, requests is an ordinary module (because it is defined by a source code file, requests.py), but the desired requests - defined by the third-party library - is a package (defined by several files inside a requests folder elsewhere, including an __init__.py which defines some top-level package contents that are not modules, like the get function).
NameError
Using a star-import, like from requests import *, will not fail directly - it creates global names for all the module contents. However, since the module in the question example doesn't contain anything named get, its attempt to star-import itself will not define that name either. Thus, a NameError occurs - the normal error for trying to use a global name that doesn't exist.
Aggravating factors

Python's default import system is based on names, not file paths, and Python does not distinguish between "(driver) script files" and "library (module) files". Any Python source code can be imported. Although Python caches module imports, the main script will not generally be in this cache, which means it is perfectly capable of attempting to import itself. This is what happens in the example in the question: since requests was not already imported, there is nothing in the cache, so the attempt in the driver script (named requests.py) to import requests will search for something to import, and find the driver script (i.e., its own source file).
This only causes a problem at import time, if the module tries to use that import in its own initialization, e.g. by doing a from-import. Otherwise, the problem will be deferred, resulting in (typically) AttributeError or NameError when trying to use the functionality. See also:

What happens when using mutual or circular (cyclic) imports?
Why do circular imports seemingly work further up in the call stack but then raise an ImportError further down?

Whenever a module is loaded (i.e., imported from its source, rather than using the cache), its own top-level import statements run, causing more imports, recursively. Any of these indirect imports could potentially find the local code. The Python standard library is not a package, and mostly uses absolute import to refer to its other components. For example, as pointed out in Dave Rove's answer, attempting to import the standard library decimal module could fail when tried from a source file named numbers.py, or within a project that has such a source file.
In one especially pernicious case, having a file named token.py in a project (or the current working directory, when starting up Python in interactive mode) causes the interactive help to break:
$ touch token.py
$ python
Python 3.8.10 (default, Nov 14 2022, 12:59:47)
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> help
Type help() for interactive help, or help(object) for help about object.
>>> help()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.8/_sitebuiltins.py", line 102, in __call__
    import pydoc
  File "/usr/lib/python3.8/pydoc.py", line 66, in <module>
    import inspect
  File "/usr/lib/python3.8/inspect.py", line 40, in <module>
    import linecache
  File "/usr/lib/python3.8/linecache.py", line 11, in <module>
    import tokenize
  File "/usr/lib/python3.8/tokenize.py", line 35, in <module>
    from token import EXACT_TOKEN_TYPES
ImportError: cannot import name 'EXACT_TOKEN_TYPES' from 'token' (/current/working directory/token.py)

The traceback tells us all we need to know: calling help triggers a deferred import of the standard library pydoc, which indirectly attempts to import the standard library token, but finds our token.py which doesn't contain the appropriate name. In older versions of Python, it was even worse: tokenize would do a star-import from token, and then its top-level code would try to use a name defined there, resulting in NameError - and a stack trace not mentioning the file name token.py.

Python can import from cached bytecode files (.pyc) even if the corresponding source file is renamed or deleted. This is intended to speed up imports, but it creates an extra step to keep code directories "clean". After renaming any .py file to resolve a problem like this, make sure to check the bytecode cache as well.

Solving the problem
Of course, the standard advice is simple and straightforward: just rename the .py files that were mistakenly imported, and delete any cached bytecode .pyc files for those modules. By default, in Python 3.x, the .pyc files for any .py files within a folder will be put into a subfolder with the special name __pycache__; in 2.x, they simply appeared alongside the corresponding .py files.
However, while this approach quickly solves the immediate problem for most people encountering it, the advice does not scale very well. There are a lot of potentially problematic names; while most projects will not be interested in including a source file named e.g. os.py, some other names might be more desirable, or harder to work around. So, here are some other useful techniques:
Controlling sys.path
Of course, since the problem is caused by sys.path specifying that absolute imports should look in the current project first, it can be avoided by just changing the sys.path.
The problematic path is described in the documentation as a "potentially unsafe path". When using the interactive Python prompt, this will be an empty string (a relative path equivalent to '.') - i.e., the current working directory for the Python process, reflecting any changes made by using e.g. os.chdir. For driver scripts started normally (python driver.py), it will be the directory where the script is located, as an absolute path (not necessarily the current working directory, since a path could be specified on the command line, like python path/to/driver.py). For modules run using the -m command-line flag, it will be the initial current working directory (not necessarily where the module is located, but also an absolute path that will not be affected by os.chdir).
To avoid having this path in sys.path, do one of the following:

In Python 3.11 and up, set the PYTHONSAFEPATH environment variable, or use the -P command-line option to Python.

In Python 3.4 and up, use the -I command-line option to start in isolated mode. This, however, has several other effects: it will ignore environment variables like PYTHONPATH and PYTHONHOME, and it will also skip adding the user-specific site-packages directory to the path (therefore the code will not have access to third-party libraries that were installed using the --user option for Pip).

If all else fails, consider manually manipulating sys.path. This is messy and error-prone, but sys.path is just an ordinary list of strings with file paths, and modifying its contents will affect future imports. (Do not try to replace the list object; this will not work, because Python does not look for it by the name sys.path, but uses a hard-coded internal reference. It is not possible to destroy or replace that object from Python; sys.path is just a name that is initialized to refer to it.)

Keep in mind that removing the "unsafe" path will prevent intentional absolute imports from working within the package. This is inconvenient for some small projects, but also a good reason to learn proper package organization. Speaking of which:
Using relative imports within packages
A well-organized Python project will typically consist of one or more (usually just one) packages, stored in subfolders of the main project folder, plus one or more driver scripts placed outside of the package subfolders. The driver scripts will typically use a single absolute import to access the package functionality, while implementing some simple wrapper logic (e.g. to parse command-line arguments, format and report otherwise-uncaught exceptions, etc.). The package, meanwhile, will use relative imports throughout for its own content, and absolute import only where necessary to access other packages (the standard library and third-party dependencies).
For example, a project might be organized like:
project
├── src
│   └── my_package
│       └── x.py
│       └── y.py
│       └── z.py
└── driver.py

Code in driver.py will use absolute import into the package, like:
from my_package.x import entry_point

if __name__ == '__main__':
    entry_point()

(If logic is needed to parse the command-line arguments, it should normally go in the driver rather than in the package's code.)
Then, code inside the package will use relative imports - so x.py might contain something like:
from .y import first_thing
from .z import second_thing

def entry_point():
    first_thing()
    second_thing()

This gets the best of both worlds: the initial absolute import sets up the top-level package so that relative imports will work, and the relative imports will avoid depending on the sys.path configuration. Even without taking steps to configure sys.path, it will typically include the folder with the driver scripts, but not any package folders; thus, this also automatically avoids import path conflicts. (An absolute import won't find the package contents unless it specifies the corresponding package path; but typically when it does, importing from the current package was intentional.)
This also avoids setting traps for the next project which has this one as a dependency. Say for example that we implement and publish an API package, and someone else writes Client which has API as a dependency. Since API code will use relative import for other API functionality (say, from . import functionality), the Client project's own functionality.py won't cause a problem.
For the initial absolute import to work, of course, the top-level package folder needs to be mentioned in sys.path. However, this is normally accomplished by installing the package, so it does not cause a problem.
Disabling bytecode caching
If a file needs to be renamed, avoiding problems with .pyc files will be easier if they simply don't exist in the first place. They are not necessary, after all; they are, again, simply intended to speed up imports on subsequent runs of the program.
To suppress .pyc file generation, use the -B command-line option or set the PYTHONDONTWRITEBYTECODE environment variable. (There is no built-in solution to delete all existing .pyc files, but this is easy enough to implement by hand using e.g. the shutil standard library module.)
Linting to avoid problematic names
Consider using third-party tools (such as IDE plugins) to warn about filenames used by the standard library or by third-party libraries in the project. In Python 3.10 and up, the full list of standard library module names is also available as sys.stdlib_module_names. This includes names that might not be present in the current Python installation (e.g. OS-specific components or things that are sometimes disabled or omitted, such as Tkinter).
Answer: just put down the import which causing error to the last
ex:
import requests
import flask
import numpy

if import flask is causing error then move that to bottom of the imports
solution:-
import requests
import numpy
import flask


How do I add a mangle rule to my saved iptables firewall rules file?

Question: I've set up OpenVPN on my Debian server and would like to add a rule to iptables. I already have a file that lists default filter rules that iptables reads from (pre-up). I tried adding the rule to the file like so:
*filter
# Default firewall rules are here
COMMIT

*mangle
-A POSTROUTING -s 10.8.0.0/24 -o wlan0 -j SNAT --to-source 192.168.1.230
COMMIT

I then try to apply the rules with:
sudo iptables-apply /etc/iptables.firewall.rules

and it fails.
For reference, I followed this tutorial but don't want to use the shell script because it also failed to apply the mangle rule.
Answer: You have to add the SNAT rule to the nat table and not mangle.
You could also add the rule directly to the active table using:
iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -o wlan0 -j SNAT --to-source 192.168.1.230

And if everything is working save it to a file using:
iptables-save > file

Comment: Thanks, I don't know where the mangle/nat confusion happened. I also didn't know non-filter table rules don't show by default when you list them with `iptables -S`. I didn't see the rules until `iptables -t nat -S`.
Comment: @cpt you're welcome, don't worry, happens to me as well. One more thing I learned while testing new iptables rules with `iptables-restore` is that error messages are not always very helpful. Using `iptables` directly will help you to find the mistake faster. Also try `iptables -vnL`


identificar um clique fora da div com jquery

Question: Bom eu sei como identificar um clique em Cida de um elemento. Eu faço assim:
// Fecha Sidenav
$("#Close_Sidenav").click(function() {
    $("#mySidenav").hide();
});

Porém eu preciso que o $("#mySidenav").hide()  seja executado quando eu clicar no elemento Close_Sidenav e quando eu clicar fora do elemento mySidenav.
Como eu faço isso?
Para mais informações estou tentando fazer esse menu fechar quando clico fora dele.
Menu
Answer: Podes adicionar um auscultador de evento a window ou document e no momento do clique verificar se o event.target está dentro do menu. Para optimizar um pouco podes ter uma flag do menu, para evitar correr código caso o menu esteja fechado...
Poderia ser algo assim:
var menuAberto = false;

// Fecha Sidenav
function fechaSideNav() {
    $("#mySidenav").hide();
    $(".shadow-full").hide();
    menuAberto = false;
}
$("#Close_Sidenav").click(fechaSideNav);

$(document).click(function(e) {
    if (!menuAberto) return;
    var foraMenu = !$(e.target).closest('#mySidenav')[0];
    if (foraMenu) fechaSideNav();
})

// Abre Sidenav
$("#Open_Sidenav").click(function(e) {
    e.stopPropagation();
    $("#mySidenav").toggle(500);
    menuAberto = true;
    $("body").append('

');
});

jsFiddle: https://jsfiddle.net/fdm4j2k2/
Comment: Muito obrigado era isso mesmo que eu queria


Official circuit for paddle?

Question: Is there an official, international circuit of tournaments (like ATP/WTA for tennis) for paddle tennis?
Answer: National and international Tournaments for Ranking only.
See here: http://www.padelfip.com/
jMike

Official circuit for paddle?


Connecting remote database in Xamarin Forms for IOS application

Question: I have a project has two parts.
1- Windows form or WPF application that basically connects to database and write/read/update some basic text data (this part is already done).
2- On the other hand, I am currently developing an IOS app that can connect to remote database and read/write/update data.
What is the best way to connect the same SQLite or SQL database from both Windows forms app and IOS app.
Thanks in advance
Comment: http://github.com/activa/iridium supports all .NET platforms and can connect to SQL Server or a local Sqlite database
Answer: The best way is creating an API/WebService which will be the interface between the database and your clients: WPF, iOS App and any other client you might want to add in the future.
Using a WebService is more secure, I guess you wouldn't want your database username and password being everywhere.
Using a WebService allows you abstract the data layer. Not using an API and using the connection to the database directly from your Apps will tightly couple your apps with the structure of your tables and any single change that happens in the database will force you to do the changes in the apps.
With WebService you decide what information will be available to the ones consuming it.
There are many others Plus on using WebServices but hope this are enough to clear your doubt.
Comment: Are there any introductory tutorials, examples about WebServices? The ones that I found are complicated for beginners. Thanks!


Microsoft.CognitiveServices.Speech.DetailedSpeechRecognitionResultCollection error

Question: We're experimenting with speech-to-text using Microsoft Cognitive Services. One of our requirements is to have word level timestamps. This works fine with short wav files, say, 2-3 minutes of audio, but with larger files we're getting an error:
"There was an error deserializing the object of type Microsoft.CognitiveServices.Speech.DetailedSpeechRecognitionResultCollection. The value '2152200000' cannot be parsed as the type 'Int32'."
Any and all hints as to how I can get around this would be greatly appreciated. Thanks in advance!
Code snippet:
    config.OutputFormat = OutputFormat.Detailed;
    config.RequestWordLevelTimestamps();

    using (var audioInput = AudioConfig.FromWavFileInput(wavfile))
    {
        using var recognizer = new SpeechRecognizer(config, audioInput);

        recognizer.Recognized += (s, e) =>
        {
            if (e.Result.Reason == ResultReason.RecognizedSpeech)
            {
                var framesStart = TimeSpan.FromTicks(e.Result.OffsetInTicks).TotalMilliseconds / 40;
                var te = new TranscriptElement((long)framesStart, e.Result.Text, languageCode);
                // Eventually fails on the following line:
                var words = e.Result.Best().OrderByDescending(x => x.Confidence).First().Words;
                foreach (var w in words.OrderBy(w => w.Offset))
                {
                    var start = TimeSpan.FromTicks(w.Offset).TotalMilliseconds / 40;
                    var duration = TimeSpan.FromTicks(w.Duration).TotalMilliseconds / 40;
                    te.SingleWords.Add(new TranscriptSingleWord((long)start, (long)(start + duration), w.Word));
                }

                transcriptElements.Add(te);
            }
            else if (e.Result.Reason == ResultReason.NoMatch)
            {
                _logger.LogError($"NOMATCH: Speech could not be recognized.");
            }
        };
        await recognizer.StartContinuousRecognitionAsync().ConfigureAwait(false);

        Task.WaitAny(new[] { stopRecognition.Task });

        await recognizer.StopContinuousRecognitionAsync().ConfigureAwait(false);
    }

Answer: It's a bug in the data type the extension is using for the offset. An int can only track ~214s of audio.
You can access the raw JSON that the Best() method is using from the result's property collection through the SpeechServiceResponse_JsonResult property until a fix is available.
Comment: Is there a bug report for this so we can track if it's been fixed?


Estimating conditional variance y|x

Question: I am building a predictor for $y = f(x)$ using training samples ${(x_i, y_i)}$ (assume) drawn i.i.d from some distribution $p(x,y)$, by optimising the empirical L2-loss:
$f(x) = argmin_f \; \sum_i ||f(x_i)-y_i||_2^2$.
(Assume $f$ is suitably parameterised, say linear regression or neural networks, etc.)
It's known that the minimiser $f = E[y|x]$.
Now, I'd like to get a confidence estimate of my prediction $f(x)$, using say the variance of the prediction.  So, I thought of this:

Generate a new dataset ${(x_i,y_i^2)}$.
Find $g(x) = argmin_g \; \sum_i ||g(x_i) - y_i^2||_2^2$.
We know that the minimiser $g = E[y^2|x]$.
Compute the conditional variance estimate as ${\rm var}(y|x) = g(x)-f(x)^2$ and use this as an estimate of the uncertainty in the prediction $f(x)$.

Is the above a theoretically sound way of estimating the confidence in the prediction?
Answer: Yes, estimating $E[y^2|x]$ and $E[y|x]$ separately and subtracting $E[y^2|x] - (E[y|x])^2$ is one way. But it is a biased estimator. One reason is that we did not get an unbiased estimate of $(E[y|x])^2$ but, hopefully, for $E[y|x]$. Also, it can be negative while conditional variance should be non-negative. This is described in Eq. 1.2 in http://stats.lse.ac.uk/q.yao/qyao.links/paper/bka98.pdf. See the discussion in Section 3.1. The paper proposes a kernel regression based estimator.
Answer: why do you square the observations $y_i$ ?
The Laplace approximation gives you an idea of the precision: the inverse curvature (where by 'curvature' I mean the set of eigenvalues of the Hessian) of the paraboloid approximating the log-posterior is an estimate of the uncertainty associated with the posterior.
However this approximation fails for multimodal distributions and other non-Gaussian phenomena (i.e. for which the central limit theorem does not apply).
Comment: I am not directly computing the posterior $p(y|x)$; rather, I am computing the first moment of the posterior (conditional mean), as it's easier to learn.
Comment: I am deriving a new dataset $(x_i, z_i)$, where $z=y_i^2$, to learn $E[z|x]$ (i.e., $E[y^2|x]$).
Comment: The conditional mean is the location parameter vector of the Laplace approximation above (which is just the truncated Taylor series of the log-posterior).
Comment: I mean, at the end of the day you need to perform the marginalization over the parameters somehow: either by approximating with an "easier" parametric distribution (variational approach) or by sampling (slow) or quadrature (specialized)
Comment: and mapping the observations onto a nonlinear manifold introduces another set of considerations (e.g. inner products and therefore distances between $z$'s need to take into account the metric transformation)
Comment: Agree I need to marginalise, but I don't understand your comment about "squaring... needs to take into account the metric transformation" -- why?
Comment: The most related discussion in ML is termed "kernel trick", which is relevant when discrimination in some input space is made simpler by mapping first on a nonlinear manifold, discriminating, and mapping back. The distance between points on a transformed space is the geodesic one, not the Euclidean one : [Riemann manifold](https://en.wikipedia.org/wiki/Riemannian_manifold#Riemannian_manifolds_as_metric_spaces_2)

Estimating conditional variance y|x


Geometric Inequality problem

Question: Within a problem I was solving I came across
Prove $xy+yz+xz \geq 2xyz$ for all non-negative real numbers $x,y,z$.
I have attempted to prove this for some time now, but cannot find a solution that works. The closest I came was trying the AM GM inequality with xy, yz, and xz as my 3 terms, but obviously we need 2 terms.
Comment: Have you considered $x=y=z$ ? you get something slightly dubious. There's probably another condition
Comment: Well, for $x=y=z=2$ we have $4+4+4=12<16=2\cdot2\cdot2\cdot2$.
Comment: $x, y, z$ integers?
Comment: @Soham real numbers
Comment: positive real numbers?
Comment: positive real numbers,
Comment: well these are just the segments formed by the tangents of the inscribed circle in a triangle if that helps
Answer:
Prove \begin{align}xy+yz+xz \ge 2xyz \tag{1}\label{1}\end{align} for all non-negative real numbers $x,y,z$.

A primitive counterexample:
for non-negative real numbers $x=y=z=2$
we have
\begin{align}
4+4+4&=12<16=2\cdot2\cdot2\cdot2
,
\end{align}
so the statement \eqref{1} is obviously false.

Geometric Inequality problem


Select entre 2 models Django

Question: Gostaria de saber como faço uma queryset que retorne todos os "Cartoes"(model2) vinculados ao meu "Colaborador"(model1)?
Models:
<code>class Colaborador(models.Model):
    # dados pessoais do colaborador
    nome = models.CharField(max_length=50)
    sobrenome = models.CharField(max_length=70)
    email = models.EmailField(max_length=50, null=True, blank=True)
    data_nascimento = models.DateField(null=True, blank=True)

class Cartoes(models.Model):
    colaborador = models.ForeignKey(Colaborador, on_delete=models.CASCADE)
    cartao = models.CharField(max_length=20, choices=CARTOES_CHOICES, default='nenhum')
    validade = models.IntegerField(null=True, blank=True)
</code>
Exemplo SQL -> "SELECT * FROM Cartoes WHERE colaborador = ' colaborador do primeiro model ' "
Answer: Consegui o resultado que queria com a seguinte query:
<code> cartoes = Cartoes.objects.filter(colaborador=id)
</code>
Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).

Select entre 2 models Django


Melhor forma de realizar o comando print

Question: Estou estudando sobre Python a pouco tempo e aprendi a exibir um valor em print de três formas:

%
'{}'.format(exemplo)
f' {exemplo} '

Existe uma forma mais pythônica ou cada forma é aplicável em uma situação?
Comment: ok, desculpe. Não tinha encontrado nada parecido.
Answer: O {}.format("variavel") é a melhor forma. E você pode realizar calculo e condições dentro da () parentese e formatar a saída das {} chaves.
Comment: E por quais motivos é melhor?
Comment: Porque permite simplificação no código e melhor manutenção futura, princialmente se você deixar o código para um outro programador realizar manutenção futuramente. O Python aceita outra forma de declarar variavel, mas por convenção ela tende a entrar em desuso e permanecer apenas o formato "format'. Consegui te ajudar Anderson?
Comment: Sim, poderia complementar sua resposta com todas essas informações? Atualmente ela está baseada em achismo sem nenhuma fundamentação. E quanto às *f-strings*, o que diz delas?
Comment: Então, não é achismo não. Na época li um artigo explicando esse conceito não estou encontrando o link agora, posso nao estar sendo exato, você tem razão. Encontrei essa fonte https://docs.python.org/3/library/stdtypes.html?highlight=format#str.format acredito que possa te ajudar mais.
Comment: Sei que não é achismo, mas sua resposta atual é pois você não colocou nenhuma fundamentação nela.  Você só disse "X é melhor", mas não disse o motivo. Também te convido a ler o tópico [O que utilizar para formatar uma string, % ou format?](https://pt.stackoverflow.com/questions/262184/o-que-utilizar-para-formatar-uma-string-ou-format)
Comment: Anderson, obrigado.


PHP: Merge specified sub-arrays into new array?

Question: I'm working in PHP and I need a function that will merge user specified sub-arrays within a 2D array into a new array, e.g.
$arr = [
    "sub_1" => [ "a", "b" ],
    "sub_2" => [ "c", "d" ],
    "sub_3" => [ "e", "f" ],
    "sub_a" => [ 1, 2, 3 ],
    "sub_b" => [ 4, 5, 6 ],
    "sub_c" => [ 7, 8, 9 ]
];

merge_subs( $arr, [ "sub_1", "sub_2", "sub_3" ] );
// should return: [ "a", "b", "c", "d", "e", "f" ]

merge_subs( $arr, [ "sub_a", "sub_b", "sub_c" ] );
// should return: [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

What is the most efficient way to go about this?
EDIT:
This is what I tried but it doesn't work so I am clearly doing something wrong.
function merge_subs( $arr, $subs ){
    $new = [];
    foreach( $subs as $sub ){
        array_push( $new, $arr[$sub] );
    }
    return array_merge( $new );
}

EDIT 2:
I realized I left out the ellipsis and now I have it working. At any rate, I want to know if there is a better way to accomplish this.
Comment: Did you try a simple look through the PHP manual? You may have found [`array_merge()`](https://www.php.net/manual/en/function.array-merge.php) if you had!
Comment: Well you show us the way you did it, then we can see if we can make it more efficient
Comment: I have edited my question to reflect what I have tried.
Comment: If you need to know which array to process and the names of the sub arrays you want to merge. it would be simpler to do `$x = array_merge($arr['sub_1'], $arr['sub_2'], $arr['sub_3']);
print_r($x);`
Answer: Your looking for $new = array_merge($new, $arr[$sub]);
<?php
$arr = [
    "sub_1" => [ "a", "b" ],
    "sub_2" => [ "c", "d" ],
    "sub_3" => [ "e", "f" ],
    "sub_a" => [ 1, 2, 3 ],
    "sub_b" => [ 4, 5, 6 ],
    "sub_c" => [ 7, 8, 9 ]
];

function merge_subs( $arr, $subs ){
    $new = [];
    foreach( $subs as $sub ){
        $new = array_merge($new, $arr[$sub]);
    }
    return $new;
}

print_r(merge_subs( $arr, [ "sub_1", "sub_2", "sub_3" ] ));
// should return: [ "a", "b", "c", "d", "e", "f" ]

print_r(merge_subs( $arr, [ "sub_a", "sub_b", "sub_c" ] ));

Result:
Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => e
    [5] => f
)
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
)

Answer: The accepted answer does what you want by taking an array of keys and looping, but why?  Just specify the the keys you want to merge:
$result = array_merge($arr[ "sub_1"], $arr["sub_2"], $arr["sub_3"]);

More involved than looping, but for fun:
function merge_subs($array, $keys) {
    return array_merge(...array_values(array_intersect_key($array, array_flip($keys))));
}

Get the elements from $arr with the same $keys passed array_intersect_key
Get the values array_values
Merge them as you would in the first example unpacking with ...
Comment: I specified that I needed a function, so that this can be performed as needed with any provided array and specified subarrays. Can you demonstrate a function that will do what I need and does not use looping?
Comment: It's still another working option, always good to have!


Execution time inconsistency in a program with high priority in the scheduler using RT Kernel

Question: Problem

We are trying to implement a program that sends commands to a robot in a given cycle time. Thus this program should be a real-time application. We set up a pc with a preempted RT Linux kernel and are launching our programs with chrt -f 98 or chrt -rr 99 to define the scheduling policy and priority. Loading of the kernel and launching of the program seems to be fine and work (see details below).
Now we were measuring the time (CPU ticks) it takes our program to be computed. We expected this time to be constant with very little variation. What we measured though, were quite significant differences in computation time. Of course, we thought this could be undefined behavior in our rather complex program, so we created a very basic program and measured the time as well. The behavior was similarly bad.
Question

Why are we not measuring a (close to) constant computation time even for our basic program?
How can we solve this problem?

Environment  Description

First of all, we installed an RT Linux Kernel on the PC using this tutorial. The main characteristics of the PC are:

PC Characteristics
Details

CPU
Intel(R) Atom(TM) Processor E3950 @ 1.60GHz with 4 cores

Memory RAM
8 GB

Operating System
Ubunut 20.04.1 LTS

Kernel
Linux 5.9.1-rt20 SMP PREEMPT_RT

Architecture
x86-64

Tests

The first time we detected this problem was when we were measuring the time it takes to execute this "complex" program with a single thread. We did a few tests with this program but also with a simpler one:

The CPU execution times
The wall time (the world real-time)
The difference (Wall time - CPU time) between them and the ratio (CPU time / Wall time).

We also did a latency test on the PC.
Latency Test
For this one, we followed this tutorial, and these are the results:

Latency Test Generic Kernel

Latency Test RT Kernel

The processes are shown in htop with a priority of RT
Test Program - Complex
We called the function multiple times in the program and measured the time each takes. The results of the 2 tests are:

From this we observed that:

The first execution (around 0.28 ms) always takes longer than the second one (around 0.18 ms), but most of the time it is not the longest iteration.
The mode is around 0.17 ms.
For those that take 17 ms the difference is usually 0 and the ratio 1. Although this is not exclusive to this time. For these, it seems like only 1 CPU is being used and it is saturated (there is no waiting time).
When the difference is not 0, it is usually negative. This, from what we have read here and here, is because more than 1 CPU is being used.

Test Program - Simple
We did the same test but this time with a simpler program:
<code>#include <vector>
#include <iostream>
#include <time.h>

int main(int argc, char** argv) {
    int iterations = 5000;
    double a = 5.5;
    double b = 5.5;
    double c = 4.5;
    std::vector<double> wallTime(iterations, 0);
    std::vector<double> cpuTime(iterations, 0);
    struct timespec beginWallTime, endWallTime, beginCPUTime, endCPUTime;

    std::cout << "Iteration | WallTime | cpuTime" << std::endl;

    for (unsigned int i = 0; i < iterations; i++) {
        // Start measuring time
        clock_gettime(CLOCK_REALTIME, &beginWallTime);
        clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &beginCPUTime);

        // Function
        a = b + c + i;

        // Stop measuring time and calculate the elapsed time
        clock_gettime(CLOCK_REALTIME, &endWallTime);
        clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &endCPUTime);

        wallTime[i] = (endWallTime.tv_sec - beginWallTime.tv_sec) + (endWallTime.tv_nsec - beginWallTime.tv_nsec)*1e-9;
        cpuTime[i] = (endCPUTime.tv_sec - beginCPUTime.tv_sec) + (endCPUTime.tv_nsec - beginCPUTime.tv_nsec)*1e-9;

        std::cout << i << " | " << wallTime[i] << " | " << cpuTime[i] << std::endl;
    }
    return 0;
}
</code>

Final Thoughts

We understand that:

If the ratio == number of CPUs used, they are saturated and there is no waiting time.
If the ratio < number of CPUs used, it means that there is some waiting time (theoretically we should only be using 1 CPU, although in practice we use more).

Of course, we can give more details.
Thanks a lot for your help!
Comment: In the simple case as `a` is not used has `a = b + c + i;` been removed by the optimizer ?  Again in the simple case what is latency and jitter of calling `clock_gettime` 4 times ie how is the clock read such that it is not halfway through an update ?
Comment: Even if by some miracle it isn't removed it will take no time in comparison to getting the time.
Comment: @RichardCritten: Linux `clock_gettime` for `CLOCK_REALTIME` should IIRC be fully in user-space (using code + data from VDSO pages the kernel maps into user-space).  It uses `rdtsc` to interpolate a fine-grained offset from the last timer tick.  If it needs a 16-byte atomic read, it probably uses a seqlock, which normally doesn't have to retry but could if a timer interrupt arrives between reads of 64-bit halves.  IDK about `CLOCK_PROCESS_CPUTIME_ID` ; there might be data exported for that, too.
Comment: Related: [Idiomatic way of performance evaluation?](https://stackoverflow.com/q/60291987) re: `a = b+c+i` being way too trivial to be meaningful to benchmark.
Answer: Your function will near certainly be optimized away so you are just measuring how long it takes to read the clocks. And as you can see that doesn't take very long with some exceptions:
The very first time you run the code (unless you just compiled it) the pages need to be loaded from disk. If you are unlucky the code spans pages and you include the loading of the next page in the measured time. Quite unlikely given the code size.
The first loop the code and any data needs to be loaded into cache. So that takes longer to execute. The branch predictor might also need a few loops to predict the loop right so the second, third loop might be slightly longer too.
For everything else I think you can blame scheduling:

an IRQ happens but nothing gets rescheduled
the process gets paused while another process runs
the process gets moved to another CPU thread leaving the caches hot
the process gets moved to another CPU core making L1 cache cold but leaving L2/L3 caches hot (if your L2 is shared)
the process gets moved to a CPU on another socket making L1/L2 caches cold  but L3 cache hot (if L3 is shared)

You can do little about IRQs. Some you can fix to specific cores but others are just essential (like the timer interrupt for the scheduler itself). You kind of just have to live with that.
But you can fix your program to a specific CPU and you can fix everything else to all the other cores. Basically reserving the core for the real-time code. I guess you would have to use cgroups for this, to keep everything else off the chosen core. And you might still get some kernel threads run on the reserved core. Nothing you can do about that. But that should eliminate most of the large execution times.
Comment: There's also lazy dynamic linking on the first call to `clock_gettime`, but that happens *before* the first time measurement.  So does loading glibc pages from disk (or soft page faulting to map them from the pagecache).  But yeah, any slowness from the first exec of the `CLOCK_PROCESS_CPUTIME_ID` code path (probably in the VDSO, a kernel page already mapped) will be part of the wall-clock timed interval, since it happens after the first `CLOCK_REALTIME` measurement.)


Linear regression minimising MAD in sklearn

Question: The standard sklearn linear regression class finds an approximated linear relationship between variate and covariates that minimises the mean squared error (MSE). Specifically, let $N$ be the number of observations and let us ignore the intercept for simplicity. Let $y_j$ be the variate value of the $j$-th observation and $x_{1,j}, \dots, x_{n,j}$ be the values of the $n$ covariates of the $j$-th observation. The linear relationship is of the form
$$ y = \beta_1 x_1 + \dots \beta_n x_n;$$
where the coefficients $\beta_1, \dots, \beta_n$ are given by
$$\beta_1, \dots, \beta_n = \underset{\tilde\beta_1, \dots, \tilde\beta_n}{\mathrm{argmin}} \left( \sum_{j = 1}^N \left( y_j - \tilde\beta_1x_{1, j} - \dots -\tilde\beta_nx_{n, j}\right)^2 \right).$$
I now wish to find the coefficients that minimise the mean absolute deviation (MAD) instead of the mean squared error. Namely, I want the coefficients given by
$$\beta_1, \dots, \beta_n = \underset{\tilde\beta_1, \dots, \tilde\beta_n}{\mathrm{argmin}} \left( \sum_{j = 1}^N \left| y_j - \tilde\beta_1x_{1, j} - \dots -\tilde\beta_nx_{n, j}\right| \right).$$
I understand that, in sharp contrast to the MSE case, the lack of differentiability of the absolute value function at $0$ implies there is no analytic solution for the MAD case. But the latter is still a convex optimisation problem, and, according to this answer, it can be easily solved by means of linear programming.
Is it possible to implement this linear regression in sklearn? What about using other statistics toolkits?
Comment: I just nominated this for reopening. Yes, the question is about how to perform a task in sklearn or Python in general. But *it needs statistical expertise to understand or answer*, which is [explicitly on-topic](https://stats.stackexchange.com/help/on-topic).
Comment: @StephanKolassa I agree with you - the question should be reopened..
Answer: The expected MAD is minimized by the median of the distribution (Hanley, 2001, The American Statistician; see also Why does minimizing the MAE lead to forecasting the median and not the mean?). Therefore, you are looking for a model that will yield the conditional median, instead of the conditional mean.
This is a special case of quantile-regression, specifically for the 50% quantile. Roger Koenker is the main guru for quantile regression; see in particular his book Quantile Regression.
There are ways to do quantile regression in Python. This tutorial may be helpful. If you are open to using R, you can use the quantreg package.
Comment: In python it is available vis statsmodels https://www.statsmodels.org/dev/generated/statsmodels.regression.quantile_regression.QuantReg.html
Comment: For an update, currently sklearn has quantile regression as well http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.QuantileRegressor.html
Comment: Thanks! It is an easy way to look at the problem indeed...


How to store all entered array elements

Question: I'm new at programming. I have to write a code, main requirements - user chooses the sorting method (one is already added, the second one I will add later), enters the amount of elements in the array, enters the elements and then the code sorts them. But it looks like the code only takes the last entered element and tries to sort it. What do I have to do to make it sort all entered elements?
     public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("181RDB094 Līva Gundega Ermansone 1");
        System.out.print("method:");
        int M;
        if (sc.hasNextInt())
            M = sc.nextInt();
        else {
            System.out.println("input-output error");
            sc.close();
            return;
        }
        System.out.print("count:");
        int count = sc.nextInt();
        int[] masīvs = new int[count];
        System.out.println("items:");
        masīvs = new int[count];
        for (int i = 0; i < count; i++) {
            masīvs[i] = sc.nextInt();
        }
        System.out.println("result:");
        if (M == 1) {
            int[] b = new int[count];
            int[] less = new int[count];
            int[] equal = new int[count];
            int k;
            for (int i = 0; i < count; i++)
                for (int j = 0; j < count; j++) {
                    if (masīvs[i] == masīvs[j]) {
                        equal[i] = i++;
                    } else if (masīvs[i] > masīvs[j]) {
                        less[i] = i++;
                    }
                }
            for (int i = 0; i < count; i++) {
                k = less[i];
                for (int j = 0; j < equal[i]; j++) {
                    b[k + j] = masīvs[i];
                }
            }
            for (int i = 0; i < count; i++) {
                masīvs[i] = b[i];
                System.out.print(masīvs[i] + " ");
            }
        } else if (M == 2) {
        } else {
            System.out.println("input-output error");
            return;
        }
    }

Sorry for the ugly code, it's just a draft.
Expected:
181RDB094 Līva Gundega Ermansone 1
method:1
count:4
items:
13
31
55
2

result:
55 31 13 2

Actual results:
181RDB094 Līva Gundega Ermansone 1
method:1
count:4
items:
13
31
55
2
result:
2 2 2 0

Comment: I would recommend using a debugger to understand what is going on.
Answer: You can add a simple for loop after filling your array to check the contents. There, you can see that all entries are written into the array correctly.
This will output:
Array:13
Array:31
Array:55
Array:2
for (int i = 0; i < masīvs.length; i++) {
    System.out.println("Array:" + masīvs[i]);
}

Answer: The sorting method you are following fixes a set of equal elements at their proper position by finding the no of elements less than those elements.
The problem in sorting lies in finding the no of elements less and equal to.
equal[i]++; instead of equal[i]=i++;
Similarly,
less[i]++; instead of less[i]=i++;
Answer: I think that your code organization is very bad. It's easier to give you more correct solution, than count and fix your problem:
public class Foo {

    public static void main(String... args) {
        final BiFunction<int[], Comparator<Integer>, int[]> sort =
                (items, comparator) -> Arrays.stream(items)
                                             .boxed()
                                             .sorted(comparator)
                                             .mapToInt(i -> i)
                                             .toArray();

        try (Scanner scan = new Scanner(System.in)) {
            Comparator<Integer> comparator = getSortingMethod(scan);
            int[] items = getItems(scan);
            int[] sorted = sort.apply(items, comparator);
            System.out.println(Arrays.toString(sorted));
        }
    }

    private static final Comparator<Integer> SORT_ASC = Comparator.naturalOrder();
    private static final Comparator<Integer> SORT_DESC = Comparator.reverseOrder();
    private static final Comparator<Integer> SORT_NULL = (one, two) -> {
        throw new IllegalArgumentException("input-output error");
    };

    private static Comparator<Integer> getSortingMethod(Scanner scan) {
        System.out.println("181RDB094 Līva Gundega Ermansone 1");
        System.out.print("method:");

        try {
            int M = scan.nextInt();

            if (M == 1)
                return SORT_DESC;
            if (M == 2)
                return SORT_ASC;
            return SORT_NULL;
        } catch(RuntimeException e) {
            return SORT_NULL;
        }
    }

    private static int[] getItems(Scanner scan) {
        System.out.print("count:");
        int[] items = new int[scan.nextInt()];

        System.out.println("items:");

        for (int i = 0; i < items.length; i++)
            items[i] = scan.nextInt();

        return items;
    }

}

Answer: If you're using Java 8 or more recent, you may be able to use the ArrayList class (with the Integer class) instead of an 1D array (i.e. int[] var = new int[x]); it would allow you to use its sort(Comparator) method instead.
You would have to create a Comparator instance (lambda function, or anonymous) or an implementing class, unless you want to use the natural ordering of those.
It would give you something around those two lines:
ArrayList<Integer> var = new ArrayList<>();
and var.sort(); (assuming you use the natural ordering)
It might however be harder to manipulate at first, if you're new to the Java Collection Framework, so don't hesitate to ask questions.

P.S.: I might have misunderstood the code, so just tell me so I can fix my answer.
P.S.S.: Somewhat unrelated, and it's probably in your mind (ignore that part then), but I would recommend you to refactor that into much more smaller methods/functions.

How to store all entered array elements


Windows 8.1 Hyper-V network adapter is set to public and won't save as private

Question: I have a collection of Windows 8.1 machines that run Hyper-V for unit testing. We often use PowerShell to script changes to these systems to ease our administration. However, we've been having trouble enabling powershell remoting on these machines.
We run the following command on these machines to attempt powershell remoting enabling

Enable-PSRemoting -force

But we always get the following error:

WinRM firewall exception will not work since one of the network connection types on this machine is set to Public. Change the network connection type to either Domain or Private and try again.

The network adapters Are as follows:
Name             : Network  2
InterfaceAlias   : vEthernet (Broadcom NetXtreme Gigabit Ethernet)
InterfaceIndex   : 13
NetworkCategory  : Private
IPv4Connectivity : Internet
IPv6Connectivity : LocalNetwork

Name             : Unidentified network
InterfaceAlias   : vEthernet (Windows Phone Emulator Internal Switch)
InterfaceIndex   : 10
NetworkCategory  : Public
IPv4Connectivity : NoTraffic
IPv6Connectivity : NoTraffic

I tried running the following scripts to set the unidentified network to be private
Set-NetConnectionProfile -name "Network  2" -NetworkCategory private
Set-NetConnectionProfile -name "Unidentified Network" -NetworkCategory private

However these scripts work for the duration of the machine's uptime, but when the machine reboots, the Unidentified network reverts back to the public.
Why is this resetting, and how can I get the scripted change to persist?
Thanks!
Comment: "**Unidentified** Network" is why.  Windows sees it as a new network each time and doesn't remember that it is the same "Unidentified" one that was there before.  Easiest workaround it just to run a startup script that will rerun these commands.
Comment: If all you really want to do is to enable psremoting you could use add the -Force parameter to the Enable-PSRemoting cmdlet, even though the firewall rule won't open up to traffic with the emulator switch.
Comment: I am using the -Force flag w/ PSRemoting cmdlet, still get the error.
Answer: You can exclude certain nics from NLA (Network Location Awareness). Very common to do this in VMware workstation scenarios since the VMware nics always end up as unidentified/public. Here's how:

Navigate to:HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002BE10318}
You will find enumerated keys like 0000, 0001, 0002 and so on.
Expend them one by one and look for DriverDesc REG_SZ value data.
In the same registry key where you found the name of the nic to exclude (DriverDesc value), create another new DWORD Value, name it *NdisDeviceType (it Case Sensitive!!). Double click on this value and in "Value Data" field put 1 as Decimal data

(snipped from)
http://www.petri.co.il/forums/showthread.php?t=45181
Answer: You can set all unidentified networks as private via Group Policy:
gpedit.msc > Computer Configuration > Windows Settings > Security Settings > Network List Manager Policies > Unidentified Networks > Location type: Private


adding the field tokens while creating the component

Question: I created the component, in body of the message i added the token based on machine name but i am unable to fetch the data of the fields of content i,e when email triggers to user in the body of the email field data is not showing based on the content created, i have followed this method Get the field data in email body. please give suggestion why is this happening?
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](http://chat.stackexchange.com/rooms/29225/discussion-on-question-by-kashish-adding-the-field-tokens-while-creating-the-com).
Answer: In Rules you need to use - not a _
Try
[node:field-working]
[node:field-remoz]

EDIT

Click on replacement patterns, it will show you all the fields that you can use. Look for your field on the list, and then use the code that is given there, and copy and paste it into the message body.


Resources ids.xml gives identical id Android

Question: I am having a weird problem, I set custom view's ids in the res/values/ids.xml file :
<code>    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <item name="observation_photo_view" type="id"/>
        <item name="path_view" type="id"/>
    </resources>
</code>
This should give unique ids to these strings.
Then I set the ids programmatically:
<code>public ObservationPhotoView(Context context){
    super(context);
    this.context = context;
    setId(R.id.observation_photo_view); //setting it here
    setOrientation(VERTICAL);
}
</code>
And the same way for my custom path view.
However, when I try to get my ObverationPhotoView thanks to a
<code>    (ObservationPhotoView) parentView.findViewById(R.id.observation_photo_view);
</code>
I get the error :
<code>    Caused by: java.lang.ClassCastException: CustomPathView cannot be cast to ObservationPhotoView
</code>
And after checking those views ids thanks to the debugger, I can see that they are indeed identical.
comparing the two values via debugger
Is there any explanation to that?
Comment: (ObservationPhotoView) parentView.findViewById(R.id.observation_photo_view); what is parent view. share this code plz
Comment: It is another type of customView which is contained in a viewFlipper
Answer: Well, looks like a rebuild project worked, sorry for bothering.
I hope it'll help in case someone has the same issue.


Slackbot + Heroku: Have to keep logging in

Question: I'm having an issue with my botkit slack bot hosted on Heroku.  The bot itself is just the "starter kit."
https://github.com/howdyai/botkit-starter-slack
After a little while, the bot stops working.  The logs complain of not being able to find the team.  I hit the /login path of my heroku-deployed app and allow it and it works again for a bit.
Is there a heroku configuration that I need to change to keep it from going idle or something?  Or is this an issue with the starter kit?  Could there be something I need to do in the slack configuration?
Comment: Are you connecting to any database with your bot? If so you have to make sure that you don't hit the connection limit.
Answer: I am pretty sure that you run your bot on a hobby dyno. Heroku sends hobby dynos to sleep if they dont receive any requests.
What had happened:

You deployed the bot -> the bot is running and working
Everybody can write with the bot -> so great!
After a few minutes, while the bot is not used, the dyno falls asleep
At this moment the bot is not working
You hit the /login request and yeah -> the dyno starts again and the bot is running and working

Read more about free dynos here: https://devcenter.heroku.com/articles/free-dyno-hours.
Solution: Switch to Standard Dynos


WSUS Upstream server is not showing current downstream server status

Question: I've upstream WSUS server running Windows Server 2008 R2 with WSUS 3.2.7600.262. The majority of downstream servers was running OS and WSUS with same versions. Now I migrated some downstream servers to Windows Server 2012 R2 and its embedded WSUS 6.3.9600.16384. And a few of them are not rolling up update and computer status to upstream server, while update approvals are synchronized and installed to computers.
All computers are reporting to downstream server current status. These computers are missing in All computers view on upstream server. If I look to Downstream servers on upstream server, there is displayed 0% Installed/Not Applicable Percentage at line with the downstream server.
I tried to follow one howto with similar problem (Wsus Downstream servers not shown in upstream) but the problem is different and it doesn't help.
It's strange that one of migrated downstream servers with Windows Server 2012 R2 works, and others doesn't.
Answer: The problem was, that it needed to do postinstall procedure (new in Windows Server 2012).
<code>'C:\Program Files\Update Services\Tools\wsusutil.exe' postinstall
</code>
All steps are at: https://technet.microsoft.com/en-us/library/hh852349.aspx
Then the problem is resolved.


IP compatible with localhost and external

Question: Im working on an online game, but I'm having an annoying issue with me and my friend testing. The thing is, I set the client to connect to my WAN IP so he can connect, but then I cannot connect as it only work with localhost or 127.0.0.1. If I set it to localhost, obviously he cannot connect.
I also tried using a DNS server, which used to work but recently I set it up again and it's not working.
Any ideas on how I can get a single domain or IP that works for a local connection and a WAN connection?
Answer: Add an entry to your hosts file.
In your hosts you can write: 127.0.0.1 thegame
and your friend can write: [your wan ip] thegame
Then you can both connect to thegame.
Comment: Wow thanks, I'm pretty sure this is what I did last time when it was working and forgot to add it after I formatted my PC. Thanks again


Proportions with Time

Question: Sorry about the title, I'm not exactly sure what to call this type of problem.
It takes one man one day to dig a $2\text{ m} \times 2\text{ m} \times 2\text{ m}$ hole. How long does it take $3$ men working at the same rate to dig a $4\text{ m} \times 4\text{ m} \times 4\text{ m}$ hole?
I tried to solve using proportions, but it didn't work out. Can someone guide me in the right direction?
Sorry about the tag as well.
Comment: I notice that you have asked quite a few questions already but have accepted none of the answers to them.  You might want to go back to your older questions and upvote answers that you have found useful, and accept the answer which you think is best for that question.
Answer: Work output is often expressed in terms of man-days (or man-hours).
The assumption here is that the number of man-days is directly proportional to the volume of the dug hole. It is a reasonable assumption.
It takes $1$ man-day to dig $(2)(2)(2)=8m^3$.
So it takes $\frac18$ man-day to dig $1m^3$.
Hence to dig $(4)(4)(4) = 64m^3$ would take $64 \times \frac18 = 8$ man-days.
With $3$ men working, that's $\frac13 \times 8 = \frac 83 \ (=2\frac23)$days.
Answer: First you need to find the rate of $\frac{\text{volume dug}}{\text{day}}$
So, for a man in one day it is $\frac{8}{1}\text{ m}^3$
You need to dig $64 \text{ m}^3$ so, how many days will that take if you know a man can dig $8\text{ m}^3$ a day and thus, 3 men could dig $24\text{ m}^3$ per day?
EDIT: Alternate method.
Look at what each change should do to your original time of 1 day.
Tripled the men working = dividing time by 3.
Doubling length = multiplying time by 2.
Doubling width = multiplying time by 2.
Doubling height = multiplying time by 2.
So your new time is $$1\text{ day}\div3\times2\times2\times2$$

Proportions with Time


How to compare current year with an integer field in Rules?

Question: I would like to compare the current year with an integer field (let's say a "year of subscription" field) using Rules (if the field value is lower than the current year, the user has no access to a specific action on the website).
I have tried many different things, data comparison, text comparison, PHP custom etc. but I did not manage to create this "apparently" simple condition.
I guess I am missing something (a date/time comparison somewhere? the right PHP code to extract the year of the current date? echo date('YY')? strtotime? mktime?).
Could anyone help me?
Thanks in advance.
Answer: Add the rule as follows:

Event
Your event
Conditions:
a. Entity has field
-> Data Selector = node
-> Field Value = your date field (mine is field_bp_year)
b. Execute custom PHP code
-> Value =
return intval([node:field-bp-year]) < intval(date("Y"));
where you add the replacement pattern for your date field (mine was field-bp-year)
Actions:
Your action

NOTE: I treated my year as four digits. If you only want 2 digits then use date("y").
Comment: I always hesitate to use PHP in rules conditions, mostly because I wonder if it has any type of potential securty issues. Any idea about that?
Comment: It works for me, thanks for the quick answer. Last thing : if I need Y-1, what would be the PHP syntax?


How to prove that the tensor product of C*-algebras $A \otimes_{\alpha} B$ is simple iff $\alpha$ is the spatial norm and both $A$ and $B$ are simple?

Question: This is Exercise 3.4.2 with a hint in Brown and Ozawa's book C star-algebras and finite-dimensional approximations.

Exercise 3.4.2. Prove that $A \otimes_\alpha B$ is simple if and only if
$\|\cdot\|_\alpha=\|\cdot\|_{\min }$ and both $A$ and $B$ are simple.
(Hint: For the "if" direction it suffices to show that every irreducible representation of $A \otimes B$ is faithful. But if $\pi: A \otimes B \rightarrow \mathbb{B}(\mathcal{H})$ is irreducible, then both $\pi_A(A)^{\prime \prime}$ and $\pi_B(B)^{\prime \prime}$ must be factors. One then uses the previous exercise and a theorem of Murray and von Neumann which asserts that if $M \subset \mathbb{B}(\mathcal{H})$ is a factor, then the product $\operatorname{map}$ $$ M \odot M^{\prime} \rightarrow \mathbb{B}(\mathcal{H}) $$ is injective.)

The previous exercise is quoted as follows:

Exercise 3.4.1. Let $\pi: A \otimes B \rightarrow C$ be a $*$-homomorphism which is injective when restricted to $A \odot B$.
Show that $\pi$ must be injective on all of $A \otimes B$. Is this
still true if one replaces $\|\cdot\|_{\min }$ by $\|\cdot\|_{\max }$?

I have worked out the Exercise 3.4.1 and the "only if" part of Exercise 3.4.2, but I cannot get the idea of the hint to do the "if" part. I wonder if someone could give some more clues or elaborate on how we can get the answer from the hint?
Any help is appreciated.
Answer: If $J\subset A\otimes B$ is a proper ideal, then $(A\otimes B)/J$ is  a non-zero C$^*$-algebra. Doing GNS for a pure state gives us an irreducible representation $\rho:(A\otimes B)/J\to B(K)$. If we define $\tilde\rho:A\otimes B\to B(K)$ by $\tilde\rho=\rho\circ q$ (where $q$ is the quotient map) we get an irreducible representation of $A\otimes B$ with $J\subset\ker\tilde\rho$. So if we show that any irreducible representation of $A\otimes B$ is faithful, then $A\otimes B$ is simple.
So we assume $\pi:A\otimes B\to B(H)$, irreducible. We have
$$
B(H)=\pi(A\otimes B)''=(\pi_A(A)\cup\pi_B(B))''=(\pi_A(A)'\cap\pi_B(B)')'.
$$
Taking commutant we get that
$$
\pi_A(A)'\cap\pi_B(B)'=\mathbb C.
$$
We also know that $\pi_A(A)$ and $\pi_B(B)$ commute, so
$$
\pi_A(A)''\subset \pi_B(B)'.
$$
It follows that
$$
\pi_A(A)'\cap \pi_A(A)''\subset \pi_A(A)'\cap\pi_B(B)'=\mathbb C.
$$
This shows that $\pi_A(A)''$ is a factor, and similarly for $\pi_B(B)''$.
Now, using the Murray-von Neumann result, we factor $\pi$ via the  injective maps
$$
A\odot B\xrightarrow{} \pi_A(A)''\odot \pi_A(A)'\xrightarrow{} B(H).
$$
And then Exercise 3.4.1 finishes the proof.
Comment: It's indeed fun. I used this book as the textbook for a course and struggled with the contents and exercises the first time but as the time went I felt better. Now the course has ended. I learned a lot.
Comment: Thank you so much!
Comment: Glad I could help. It's always fun to do exercises from Nate and Taka's book.


Given the fundamental theorem of calculus part 1, prove the part 2

Question: Given:
$f$ is continuous on $[a,b]$, then $g$ defined by:
$g(x) = \int _a^xf\left(t\right)dt
$
is continuous on $[a,b]$ and differentiable on $(a,b)$ and $g'(x) = f(x)$
Prove that:
$\int _a^bf\left(x\right)dx = F(b)-F(a)
$
Comment: Do you mean g (b)-g (a) instead of F (b)-F (a)?
Comment: Also, what is the function $F(x)$? Is that an antiderivative of $f $?
Comment: Um, what is F?  By definition int from a to b is g (b).  And it's easy to to see g (a) = 0.  So I assume there is more to the question then proving int is g (b)-g (a).
Answer: See that we have, given $f(x)$ is continuous and that for some unknown continuous function $F(x)$,
$$\frac d{dx}\left(\int_a^xf(t)dt-[F(x)-F(a)]\right)=f(x)-F'(x)=0$$
Since the derivative of the integral is taken care of by the FTOC Part I, and we are trying to find the function $F(x)$ that satisfies this.  It is then trivial to see that if we must have $F'(x)=f(x)$, then $F(x)$ is, by definition, the antiderivative of $f(x)$.
Thus,
$$\int_a^xf(t)dt-[F(x)-F(a)]=c\ \forall\ (x,a)\in\mathbb R$$
for an unknown constant $c$, since the only function with $0$ as it's derivative for all $x$ is a constant function.  By having $x=a$, you can see that $c=0$, thus, we have
$$\int_a^xf(t)dt-[F(x)-F(a)]=0$$

$$\int_a^xf(t)dt=F(x)-F(a)$$


Console Program results to text file

Question: I have written a console program that uses TCP IP and I am now debugging in a 64 bit machine.
The program connects ok to the server and output things in the screen (until the error I am debugging happens)
I want to record these screen outputs so I did
>theProgram.exe > screenrecord.txt
as a pipe. This used to work well before but for some reason now, the program when run this way although connecting to the network is now receiving just 0 bytes (by the way I could never understand what this "0 bytes" mean, I pointed out the documentation is vague at best on this)
Why this piping can be affecting the behavior of the TCP IP?
and what are methods to derive the output to a text file?
Is there a way to put these output to a text file and seeing them on the screen at the same time??
Comment: Can you give some more information e.g. the exception
Comment: This program is tagged as a C#,  I assume that You have created the program. Why don't You just add module for debugging into file? You can write it Yourself or use some existing (e.g.: [Log4NET](https://csharp.today/log4net-tutorial-great-library-for-logging/) ).
Comment: @Tatranskymedved thanks, could you please elaborate a little more on adding modules?
Comment: Also, could You please share information about code? Have You used any network communication library or using standard .NET? Can You show us some code? Have You done some research about this ?
Comment: @Tatranskymedved I am using standard .NET. I will post some code, but in the meantime, is there any other way to output my screen to a file? (and if possible to both file and console?)
Comment: @KansaiRobot , Check the link in the comment. After that, when You run the program, You can add parameters where the path for debug can be included, or the information if You want to debug it (string[] Args must be handled)
Comment: @KansaiRobot Try googling for a moment about I/O into files - C#. [link](https://www.tutorialspoint.com/csharp/csharp_file_io.htm) [link2](https://msdn.microsoft.com/en-us/library/8bh11f1k.aspx?f=255&MSPPError=-2147217396) [link3](https://www.google.cz/search?q=C%23%20IO%20files)
Comment: @Tatranskymedved Thank you. And sorry, I think I have not made myself understood (my bad!) . I don't want to modify my code and write to a file (although if there is no other way maybe I will do) In fact, my code is already writing to a file. What I am asking is to >temporarily< shift the screen output to a text . I could do this with ">" but wonder if there is other way
Answer: The Console can only output to 1 device at a time. The Console.SetOut method directs the output to another device such as your screenrecord.txt. As you show >theProgram.exe > screenrecord.txt when executed will not show any output to the screen. The same is with Console.SetOut, since it is redirected to a file, it won't show up in the console. The code below was taken from MS Console.SetOut Method (TextWriter)
Below shows one way you could redirect the console output to a file. In this code... ScreenRecord.txt will be saved in the debug folder of the project, or you can set a path also.
Hope this helps.
static void Main(string[] args)
{
  Console.WriteLine("Start Of Main - output not redirected yet!");
  FileStream fs = new FileStream("ScreenRecord.txt", FileMode.Create);
  // First, save the standard output.
  TextWriter tmp = Console.Out;
  StreamWriter sw = new StreamWriter(fs);
  Console.SetOut(sw);
  Console.WriteLine("this writes to file 1");
  printStuff();
  Console.SetOut(tmp);
  Console.WriteLine("this line not in file");
  Console.ReadKey();
  sw.Close();
}

private static void printStuff()
{
  for (int i = 1; i < 7; i++)
    Console.WriteLine("printStuff " + i);
}

Console Program results to text file


How to pass variable to href in javascript?

Question: How to pass this variable value here? Below code is not working. And all other discussions on Stackoverflow are unclear.

And my HTML code is:
<select id="value" name="dist" onchange="return check()">

Comment: You may want to encode it as well.
Answer: You have to fetch field value using .value as you are passing whole object to the URL as document.getElementbyId('value') returns whole field object.
var dist = document.getElementById('value').value;

So your function should be like this
function check() {
    var dist = document.getElementById('value').value; // change here
    if (dist != "") {
        window.location.href = "district.php?dist=" + dist;
    } else
        alert('Oops.!!');
}

Answer: You have fetch value of the field, Currently you are using DOM object
Use
 var dist = document.getElementById('value').value;

OR
Use
 if (dist.value!=""){
     window.location.href="district.php?dist="+dist.value;

instead of
if (dist!=""){
     window.location.href="district.php?dist="+dist;

Comment: @Joel, upvoted your question soon you will enough reputation to upvote. As far I am concerned Its more important to help a fellow community member than reputation point. Mary x-mas
Comment: Merry x'mas dude :) Thanks
Answer: Try this:
function check() {
    var dist = document.getElementById('value').value;

    if (dist) {
        window.location.href = "district.php?dist=" + dist;
    } else {
        alert('Oops.!!');
    }
}

Answer: Try this:
var dist = document.getElementById('value').value;
if (dist != "") {
 window.location.href="district.php?dist="+dist;
}

Answer: You have to make some correction in your function..
function check()
    {
        var dist = document.getElementById('value').value;  //for input text value
       if (dist!==""){  //  for comparision
           window.location.href="district.php?dist="+dist;
       }
       else
           alert('Oops.!!');
    }

Answer: I use a very different approach to this.  I set browser cookies in the client that expire a second after I set window.location.href.
This is way more secure than embedding your parameters in the URL.
The server receives the parameters as cookies, and the browser deletes the cookies right after they are sent.
const expires = new Date(Date.now() + 1000).toUTCString()
document.cookie = `oauth-username=user123; expires=${expires}`
window.location.href = `https:foo.com/oauth/google/link`


React Native:  won't render if placed inside

Question: In the following code:
'use strict';

var React = require('react-native'),

{
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Component,
  NavigatorIOS
} = React,

styles = StyleSheet.create({
  container: {
    padding: 30,
    marginTop: 65,
    alignItems: 'center'
  },
  button: {
    height: 36,
    flex: 1,
    flexDirection: 'row',
    backgroundColor: '#48BBEC',
    borderColor: '#48BBEC',
    borderWidth: 1,
    borderRadius: 8,
    marginBottom: 10,
    alignSelf: 'stretch',
    justifyContent: 'center'
  },
  buttonText: {
    fontSize: 18,
    color: 'white',
    alignSelf: 'center'
  },
  text: {
    color: 'black',
    backgroundColor: 'white',
    fontSize: 30,
    margin: 80
  }
})

class Login extends Component {
  render() {
    return (
    /*<TouchableHighlight
      style={styles.button}
      underlayColor='#99d9f4'>*/
      <Text style={styles.text}>Login with Google</Text>
    /*</TouchableHighlight>*/
    )
  }
}

module.exports = Login

The <Text> Login gets rendered only when the surrounding <TouchableHighlight> is commented out. What am I doing wrong?
Comment: This is weird. It works for me, but only if I add TouchableHighlight to the things I'm importing from React. But if that's not there then I get the red screen of death...
Comment: hmm, other than the components (jsx tags), feels just like react to me. Anything in particular you find different from react?
Comment: Wow - I forgot to import TouchableHighlight, but React didn't show me the red screen so I never even bothered to check if I'd imported it. If you add this as an answer, I'll accept it.
Answer: You need to import 'TouchableHighlight'.
Add TouchableHighlight to your list of requires.
var React = require('react-native'),

{
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Component,
  NavigatorIOS,
  TouchableHighlight
} = React,

Answer: In order to use the  tag, you have to import it in the destructuring assignment block just like Text and View.


Block Permission for user

Question: I have faced a new problem, here I have poll block which is already displayed for administrator or user who has the permission of "view published content". When I made another user and give the complete permission for the poll but does not giver the permission of "view published content", it is not displayed for the user. Can any one help me to show that in the block for user except administer or user who has the permission of "view published content".
cheers
Answer: You want to be looking at the permission "vote on polls" that is the one you want to enable for that user.
Comment: yes, I want to enable the poll block for another users without having the permission of "view published content". Could you help me
Comment: Did you read my answer?
Comment: yes, I rad your answer but it did not make any sense for me. My question is this that I want to display the block for some users and there is no difference weather it is poll block or any other block

Block Permission for user


Problems in Kentico, doesnt find CMSItem reference

Question: we had some movements of some webservices yesterday in our project. We had the web services in trunk of SVN, we created a branch for them because we want to use the webservices in our website in the branch too.
Ok, after to do it I am getting the next error: looks like doesnt find CMSItem just when I run the webseite.
We have a Kentico version 7

Why it is happening? where can I find the reference? Is possible our kentico liscence is for only one directory?
Answer: In Kentico 8, CMSItem lives in the CMS.Helpers namespace.
You're using v7, where it lives under CMS.GlobalHelper.
E.g.
CMS.GlobalHelper.CMSItem

Make sure you've referenced the CMS.GlobalHelper.dll in your project.
See API docs
Kentico 7 > Reference Guides > Kentico CMS API reference > CHM file

Comment: I have this using: `using CMS.CMSHelper;` it fails in GetResource.ash.cs
Comment: and in bin I have as reference `CMS.CMSHelpers.dll`