Polynomials with $f(\sin x) = f(\cos x)$

Question: Find all polynomials in $f \in \mathbb{R}[x]$ such that $f(\sin x) = f(\cos x)$ for all $x\in \mathbb{R}$.
The best idea I tried was comparing coefficients of $f(t)$ and $f(\sqrt{1-t^2})$ but it's still quite messy.
Update: Finding all $f$ with $f(t^2) = f(1-t^2)$ would be enough, by Sufficient and essential condition for polynomials $P$ and $Q$ to satisfy $P(\sin x)= Q(\cos x)$
Answer: Yup, I just arrived at that.
Make a substitution $t^2=u$, then we have $f(u)$ can be any polynomial that is symmetric around $u=\frac{1}{2}$.
One example could be $a(u)=(u-\frac{1}{2})^2$ which corresponds to $f(t)=(t^2-\frac{1}{2})^2$.
Another example of a non-polynomial function would be $f(t)=|t^2-\frac{1}{2}|$.
Any polynomial that is a linear combination of even powers of $(t^2-\frac{1}{2})$ will work.
Comment: Ah, my bad. @DanielSchepler I think I'll keep it and mention it's not a polynomial
Comment: $f(t) = |t^2 - \frac{1}{2}|$ wouldn't be a polynomial, though.


Bayes theorem: a function of D, or theta, or both?

Question: In the Bayes formula as written for machine learning applications,
$$
   p(\theta|D) = \frac{ p(D|\theta) p(\theta) }{ p(D) }
$$
where $D$ is the data, $\theta$ are the model parameters.
Commonly $p(\theta)$ is labeled the prior, $p(D|\theta)$ is called the likelihood,
and $p(D)$ is called the evidence (or marginal likelihood I think).
The question: I am bothered by calling $p(D|\theta)$ as a likelihood.
I believe a likelihood is not a probability density, meaning that $\int p(D|\theta) d\theta$ does not integrate to one.
Wheras I think $\int p(D|\theta) d\,D$ does integrate to one.
So it seems strange to include something that is not a probability in the formula.  I think maybe my confusion is about whether the overall Bayes formula should be considered as "a function of" $D$, or $\theta$, or either or both?
Answer: In probability theory (as this has nothing specific to machine learning or statistics) Bayes' formula is based on the joint distribution of the pair of random variables $(D,\theta)$, $p(D,\theta)$, which can be expressed either as
$$p(D,\theta)=p(D)\times p(\theta|D)$$
or as
$$p(D,\theta)=p(\theta)\times p(D|\theta)$$
[with the confusion notation of using the same $p(\cdot)$ everywhere!] where

$p(D)$ denotes the marginal density of $D$ [integrates to one in
$D$] also called marginal likelihood or evidence
$p(\theta)$ denotes the marginal density of $\theta$ [integrates to one in $\theta$] also called prior
$p(D|\theta)$ denotes the conditional density of $D$ given $\theta$ [integrates to one in $D$] also called likelihood and often denoted $\ell(\theta)$
$p(\theta|D)$ denotes the conditional density of $\theta$ given $D$ [integrates to one in $\theta$] also called posterior
Comment: This seems intuitive. (Typo in #4, "DS").   However I am bothered by calling $p(D|\theta)$ a _likelihood_ if it is viewed as an object where we integrate D, and so it seems to be a function of D rather than of $\theta$.  I am sure this comment is stupid, but that is my feeling.


How to perform arithmetic operations separately for each group and average the results in R

Question: Here example of mydata
mydat=structure(list(MDM_Key = c(26L, 26L, 26L, 26L, 26L, 26L, 55L,
55L, 55L, 55L, 55L), SalePrice = c(91.51, 91.51, 0, 91.51, 91.51,
0, 3344.44, 0, 2721.35, 3200, 0), ActionDuration = c(20L, 40L,
500L, 37L, 30L, 400L, 155L, 1074L, 5L, 61L, 350L), Articul = c("LLE-A60-11-230-40-E27",
"LLE-A60-11-230-40-E27", "BC1-C5E04-111", "LLE-A60-11-230-40-E27",
"LLE-A60-11-230-40-E27", "BC1-C5E04-111", "LPDO401-100-K03",
"LPDO401-100-K03", "LPDO401-100-K03", "LPDO401-100-K03", "LPDO401-100-K03"
), maxPrice = c(101.68, 101.68, 5351.15, 101.68, 101.68, 5351.15,
4838.66, 3650, 3650, 5037.73, 5037.73), minPrice = c(101.68,
101.68, 5351.15, 101.68, 101.68, 5351.15, 2993.49, 2993.49, 3650,
5037.73, 3400), avgPrice = c(101.68, 101.68, 5351.15, 101.68,
101.68, 5351.15, 4628.3121, 3608.1565, 3650, 5037.73, 4238.4785
), QtySale = c(3456L, 54634L, 63855L, 181089L, 216786L, 100L,
3582L, 67263L, 582L, 601L, 3007L), QtySale6mAfterAction = c(0L,
0L, 2000L, 0L, 0L, 1000L, 0L, 9966L, 0L, 0L, 1457L)), class = "data.frame", row.names = c(NA,
-11L))

I need to perform a series of arithmetic operations for each MDM_Key.

divide QtySale/ActionDuration before the row where salesPrice=0.
Let's consider MDM_Key=26
for example the first row
3456/20=172.8

second row
54634/40=1365.85

Next comes the row where SalesPrice=0, there is no need to divide anything.
after this row with zero there is data again
they also need to be divided
181089/37=4894.29
216786/30=7226.2

after that, the obtained values must be averaged
per_day_before_zero=(172.8+1365.85+4894.29+7226.2)/4=3414.785

Now for this MDM Key we can go back to the rows where salesprice=0 , there are 2 of them in this example for MDM_Key=26.
However, we always divide their values by 180 and work with the QtySale6mAfterAction column,
in other words, for such rows QtySale6mAfterAction/180.
that is,
2000/180=11.11
1000/400=2.5

and also averaging per_day_in_zero=(11.11+2.5)/2=6.8
After this, a similar procedure is necessary for the next MDM_Key
Thus the desired output
MDM_key per_day_before_zero per_day_in_zero
26        3414.785                 6.8
55        49.78 3                  1.73

How can i do it?
Thank you for your help
Answer: I would suggest to take a look into e.g. R for Data Science. After reading the first few chapters your problem should be easy to solve. However, here's a possible way:
library(tidyverse)

df1 <- mydat %>%
  filter(SalePrice != 0) %>%
  mutate(div_val = QtySale/ActionDuration) %>%
  group_by(MDM_Key) %>%
  summarize(per_day_before_zero = mean(div_val))

df2 <- mydat %>%
  filter(SalePrice == 0) %>%
  mutate(div_val = QtySale6mAfterAction/180) %>%
  group_by(MDM_Key) %>%
  summarize(per_day_in_zero = mean(div_val))

df1 %>% left_join(df2, join_by(MDM_Key))

Answer: A {dplyr} solution wrapped in one piped statement:
library(dplyr)
mydat |>
  mutate(newvar = ifelse(SalePrice != 0, QtySale / ActionDuration, NA),
         per_day_before_zero = mean(newvar, na.rm = TRUE),
         newvar2 = ifelse(SalePrice == 0, QtySale6mAfterAction / 180L, NA),
         per_day_in_zero = mean(newvar2, na.rm = TRUE),
         .by = MDM_Key) |>
  filter(SalePrice == 0) |>
  select(MDM_Key, per_day_before_zero, per_day_in_zero) |>
  unique()

gives
>  MDM_Key per_day_before_zero per_day_in_zero
> 1      26          3414.78682        8.333333
> 3      55            49.78738       31.730556

Note, I assume you want to divide by the constant 180L.
Answer: Here is another option with data.table:
dt <- as.data.table(mydat)

x <-
  dt[, c("per_day_before_zero", "per_day_in_zero") := list(mean(ifelse(SalePrice !=
                                                                         0, QtySale / ActionDuration, NA), na.rm = T),
                                                           mean(ifelse(
                                                             SalePrice == 0, QtySale6mAfterAction / 180, NA
                                                           ), na.rm = T)), by = MDM_Key ]
res <-
  unique(x[, c("MDM_Key", "per_day_before_zero", "per_day_in_zero")])


cancelling a thread inside a signal handler

Question: I have started a timer and set the interval as 5 secs and registered a signal handler for it.
When SIGALRM is encountered  iam trying to terminate the thread inside the signal handler, bt not able to do that. Thread is not getting terminated , instead of this whole process is killed.
The following is the code:
 void signalHandler()
{
        printf("Caught signal ...\n");
        printf("Now going to terminate thread..\n");
        pthread_kill(tid, SIGKILL);
}

void * thread_function()
{
        int oldstate;
        char result[256] = {0};
        time_t startTime = time(NULL);
        time_t timerDuration = 5;
        time_t endTime = startTime + timerDuration;

        while(1) {
                printf("Timer is runnuing as dameon..\n");
                if(!strcmp(result, "CONNECTED")) {
                        resp = 1;
                        pthread_exit(&resp);
                }
        }
}

int main()
{
        int *ptr[2];

        signal(SIGALRM, signalHandler);

        timer.it_interval.tv_usec = 0;
        timer.it_interval. tv_usec = 0;

        timer.it_value.tv_sec = INTERVAL;
        timer.it_value.tv_usec = 0;

        setitimer(ITIMER_REAL, &timer, 0);
            pthread_create(&tid, NULL, thread_function, NULL);
        pthread_join(tid, (void**)&(ptr[0]));
        printf("test %d\n\n",*ptr[0]);

        while(1)
                printf("1");
}

Platform : Linux , gcc compiler
Answer: As far as I'm aware you pretty much can't call anything inside a signal handler as you don't know what state your code is in.
Your best option is to set up a thread to handle your signals. All your other threads should call pthread_setsigmask and to block all signals, and then you create another thread, which calls calls pthread_setsigmask to catch SIGALARM, and then calls sigwait, at which point it can cancel the other thread.
Answer: The way of handling signals is much different in a multi-threaded environment as compared to a single threaded environment. In a multi-threaded code, you should block out all the signals for all the threads that have your business logic and then create a seperate thread for handling the signals. This is because, in multi-threaded environment, you cannot be sure to which thread the signal will be delivered.
Please refer to this link for more details:
http://devcry.heiho.net/2009/05/pthreads-and-unix-signals.html
Apart from this, to kill a thread use pthread_cancel which should work fine for you.
Answer: You can try using a flag:
int go_on[number_of_threads] = { 1 };

void signalHandler()
{
        printf("Caught signal ...\n");
        printf("Now going to terminate thread..\n");
        go_on[tid] = 0;
}

void * thread_function()
{  /* */
   while(go_on[this_thread_id]) {
                printf("Timer is runnuing as dameon..\n");
                if(!strcmp(result, "CONNECTED")) {
                        resp = 1;
                        pthread_exit(&resp);
                }
   }
}


Makefile How to wrap lines in log files

Question: Currently using Ubuntu 20.04 LTS, VS Code, with SHELL=/bin/zsh.
I have my makefile setup to log error outputs to a err.log file using the command ./myprogram 2> err.log whenever I run the command make test. However, I want to wrap the lines such that every time a line exceeds a specified character limit per line (e.g. 80 characters), it wraps and continues on the next line (to improve readability).
How can I achieve this?
Additionally, VS Code supplies color coding for log files which helps in reading. However, when I tried to wrap the lines myself, the color disappears.
Answer: If you wanted to wrap the lines of the standard output, you could use fold:
./myprogram | fold -w 80

or
./myprogram | fold

(The default line length is 80.)
But a pipeline like this operates only on standard output, and leaves standard error unchanged. We could redirect standard error to standard output:
./myprogram 2>&1 | fold > err.log

but this would combine the standard output and standard error. To keep them separate, pipe the error through fold, send the wrapped error to the file and send the output to the screen, we must use a sequence of redirections using a third file descriptor (e.g. 3):
{ ./myprogram 2>&1 1>&3 | fold -w 80 1>err.log; } 3>&1

Makefile How to wrap lines in log files


Como fazer uma classe para manipular Graphics2D no paint?

Question: No código a seguir eu tentei criar uma classe Sprite para manipular os desenhos, a função dele seria transformar as sprites em Graphics2D e usa-lo no paint. Mas a unica forma que encontrei para liga-los foi fazendo esse:
public Sprite(Graphics g) {
    g2d = (Graphics2D) g;
}

O problema é que no código do Title, quando o load = true ocorre, ele não passa pela inicialização do objeto Sprite, o drawImage não funciona, então no primeiro paint ele faz tudo certinho, no segundo paint com o load = true, tudo some e o draw não funciona. Alguma idéia de como corrigir isso?

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JPanel;
import javax.swing.Timer;

import engine.Display;
import engine.Sprite;

public class Title extends JPanel implements ActionListener, KeyListener{

    // IMAGENS

    Sprite city1;
    Sprite city2;
    Sprite tipo;

    private int phase = 1;
    private boolean load = false;

    public Title(Display window){

        setSize( 800, 600 );
        setBackground(Color.WHITE);
        Timer t = new Timer(20, this);
        t.start();
        window.addKeyListener(this);
    }

    @Override
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        if (load == false) {

            city1 = new Sprite(g);
            city2 = new Sprite(g);
            tipo = new Sprite(g);

            city1.setImage("images/scene/logo2.png");
            city2.setImage("images/scene/logo2.png");
            tipo.setImage("images/scene/tipo.png");

            city1.setLocation((800/2) - (city1.getWidth()/2), 150 + (tipo.getHeight()/2));
            city2.setLocation((800/2) - (city2.getWidth()/2), 150 + (tipo.getHeight()/2));
            tipo.setLocation ((800/2) - (city2.getWidth()/2), 150);

            city1.setHeight(0);
            city2.setHeight(0);

            city1.setAnimation(true);
            city2.setAnimation(true);

            city1.setMotionAnimation(0, 0, 0, -1, 0);
            city2.setMotionAnimation(0, 0, 0, +1, 0);

            city1.draw();
            city2.draw();
            tipo.draw();

            load = true;

        }

        city1.draw();
        city2.draw();
        tipo.draw();

    }

    public void actionPerformed(ActionEvent e) {
        if (phase == 1){
            repaint();
        }
    }

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class Sprite {

    private BufferedImage image;
    private int width;
    private int height;
    private int x = 0;
    private int y = 0;
    private String string;
    private boolean visibility;
    private float alpha = 1f;
    private Font font;
    private Graphics2D g2d;

    private boolean animation = false;
    private int spd_x = 0;
    private int spd_y = 0;
    private int spd_width = 0;
    private int spd_height = 0;
    private float spd_alpha = 0;

    public Sprite(Graphics g) {
        g2d = (Graphics2D) g;
    }

    public void setImage(String path){
        try {
            image = ImageIO.read(new File(path));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("Arquivo (" + path + ") não encontrado!");
        }

        this.setHeight(image.getHeight());
        this.setWidth(image.getWidth());
    }

    public void setString(String string, Font font, float alpha){
        this.font = font;
        this.alpha = alpha;
        this.string = string;
        g2d.setRenderingHint( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        g2d.setFont(font);
    }

    public void setLocation(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public void setDimension(int width, int height){
        this.width = width;
        this.height = height;
    }

    public void setMotionAnimation(int spd_x, int spd_y, int spd_width, int spd_height, float spd_alpha){
        this.spd_x = spd_x;
        this.spd_y = spd_y;
        this.spd_width = spd_width;
        this.spd_height = spd_height;
        this.spd_alpha = spd_alpha;
    }

    public void setAnimation (boolean animation){
        this.animation = animation;
    }

    public void draw() {
        if (image != null){
            if (animation == true) {
                this.x += this.spd_x;
                this.y += this.spd_y;
                this.width += this.spd_width;
                this.height += this.spd_height;
                this.alpha += this.spd_alpha;
            }
            g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
            g2d.drawImage(image, x, y, width, height, null);
        } else if (string != null){
            g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
            g2d.drawString(string, x, y);
        }
    }

Answer: Resolvi o problema fazendo com que o comando draw() receba o graphics g e após isso fiz novamente a variavel g2d, igual fiz na iniciação do Sprite.
public void draw(Graphics g)
g2d = (Graphics2D) g

Mas se houver alguma dica para fazer essa classe corretamente, aceito.
Comment: Não faz sentido algum passar graphics no construtor, sendo que você só precisa dele para desenhar no método draw. Essa é a forma correta, remova ele do construtor e deixe o construtor apenas para definir propriedades do objeto e deixe apenas neste método draw.


Risks of enabling nginx upstream keepalive

Question: Using nginx as HTTP reverse proxy for Apache with PHP backend (I need .htaccess flexibility for webmasters).
Seeing http/1.0 used in Apache logs made me look up on how to enable keep-alive connection.
Upon my search I found this blog post from Nginx https://www.nginx.com/blog/avoiding-top-10-nginx-configuration-mistakes/#no-keepalives

By default, NGINX opens a new connection to an upstream (backend) server for every new incoming request. This is safe but inefficient,[...]

If default behavior is safe, what are the risks of enabling upstream keepalive ?
Answer: Proxying a connection with keepalive is considered a risk because of HTTP desynchronization attacks / request smuggling. This occurs when the backend doesn't split different client requests in the exact same way as the frontend. Closing the connection after each request is the "safe" option, since this clearly delineates when the current request has ended.
See https://book.hacktricks.xyz/pentesting-web/http-request-smuggling for more information.
Answer: As I already stated, KeepAlive is an optimization to cache the connection. It is to support high throughput traffic. I do not see any risks for enabling it, in fact it would have better results in any case.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Answer: Default behaviour, creation of connection with upstream for each request is not safe for heavy load. Because of following reasons:

once a request come to nginx server from the same client itself also, it will create a new connection with upstream server, for which, it will use the new available local port.
Once it completes the request, the give connection on that local port will move from established to TIME_WAIT for 120 seconds, this means for 120 seconds, that local port cannot be reused for any new request
now the second request come from same client, it will repeat step 1.
in this way for heavy duty load,

you may end up in using all available local ports on the nginx (65k)
Creation & termination of connection on every request is very costly
operation

So to avoid that, but best you can do is to Cache the connection, so that when request come, you may reuse the same connection with upstream server (on the same local port, as you did for last request)
Regards
Vj
Comment: Thanks for taking the time to answer !
The blog post I linked is saying that re-openning a new connection to backend for each request is the safe way. But also inefficient like you said.
What I'm trying to understand is what are the risks of enabling keepalive. Your answer seems to be about the risks of NOT enabling keepalive.


How do I redirect subdomains to a different port on the same server?

Question: I have some subdomains I want to redirect to specific ports on the same server.
Say I have
dev.mydomain.com

I want dev.mydomain.com to transparently redirect to mydomain.com:8080 and I want to preserve the original sub-domain name the url of the browser.
How do I do this with Apache 2.2? I have Apache 2.2 running on default port 80. I can't figure out the write configuration to get this to happen.
I have already set up dev.mydomain.com to resolve in DNS to mydomain.com.

This is for an intranet development server that has a non-routable ip
  address so I am not so concerned about exploits and security that
  would compromise a publicly facing server.
Answer: Solution
Here is what I finally came up with after being set in the right direction by Miles Erickson. I wanted the address bar to reflect the original subdomain/domain of the request and not the redirected server and port, but he put me on the right path to Google up a solution using VirtualHost and I finally found a solution that included the use of mod_proxy.
First, make sure mod_proxy is enabled:
sudo a2enmod proxy
sudo a2enmod proxy_http
sudo a2enmod proxy_balancer
sudo a2enmod lbmethod_byrequests
sudo systemctl restart apache2

Next, add the following to your site config (e.g., /etc/apache2/sites-available/000-default.conf):
<VirtualHost *:80>
    ServerAdmin firstname.lastname@example.com
    ServerName dev.mydomain.com
    ProxyPreserveHost On

    # setup the proxy
    <Proxy *>
        Order allow,deny
        Allow from all
    </Proxy>
    ProxyPass / http://localhost:8888/
    ProxyPassReverse / http://localhost:8888/
</VirtualHost>

Comment: For everyone who this answer didn't work for, keep in mind that you have to enable mods `mod_proxy` as well as `proxy_http`.
Comment: What about in `nginx` ?
Comment: For macOSX, don't waste hours like me trying to edit `/etc/apache2/extra/httpd-vhosts.conf`. My `httpd.conf`wasn't looking at this vhosts file by default. I had to add my new conf to `/private/etc/apache2/other` ([ref](https://jasonmccreary.me/articles/configure-apache-virtualhost-mac-os-x/)). Everything else above worked as is.
Answer: Run the following line on terminal (specify your domain and sub domain name correctly)
sudo nano /etc/apache2/sites-available/subdomain.example.com.conf

Paste the following code and change as your requirement
<VirtualHost *:80>
        ServerAdmin firstname.lastname@example.com
        ServerName subdomain.example.com
        ServerAlias subdomain.example.com
        ProxyRequests Off

        #ProxyPass / http://localhost:8080/
        <Location />
                ProxyPreserveHost On
                ProxyPass http://example.com:8080/
                ProxyPassReverse http://example.com:8080/
        </Location>
     # Uncomment the line below if your site uses SSL.
     #SSLProxyEngine On
</VirtualHost>

Run the following lines on terminal (specify your domain and sub domain name correctly)
sudo a2enmod proxy
sudo a2enmod proxy_http
sudo a2ensite subdomain.example.com.conf
sudo service apache2 restart

Comment: Is there any essential difference between this and the accepted answer?
Comment: Correction in registering subdomain
 `sudo a2ensite sub.yourdomain.com`
Comment: Most of the people forget to add `sudo a2enmod proxy_http` so they face difficulties on running properly. Also I try to give full process from start to end in a sequence to help more acculturate. Thanks for your question.
Comment: This just does not work for me. 'sudo a2enmod subdomain.domain.com.conf' says "ERROR: Module x.y.z does not exist!" Does it have to be mentioned in the 'default' configuration?
Comment: @dirk-schumacher can you please give your configuration file details here so that we can identify the exact error cause.
Comment: Thanks kasperd for asking it's just a little bit tweaking for people like me who forget some little things which are essential like sudo a2enmod proxy and sudo a2enmod proxy_http command after creating the configuration file.
Answer: Assuming that dev.mydomain.com can be resolved to mydomain.com's IP, you could add the following to your httpd.conf:
NameVirtualHost *:80

<VirtualHost *:80>
    ServerName dev.mydomain.com
    redirect / http://mydomain.com:8080/
</VirtualHost>

Relevant Apache documentation:

Guide to creating name-based virtual hosts
Core, including VirtualHost and NameVirtualHost
Redirect

Related question:
Apache redirect based on hostname
(Note: the original version of this answer incorrectly suggested the use of RedirectMatch, which, as @ChrisS helpfully pointed out, cannot parse the domain portion of the URL.)
Comment: see my self provided answer for what I actually used, which is this idea of VirtualHost with mod_proxy to preserve the original host instead of doing a redirect. This is an internal server so I am not concerned with security or exploits of mod_proxy.
Comment: Found numerous other suggestions but this ultimately worked for me on Windows Server 2008 R2/Apache 2.2.25.
Comment: The problem with this solution is that in your brother, you don't stay on the first domain, you get a 302 to the second.
Answer: Add in your main vhost configuration the following lines:
ProxyPreserveHost On
ProxyPass / http://example.com:8080/
ProxyPassReverse / http://example:8080/

Note that this requires mod_proxy on Apache.
Comment: He doesn't want a redirect, as per his OP. He wants the original URL to remain in the address bar; this means using either mod_proxy or mod_rewrite, and y'all better avoid mod_rewrite.
Comment: This is not a redirect; it proxies the connection. Enabling mod_proxy can be extremely easy to exploit if you aren't very careful configuring it. I would highly recommend against this.
Answer: You're looking for mod_rewrite. Here's the link to Apache's documentation which includes many examples for basic and advanced configurations..
And if you're unable to interpret the documentation yourself, try adding this to httpd.conf:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^dev\.example\.com$ [NC]
RewriteRule ^(.*)$ http://example.com:8080$1 [R=301]

And if that's not a clear example, here's a link to a mod_rewrite beginners guide too.
Comment: I'm on shared hosting. Rewrite is the only option. I can create a .htaccess file, but not a proxy or virtual host.


Display a block based on the term reference field of the current node

Question: What I'm trying trying to do sounds fairly simple, but I can't get my head around it.
I'm having 2 taxonomy vocabularies: machinery and batteries (both created with NAT for all that matters), and 2 content types which are named the same.
Both the content types provide the ability to check related items (a regular term reference field). For the machinery node the user can check which batteries are suitable, and for the battery node the user can check which machines use this battery.
Basicly what I'm trying to is: if you're on a page about a specific machine, it should show the batteries that are related to it, be it as teasers (or fields) in a block. And vice versa: when you're on a page about a specific battery, it would show all the machines in which it fits.
I've been boggling around with relationships and contextual filters, but it just wouldn't work out so far (spent a couple of hours here). Does anyone have an idea how to sort this out please?
Answer: There's possibly an easier way with the References module. In that case it wouldn't even require NAT, but just a View with contextual filter based on the Reference field.
Comment: Just saying there is a way is not an answer. Please describe that way.
Comment: Actually it's pretty straight forward.

1) Provide a node reference field to the content type you want to display.
2) Use that field as a contextual filter in the View.
Answer: I can't summarize those instructions, MPD, you have to follow the exact steps or it won't work. Full instructions:
Create
2 content types, both correctly configured with NAT:
Machinery
Battery

2 vocabularies, both will be filled along the way with terms generated by NAT:
Machines
Batteries

Remark the difference in names, just to keep things clear in this explanation (so you don't mix up).
Add a "Term reference" field in both the content types. In het "Machinery" content type this field will refer to the "Batteries" vocabulary, and vice versa: the "Battery" content type has a term reference field that's linked to the "Machines" vocabulary.
Create the necessary nodes with both the Machinery and the Battery content type - which will generate terms in both the Machines and Batteries vocabulary.
Once this is done, check the right terms in each node: what batteries are related to this machine (for the Machinery nodes), and vice versa: in what machines does this battery fit (in the Battery nodes).
Once this is done, create a View and create a block in it. The block in this example will display related machines, being displayed on the page of a battery.
Set the format to whatever you like (HTML-list, unformatted, grid, ...). I'm using fields in this example (not content, but it should work as well).
Add the fields you'd like to show (Title, Image, ...)
Add the following filter: Content: type (=Machinery)
Now add 2 relationships:

NAT: Nid (Identifier: "NAT node")
Content: Taxonomy terms on node

Relationship: "NAT node"
Vocabularies: "Machines"
Identifier: "term"

Add a contextual filter:

File Usage: Entity ID

Relationship: "NAT node"
When the filter is not available: provide default value (Content ID from URL)
Finally go to the Query settings of the View and check "Distinct" (to avoid duplicates).

Et voila, the first block is ready to go.
For the second block that will show associated batteries on a Machinery page, duplicate the block we've just created and modify the proper settings accordingly (content type filter, vocabulary in taxonomy terms on node).
You should be good to go - it works in both ways now.
I've add some screenshots in case they may be useful (with other names though than in this example, so don't get confused).
(Maybe the EVA module does something similar, both the method above works in both directions)


UIScrollView does not receive touch events immediately after appearing

Question: I have a drawing app where I load an image into a UIImageView and use touchesBegan, touchesMoved and touchesEnded to draw simple lines. I moved by UIImageView into a UIScrollView to allow the user to zoom in on the drawing. Now, after loading the image, if the user tries to start drawing immediately (within a couple of seconds of the image becoming visible), touchesBegan does not fire. If the user waits 2 or 3 seconds to begin drawing, all works as expected.
I have tried setting delaysContentTouches=NO with no effect. I have also implemented touchesShouldBegin: but this method is only called when touchesBegan is called (and the drawing works properly). Other solutions I have seen (such as ensuring user interaction is enabled and using hitTest to make sure the hit occurs in the view I expect) don't seem to apply in my case since everything works as expected after 2-3 seconds. Are there any other timing issues I should be aware of?
Answer: Try this:
    scrollView.canCancelContentTouches = NO;

If you have any kind of gestures, you need to use this possibly:
    gestureRecognizer.cancelsTouchesInView = false;

Comment: I've had this problem with Sprite Kit when trying to select the right object, but in this case. you're trying to draw right after the image is being moved. You will need to find a work around. You're only going to have timing issues if you're actually using multiple threads. Provide some code, then maybe I can figure something out.


Just in Time Debugging in VS2015 - crtexe.c

Question: I am attempting to debug a Microsoft application using VS's Just in-time debugger. At a certain point, I am prompted to locate the crtexe.c file. I cannot seem to locate the file. Any idea how this should be resolved (i.e. should I be aware of where this file is)? It appears that if I cannot locate this file, I cannot set breakpoints (VS says "You need to find crtexe.c to view the source for the current call stack frame"). Also, just for my own curiosity, what is the purpose of the crtexe.c file?
(It is my first time using the Just in-time debugger and that is why I am slightly clueless regarding crtexe.c etc.)
Answer: The header for crtexe.c says:
/***
*crtexe.c - Initialization for console EXE using CRT DLL
*
*       Copyright (c) Microsoft Corporation. All rights reserved.
*
*Purpose:
*       This is the actual startup routine for apps linking to the CRT DLL.
*       It calls the user's main routine [w]main() or [w]WinMain after
*       performing C Run-Time Library initialization.

It sounds like you are debugging an application that was built in an older version of Visual Studio. crtexe.c was available in the C Runtime source code included with VC++ 2013 and earlier. (Maybe paid versions only?)  For example, with Visual Studio 2013, the file was located in C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\crt\src\crtexe.c. I don't see it in Visual Studio 2015, so I suspect it may have been renamed and/or removed as part of the Universal CRT effort.
Therefore, to see the source code to crtexe.c and debug that code, you need to install the version of VC++ that the application was built with.
Having said that, it's unlikely you need that source code. The only reason that you are being asked for the source location is for your convenience viewing that code from the call stack. Typically you can just click Cancel and you'll still be able to see your own code.


Power analysis in R - Sample size

Question: I have a question regarding power analysis in R using the following function:
library(pwr2)
pwr.2way(a=2, b=8, alpha=0.01, size.A=12, size.B=12, f.A=0.47, f.B=0.4)

whereas:
a=levels of first group
b=levels of second group
alpha=confidence interval
sizeA=sample size of group A
sizeB= sample size of groupB
f.A=effect size of A
f.B=effect size of B

I'm wondering if my sizeA and sizeB is correct and why there are two variables for it. I'm working with a two way anova in a full factorial design.
Isn't the sample size always the same for both group A and group B?
Are there cases where the sample size differs?
Like I said, I'm using a 2x8 full factorial design with a repetition of 12 per treatment. So did I use the right sample size in my code above?
Answer: There is no way for us to know if what you did is correct -- that depends on your situation. But there are certainly cases where the sample size varies two groups (or more than two groups). In observational studies, I'd say it's usually the case that the sample sizes vary.

Power analysis in R - Sample size


python: Vectorised Def works only on the first condition. Subsequent loops are unaffected

Question: I have a vectorised def:
def selection_update_weights(df):
    # Define the selections for 'Win'
    selections_win = ["W & O 2.5 (both untested)", "Win (untested) & O 2.5", "Win & O 2.5 (untested)", "W & O 2.5",
                      "W & O 1.5 (both untested)", "Win (untested) & O 1.5", "Win & O 1.5 (untested)", "W & O 1.5",
                      "W & U 4.5 (both untested)", "Win (untested) & U 4.5", "Win & U 4.5 (untested)", "W & U 4.5",
                      "W (untested)", "W"]

    # Create a boolean mask for the condition for 'Win'
    mask_win = (df['selection_match'] == "no match") & \
               (df['selection'].isin(selections_win)) & \
               (df['result_match'] == "no match") & \
               (df['result'] != 'draw')

    # Apply the condition and update the 'Win' column
    df.loc[mask_win, 'Win'] = df.loc[mask_win, 'predicted_score_difference'] + 0.02

    # Define the selections for 'DNB'
    selections_DNB = ["DNB or O 2.5 (both untested)", "DNB (untested) or O 2.5", "DNB or O 2.5 (untested)",
                      "DNB or O 2.5", "DNB or O 1.5 (both untested)", "DNB (untested) or O 1.5",
                      "DNB or O 1.5 (untested)", "DNB or O 1.5", "DNB (untested)", "DNB"]

    # Create a boolean mask for the condition for 'DNB'
    mask_DNB = ((df['selection_match'] == 'no match') & \
                (df['selection'].isin(selections_DNB)) & \
                (df['result_match'] == 'no match') & \
                (df['result'] != 'draw'))

    # Apply the condition and update the 'DNB' column
    df.loc[mask_DNB, 'DNB'] = df.loc[mask_DNB, 'predicted_score_difference'] + 0.02

    # Define the selections for O 1.5'
    selections_O_1_5 = ["W & O 1.5 (both untested)", "Win (untested) & O 1.5", "Win & O 1.5 (untested)",
                        "W & O 1.5", "DNB or O 1.5 (both untested)", "DNB (untested) or O 1.5",
                        "DNB or O 1.5 (untested)", "DNB or O 1.5", "O 1.5 (untested)", "O 1.5"]

    # Create a boolean mask for the condition for 'O 1.5'
    mask_O_1_5 = ((df['selection_match'] == 'no match') & \
                (df['selection'].isin(selections_O_1_5)) & \
                (df['total_score'] < 2))

    # Apply the condition and update the 'O 1.5' column
    df.loc[mask_O_1_5, 'O_1_5'] = df.loc[mask_O_1_5, 'predicted_total_score'] + 0.02

    # Define the selections for O 2.5'
    selections_O_2_5 = ["W & O 2.5 (both untested)", "Win (untested) & O 2.5", "Win & O 2.5 (untested)",
                        "W & O 2.5", "DNB or O 2.5 (both untested)", "DNB (untested) or O 2.5",
                        "DNB or O 2.5 (untested)", "DNB or O 2.5", "O 2.5 (untested)", "O 2.5"]

    # Create a boolean mask for the condition for 'O 2.5'
    mask_O_2_5 = ((df['selection_match'] == 'no match') & \
                (df['selection'].isin(selections_O_2_5)) & \
                (df['total_score'] < 3))

    # Apply the condition and update the 'O 2.5' column
    df.loc[mask_O_2_5, 'O_2_5'] = df.loc[mask_O_2_5, 'predicted_total_score'] + 0.02

    # Define the selections for U 4.5'
    selections_U_4_5 = ["W & U 4.5 (both untested)", "Win (untested) & U 4.5", "Win & U 4.5 (untested)",
                        "W & U 4.5", "U 4.5 (untested)", "U 4.5"]

    # Create a boolean mask for the condition for 'O 2.5'
    mask_U_4_5 = ((df['selection_match'] == 'no match') & \
                (df['selection'].isin(selections_U_4_5)) & \
                (df['total_score'] > 4))

    # Apply the condition and update the 'O 2.5' column
    df.loc[mask_U_4_5, 'U_4_5'] = df.loc[mask_U_4_5, 'predicted_total_score'] - 0.02

    return df

First run works:
However, subsequent loops don't yield any changes.
While I have a very large dataframe, Columns are updated partially. And I am not sure why.
The original dataframe is unaffected.
Would it help if I break down every if-else but the dataframe is too big and the row calcs take 20 mins?
and I apply it by:
df = selection_update_weights(df)

First run works:
home_score  away_score  total_score  score_difference  predicted_total_score  predicted_score_difference result predicted_result result_match  Win  DNB  O_1_5  O_2_5  U_4_5                  selection selection_match
3            2           0            2                 2              12.370528                   12.090888   home             home        match  1.1  0.7      2      3      4  W & O 2.5 (both untested)        no match
9            2           0            2                 2              11.439416                   10.291339   home             home        match  1.1  0.7      2      3      4  W & O 2.5 (both untested)        no match
10           2           0            2                 2              11.226599                   10.228954   home             home        match  1.1  0.7      2      3      4  W & O 2.5 (both untested)        no match
11           1           5            6                 4              12.069979                   10.194557   away             home     no match  1.1  0.7      2      3      4  W & O 2.5 (both untested)        no match
20           2           0            2                 2               9.808659                    9.049657   home             home        match  1.1  0.7      2      3      4  W & O 2.5 (both untested)        no match

When I run the def provides:
home_score  away_score  total_score  score_difference  predicted_total_score  predicted_score_difference result predicted_result result_match       Win  DNB     O_1_5     O_2_5  U_4_5                  selection selection_match
44           3           3            6                 0               8.748172                    8.135116   draw             home     no match  8.155116  0.7  2.000000  3.000000    4.0  W & O 2.5 (both untested)        no match
50           1           0            1                 1               8.605350                    7.932909   home             home        match  1.100000  0.7  8.625350  8.625350    4.0  W & O 1.5 (both untested)        no match
57           1           1            2                 0               7.510030                    7.750101   draw             home     no match  7.770101  0.7  2.000000  7.530030    4.0  W & O 1.5 (both untested)        no match
62           0           1            1                 1               8.895045                    7.710740   away             away        match  1.100000  0.7  8.915045  8.915045    4.0  W & O 1.5 (both untested)        no match
85           1           0            1                 1               8.099853                    7.444815   home             home        match  1.100000  0.7  8.119853  8.119853    4.0  W & O 1.5 (both untested)        no match

However, subsequent loops don't yield any changes.
While I have a very large dataframe, This snippet is where the weights don't get updated. Weights are updated partially. And I am not sure why.
df.head():
home_score  away_score  total_score  score_difference  predicted_total_score  predicted_score_difference result predicted_result result_match  Win  DNB  O_1_5     O_2_5  U_4_5                  selection selection_match
44           3           3            6                 0               8.748172                    8.135116   draw             home     no match  1.1  0.7    2.0  3.000000    4.0  W & O 2.5 (both untested)        no match
50           1           0            1                 1               8.605350                    7.932909   home             home        match  1.1  0.7    2.0  8.625350    4.0  W & O 1.5 (both untested)        no match
57           1           1            2                 0               7.510030                    7.750101   draw             home     no match  1.1  0.7    2.0  7.530030    4.0  W & O 1.5 (both untested)        no match
62           0           1            1                 1               8.895045                    7.710740   away             away        match  1.1  0.7    2.0  8.915045    4.0  W & O 1.5 (both untested)        no match
85           1           0            1                 1               8.099853                    7.444815   home             home        match  1.1  0.7    2.0  8.119853    4.0  W & O 1.5 (both untested)        no match

So when I am applying it:
df = selection_update_weights(df)

I should ideally get
home_score  away_score  total_score  score_difference  predicted_total_score  predicted_score_difference result predicted_result result_match       Win  DNB    O_1_5    O_2_5    U_4_5                       selection  selection_match
          3           3            6                 0               8.748172                    8.135116   draw             home     no match  8.155116  0.7       2.0         3      4.0      W & O 2.5 (both untested)        no match
          1           0            1                 1               8.605350                    7.932909   home             home        match  1.100000  0.7  8.625350  8.625350      4.0      W & O 1.5 (both untested)        no match
          1           1            2                 0               7.510030                    7.750101   draw             home     no match  7.770101  0.7       2.0  7.530030      4.0      W & O 1.5 (both untested)        no match
          0           1            1                 1               8.895045                    7.710740   away             away        match  1.100000  0.7  8.915045  8.915045      4.0      W & O 1.5 (both untested)        no match
          1           0            1                 1               8.099853                    7.444815   home             home        match  1.100000  0.7  8.119853  8.119853      4.0      W & O 1.5 (both untested)        no match

However that's not happening and the original dataframe is unaffected.
Would it help if I break down every if-else but the data frame is too big and the row calcs take 20 mins?
Comment: Can you share the following things:

1. The df.head().values
2. The name of the columns as a list

In order to replicate this on local...
Comment: Sure. If you would want the dataframe on which this is built: [here](https://gofile.io/d/bu3N1p) and if you want the simplified code that I am working with, [here](https://pastebin.com/8Sa8815X)
Answer: In the second loop you only Win and O_2_5 columns are updated.
Win is updated in function of the value predicted_score_difference
O_2_5 is updated in function of the value predicted_total_score
predicted_score_difference and predicted_total_score never change in selection_update_weights, so we could consider predicted_score_difference , and predicted_total_score as constants in selection_update_weights. Since you are calling a method multiple times and updating its value in terms of constants, they will never have another value.
I'm not sure why you want to call selection_update_weights multiple times, but maybe you should update Win, O_2_5 (and the rest of the other columns) in terms of themselves or update predicted_score_difference and predicted_total_score in the selection_update_weights function
Comment: Oh ok. So how should I rewrite the function? See the expected dataframe is what I want after the fist loop and then subsequently too. As the additions are to the total_score and score_difference columns, they should be updated at every instance the conditions match? Unless I understand vectorisation incorrectly.
Comment: Let's think in gradient descent.
https://wikimedia.org/api/rest_v1/media/math/render/svg/26a319f33db70a80f8c5373f4348a198a202056c
There weights are calculated such that they minimize a function.
The value of the weights in iteration i+1 is a function of the i values plus characteristics of the function.
You should update O_2_5 based on O_2_5 and other characteristics (like total_score etc), the same for the rest of the weights
I don't know the algorithm you are implementing but I think you should consider what I said above


How to uninstall MySQL?

Question: I have tried for 6 hours to uninstall my old MySQL Server and install a new one.
Now I have 6 service from old instalations, which I don't know how to delete, I have NO SINGLE MySQL File on my HDD, but there is a server, because when I try to install it newly, it tells me "current PW" and that it can't start the Service and I don't know why.
I don't know what I should describe, I have deleted every single file on my HDD after a restart, but the server seems still active. I have no idea on which port or how to find out where the server is running.
Comment: what operating system?
Answer: I can only assume you're running a Windows server here, given your usage of the word "service" and the reference to the password wizard.
To find out what a service is running, go to your Services control panel (Control Panel > Administrative Tools > Services) and locate the MySQL Service. Right-click it and go to properties.
There will be a "Path to Executable" (just above the "Startup Type"). This is where Windows is finding its MySQL server. The field is even highlitable so you can just copy and paste it straight into Explorer to locate the file.
However the correct method of un-installing a MySQL server is to go to Programs, locate MySQL, right-click and go "Un-Install"
If you are running *nix and you installed MySQL with apt-get the correct method to remove it is apt-get remove <package> (where  was the name of the MySQL package you used to install). If you want to make sure you even get rid of the config files and all the rest of the files, then add the --purge option to the command.
Answer: I assume you're installing on Windows, what version?  For XP/2003, first stop any listed MySQL services under the [control panel > administrative tools > services] MMC console.
Then [run > cmd] to get a command prompt (must be logged in as an admin), and type the follwing to delete the MySql services:
SC DELETE [servicename]
That should remove the services, and you can delete any remaining MySQL directories and files manually before reinstalling.

How to uninstall MySQL?


property of function

Question: Let $f _n (x)=x ^n$  .
If I want to get $f_{n+1}'(x)$ ,
firstly I find $f _{n+1} (x)=x^ {n+1}$   and next differentiate $f _{n+1} (x)=x^ {n+1}$  ,
I obtain $f _ {n+1}' (x)=(n+1)x^ n $ .
But in other ways, firstly differentiate $f _n (x)$ , obtain $f  _n '(x)=nx^ {n−1} $ , and substitute $n+1$  for $n$  in $f  _n '(x)=nx^ {n−1}$  , I get $f_  {n+1}' (x)=(n+1)x ^n$   too.
I think second ways is not definition of $f ′ _{n+1} (x)$ .
Is there any function which satisfying first ways is not equal to second ways?
Answer: Many functions satisfy this, but only because you are viewing $n$ as a fixed parameter.  You really have a function $f(x,n)$ and are asking does $\frac {\partial f(x,n)}{\partial x}|_{n \to n+1}=\frac {\partial f(x,n+1)}{\partial x}$ or do partials and substitution commute?  So let me define $f_n(x)= \begin {cases} x&n=1\\5x&n=2 \end {cases}$ and it fails.  Good for you to be thinking about this.
Answer: As long as you stick to real, continuous functions, no. Here's the reasoning:

In the first example you provided, you find the next term, then take its derivative. You end up with the derivative of the $(n+1)$th term.
In the second example you provided, you find the general derivative term, then plug in $n+1$. You end up with the derivative of the $(n+1)$th term.

To think about it another way:
$$f_n{x}\to f_{n+1}{x}\to f'_{n+1}{x}$$
$$f_n{x}\to f'_n{x}\to f'_{n+1}{x}$$
Both get you to the same place. There's no reason why this would change. However, for discontinuous functions, it could very well be different.
Comment: We are taking the derivative with respect to $x$, not $n$.  There is no derivative of $n+1$  Also no function is differentiable at a discontinuity.  You are correct that a large class of functions, continuous in both $x$ and $n$ satisfy this.
Comment: @Ross Ah, yeah, typing without thinking. Fixed the couple errors, sorry!

property of function


How to create "Add to my List"?

Question: I have a movie site and I want users to be able to add movies (node) to their list by visiting the movie and it should have a link saying "Add to my list". When they are about to add to their list it should have a selection box with options like watching, completed, on-hold etc...
An example site http://myanimelist.net/anime.php?id=269 you can see when you click their "Add to my List" it gives some more options like status, eps seen, score
So how can I do this?
Answer: I would recommend using the Flag module, as it provides this functionality for users upon install. The Nodequeue module is intended for admin-configured lists.
Comment: I'm using the flag module but I don't know how to make a drop down list to give more options such as completed, ongoing, on-hold.
Answer: Use the nodequeue module http://drupal.org/project/nodequeue: The Nodequeue module allows users to collect nodes in an arbitrarily ordered list. The order in the list can be used for a any purpose, such as...A user's favorite music albums or the flag list module http://drupal.org/project/flag_lists

How to create "Add to my List"?


Maximum input for the second input?

Question: I would like to know, how to limit the input based on the first input. Let say that in the first input, 10 was entered. Then, the second input should not be allowed to exceed 10.
<input type="number" id="a1" value=""/>
<input type="number" id="a2" value="" max=""/>

In the first time, i thought about jQuery to set the max attribute. but, I cannot set max, but only the input value. Thank You
Answer: You can do this:
$('#a1').on('change input', function(){
    $('#a2').attr('max', this.value);
});

Demo

Place two events change input change input occurs when you click the arrows up/down of input[type="number"] and input occurs when you press any key or paste some value init.
Comment: Thanks a lot guys, those JQ works well. And also C-link code is works well. the different is this one can has equal value.
Comment: You should also set the #a2's value if it's bigger than #a1 newer value.
Answer: You can use like this:
$('#a1').on('change blur',function(){
   $('#a2').prop('max',this.value++);
});

working fiddle
Comment: What if I change the #a1 value after a while?
Comment: what if a1 value is less
Answer: You have to listen for changes applied to #a1 and update the max property of #a2. You can use jQuery, but Vanilla JS will do just fine(and faster).
There is one problem. If you have #a1's value 10, and #a2's value is 9, you will have to decide what to do with the #a2's value if you change #a1 to something smaller, like 5.
Comment: yeah that's a problem too. the simple one maybe double checking, when it is submit, then i need to check if it bigger or not. if bigger then cancel the submit. But, I think it can be done by simple way with jquery, but i am confused haha
Comment: You just need a change listener, the rest will come, trust me :)
Answer: You can do following :
 $(document).ready(function()
{
   $("#a2").attr('maxlength',$("#a1").attr("maxlength"));
});

and then listen to changed dom value of a1 div doing something like this
Answer: Try this with jQuery
$('#a1').on('change', function(){
    var two = $('#a2');
    two.attr('max',$(this).val());
});

jsFiddle
Note: Works if you try to increment using the up-down arrow inside the input (html 5 property)
Answer: you can on keyup event of second input .
$('#a2').on('keyup', function(){
    var v2=parseInt($(this).val()) || 0;
    var v1 =parseInt($('#a1').val()) || 0;
    if(v2 > v1){
        $(this).val('');
    }
});

DEMO
Answer: You can subscribe to change event of '#a1' and onchange event handler change max attribute of #a2.
$( "#a1" ).change(function() {
  $('#a2').attr('max',$(this).val());
});

Maximum input for the second input?


Como criar atalho na área de trabalho de um site quando estiver usando o chrome?

Question: Gostaria de sugerir para o usuário quando ele entrar no meu sistema criar um atalho do site no computador dele, isso pode ser feito manualmente indo em "Mais Ferramentas -> Adicionar a área de trabalho":

Como poderia fazer isso programaticamente? existe alguma api do chrome ou função nativa que permita?
Comment: Isso não é possível apenas com JavaScript, provavelmente por questões de segurança.
Comment: Poderia ser feito como Notifications API, mostrar uma notificação pedindo permissão, seguindo esse formato não haveria problema algum de segurança, o problema é forçar o usuário a criar um atalho.
Comment: Também é possível fazer isso utilizando Progressive Web Apps - PWA.
Answer: Cara se eu fosse você eu faria um arquivo .bat e chamaria a execução dele com o Javascript.
O arquivo Javascript:
var objetoMan = new ActiveXObject("Scripting.FileSystemObject");
var WshShell = new ActiveXObject("WScript.Shell");
var oExec = WshShell.Exec("c:\\temp\\SeuArquivo.bat");

O arquivo .bat:
copy \\server\programa\NomeDoAtalho.lnk %userprofile%\desktop


Are opinions considered sentences in Logic?

Question: I am beginning to read the book titled forallx An Introduction to Formal Logic by P.D. Magnus. This is an open source book. On page 4 Magnus states:

In this open source book found here: https://math.libretexts.org/Courses/Fullerton_College/Math_100%3A_Liberal_Arts_Math_(Claassen_and_Ikeda)/05%3A_Logic/5.01%3A_Logic_Statements  the author states that opinions don't count as sentences because one person might consider it true while another might consider it false.

This author wouldn't consider "Rhubarb is tasty." as a sentence. So which definition is correct to use? Thank you!
Comment: You should cite one of the books that you think conflicts with what Magnus writes, otherwise we can't come to a fair judgment. The key point is that logic is about reasoning from a well-defined set of agreed principles.
Comment: @Karl There are plenty of mathematical or meta-mathematical statements which are opinions, at least so far as humans know.  In fact, opinions are *necessary* for mathematical research.  "The Goldbach Conjecture is False" would be one, longstanding, example of an opinion which is not known as true, nor false.
Comment: Sounds good. I'll edit the question.
Comment: Math is not a study of opinions. Any mathematical terminology should be precisely defined before it is used.
Comment: I don't see why both can't work out as correct.  Those authors both define their terms.  One allows for a 'sentence' to be an opinion.  One defines a 'statement' as necessarily true or false and thus not an opinion.  In effect, the later definition implies that at present The Collatz Conjecture and The Goldbach Conjecture are not 'statements'.  This strikes my ears as strange, but so long as one defines one's terms, I don't see any confusion or issue.  But, I would keep in mind that sentences about unknown matters are necessary for research.  Thus, opinions are necessary.
Answer: This question would likely better be served in the philosophy stack exchange, as  after reading a few sentences it appears that Magnus's book is more focused on philosophy than mathematical logic. With that being said, I think Magnus means opinions in the sense that they can be well defined. For example, if "A piece of food is tasty because it has certain proteins in it" and "Rhubarb is a piece of food with special proteins in it", then "Rhubarb is tasty" would make sense as a sentence in logic. On the other hand, This second author is talking about opinions in general, if my two sentences are "You should eat tasty food" and "Rhubarb is tasty", Rhubarb is tasty has no real truth value, because its up to the eater. In philosophy (to my knowledge), many arguments are formed around opinions because they deal with real life issues that cannot be proven true or false, and are a matter of judgement. Either way, don't take anything I say as concrete, seeing as how this is a philosophy question less of a math one.
Answer: I much prefer Magnus' treatment over the second one. Logic doesn't care about whether some statement is actually true or not, let alone whether we know or believe it to be true. Logic only cares about implication: it asks: If we consider such-and-such to be true, what else would be true.
In fact, in logic we can work with completely non-sensical statements like 'Hupflubbers are brig' and 'Nothing that is brig is shomsooza', because logic will now tell you that it logically follows from those statements that 'No hupflubbers are shomsooza'.
Now, what is a potential worry is cases of ambiguity and vagueness, especially as we try to apply logic to real life. For example, if I use 'bank' to refer to a financial institution in one sentence, then we should not combine that with some other sentence where I use 'bank' to refer to a river's edge. And in real life, we may declare that 'John is a tall person' and that 'Susan likes tall people', but we should not be so quick to infer that Susan likes John: the context under which John is considered 'tall' may be quite different from the contect under which Susan likes 'tall' people and besides, does Susan literally like all tall people?!
But like I said, these considerations are mainly for when you try to apply logic to real life. As an abstract and idealized branch of mathematics, all that matters for logic is that the expressions have the abstract form of a statement … which is exactly what allows us to do formal logic.
And while the second source does allude to the potential issues of vagueness and ambiguity, I really don't like how it makes it sound as if it is about the difference between facts and opinions. Yes, as explained above, vagueness and ambiguity can hinder the application of logic to real life. But, as long as we are clear on our terms, then why does it matter whether something is fact or opinion? If the house is beautiful, and if I like beautiful things, then as long as the two sentences agree on their use of 'beautiful', we can infer that I like the house. That is, we can do logic on statements that are opinions just as much as on statements that are facts.
In fact, the line between 'fact' and 'opinion' is a lot more blurry than we like to think anyway. Is it a fact that Pluto is not a planet? Or even that $1$ is not a prime? Remember Pluto used to be a planet, and $1$ used to be a prime. And it wasn't as if we suddenly realized that we were wrong about these beliefs. We didn't say: 'Oh shoot! And here I thought $1$ was a prime, but it turns out I was wrong about it! Dang!' No, it simply was that we felt it was more useful and practical to regard Pluto as something other than a full-fledged planet. So the point is that one can have interminable discussions about what is 'fact' and what is 'opinion' or what would even make something 'true', but fortunately, as explained earlier, in the abstract context of mathematical formal logic we can completely sidestep such discussions: it just doesn't matter!
Indeed, as should be clear from what I have been saying, the goal of logic is not to 'establish truth'. As such, I find the second source confusing, if not inaccurate.
Comment: Thank you! Your explanation cleared this up for me. The only thing that I'm trying to understand is the meaning of "logic is that the expressions have the abstract form of a statement" in your explanation. What is meant by form? I have heard this mentioned a few times.
Comment: @Dr.J Take the example I gave in my post about hupflubbers. That inference is of the form 'All A's are B's. No B's are C's. Therefore, no A's are C's'.  This is a logically valid inference, no matter what the A's, B's, and C's stand for. So this is what formal logic does: it looks at the abstract form of the statements (often further symbolized by symbols like $\to$ and $\forall$), and it can tell on the basis of that abstract symbolic form or pattern whether the inference is valid or not, even if you don't know what the statements are about. Like I said, truth does not matter!


Interpret TimeStamp

Question: I am trying to interpret a series of numbers that are representing time so that I can change them in the near future to different numbers.
How long is 135671800? And what does each mean? Is it DD:HH:MM:SS?
{"next_timestamp":1356751800,"next_duration":9000,"next_title":"Saturday Night","next_description":"Hearing and Healing"}

The original javascript that is interpreting the result is:
else if (typeof data.next_timestamp !== "undefined") {
        seconds_till = data.next_timestamp - (new Date().getTime() / 1000);
        days = Math.floor((seconds_till % 31536000) / 86400);
        hours = Math.floor((seconds_till % 86400) / 3600);
        minutes = Math.floor((seconds_till % 3600) / 60);
        seconds = Math.floor(seconds_till % 60);
        return intervalId = setInterval(function() {
          if (--seconds < 0) {
            seconds = 59;
            if (--minutes < 0) {
              minutes = 59;
              if (--hours < 0) {
                hours = 23;
                  if (--days < 0) {
                days = 365;
                }
              }
            }
          }

Thanks!
Comment: According to the code it is seconds since some fixed time in the past. But is is the same point in the past that browsers use. The key is the code `(new Date()).getTime()` which returns in javascript the elapsed time in milliseconds since that time. It gets divided by 1000 to turn it into seconds and then subtracted from your time value which would need to have the same units ... seconds.
Comment: I believe it's usually seconds from the epoch.
Comment: I think you are right. But what is the fixed time in the past? I cannot figure out how to find it anywhere in my code. It is a countdown timer, and it all works, but the time in the past is where I am having trouble, I don't know what to set for the numbers to make it a specific day in the future.
Answer: If you are working with a standard timestamp you can just use the Javascript Date object.
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date
var date = new Date(/* timestamp * 1000 here */);
var day = date.getDay();
var month = date.getMonth();
var year = date.getFullYear();

Not sure what your interval is for but if you want to count this back down to 0...
// Assume that date still exists.
time = date.getTime() / 1000;
time--;
date = new Date(time * 1000);
day = date.getDay();
month = date.getMonth();
year = date.getFullYear();

Answer: It is seconds from "epoch" (seconds that have elapsed since midnight Coordinated Universal Time (UTC), 1 January 1970).
Actually Sat, 29 Dec 2012 03:30:00 GMT
See live counter here
http://www.epochconverter.com/
More about UNIX Time http://en.wikipedia.org/wiki/Unix_time

Interpret TimeStamp


Is it possible to use image styles in Views field rewriting?

Question: I would like to add "no results" behavior to an image field displayed in Views, such that the image from an alternate field is displayed. Ie., if Image1 is empty, display Image2.
Is it possible to use an image style in the rewrite code? I'm sure I can display the second image, using something like , but how can I specify that the image be displayed using the max_height_125 image style?
Answer: I figured it out! What you have to do is include a copy of the second field, set to "Exclude from display" in the options, and arrange the fields such that Image2 comes before Image1 in the list. You can set the image style in the options for Image2, and that information will get carried over when Image1 is empty and gets rewritten using the behavior specified in the "No results" option. Also, you don't have to write  in the rewrite area.  All you need is the token for the other field, like [field_Image2].


How to close Window in WinUI3?

Question: I have an app that consists of 2 parts. 1st part is Login form, where user needs to enter login and password. If they are correct, it start "Editor" window where user can work.
For now in order to launch second window I use:
var editorWindow = new EditorWindow();
editorWindow.Activate();

The problem is that Login window is still there, and while it is not critical, I still want to close it after Login is done.
First time I tried to add Window.Close() after opening the 2nd window in the .cs file of 1st Window, so
var editorWindow= new EditorWindow();
editorWindow.Activate();

var oldWindow = new MainWindow();
oldWindow.Close();

Which resulted  Attempted to read or write protected memory eror.
I tried to do it in the 2nd Window .cs file like this:
this.InitializeComponent();

var oldWindow = new MainWindow();
oldWindow.Close();

Which resulted the same error
So how can I do this properly?
Comment: Just call `this.Close()` right after you've called `Activate()` on the new window? Please post a reproducible example if you need more help.
Answer: If you open the second window in the code-behind of the first window, you should be able to just call this.Close() right after you've called Activate() on the new window:
var editorWindow= new EditorWindow();
editorWindow.Activate();

this.Close();

If you open the EditorWindow from somewhere else, you need to get a reference to the first window to be able to close it. You could for example use a variable in the App class for this as suggested here.
Comment: Thanks, that works. I dont know why I haven't thought of that.

How to close Window in WinUI3?


StrictModeDiskReadViolation when

Question: I am trying to use SharedPreferences to store some user settings for my app. I have this code in my Activity.onCreate method:
sharedPreferences = context.getSharedPreferences("MMPreferences", 0);
soundOn = sharedPreferences.getBoolean("soundOn", true);

but it gives me this error (it is the getBoolean that generates the error):
11-10 16:32:24.652: D/StrictMode(706): StrictMode policy violation; ~duration=229 ms: android.os.StrictMode$StrictModeDiskReadViolation: policy=2079 violation=2

and the result is that the value is not read and I also get the same error when I try to write to the SharedPreferences with this code (it is the commit that generates the error):
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("soundOn", soundOn);
editor.commit();

The only answers for this error I can find is about a strict mode warning, but my code actually fails to read/write the SharedPreferences key/value data.
Comment: Possible duplicate of [Should accessing SharedPreferences be done off the UI Thread?](http://stackoverflow.com/questions/4371273/should-accessing-sharedpreferences-be-done-off-the-ui-thread)
Answer: You must do fileSystem operations on a separate thread, then the error will go away.
you can also turn off the StrictMode (but i am not recommending that)
StrictMode.ThreadPolicy old = StrictMode.getThreadPolicy();
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder(old)
    .permitDiskWrites()
    .build());
doCorrectStuffThatWritesToDisk();
StrictMode.setThreadPolicy(old);

Comment: It works for sure, and I have tested that the thread is not alive when the app is in the background so it looks good. Just wanted to hear if you wizards thought it sounded like a good way to do it ;)
Comment: Ok I now create a thread on Activity.onCreate and this thread reads properties in startup and checks for dirty properties and writes those if needed, and I stop the thread on Activity.onPause and start it again on Activity.onResume. Sounds about right?
Comment: @Frank what "doCorrectStuffThatWritesToDisk() " mean ?   Thanks
Comment: It is your "business logic" that writes things to the disk. Basicly i am turning off strict mode, write, turn strict mode back on.
Answer: If you have reactive (RxJava)  configured in your Android project, you can take advantage of its properties like schedule a task on an I/O-specific Scheduler, for instance:
public void saveFavorites(List<String> favorites) {
    Schedulers.io().createWorker().schedule(() -> {
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        Gson gson = new Gson();
        String jsonFavorites = gson.toJson(favorites);
        editor.putString(Constants.FAVORITE, jsonFavorites);
        editor.apply();
    });
}

Comment: Use `editor.commit()` to avoid wasting another thread, since you're already there.

StrictModeDiskReadViolation when


How to programmatically trigger a click on an AJAX enabled form submit button?

Question: I'm trying to programmatically (with jQuery) trigger a click on button with AJAX behavior in a Drupal form, but so far jQuery('#edit-submit').click() doesn't do anything.
A real mouse click on that button works as intended. Any ideas how to make it work?
Comment: If it is an #edit-submit button, can you not just do $('form').submit()?
Comment: that didn't work for me either. It either posts the form in a non-AJAX way or does nothing, depends on some settings in the form builder.
Answer: jQuery('#edit-submit').mousedown() - apparently there's a big difference.
Comment: doesn't work for me
Comment: I would avoid using the ID selector on form elements. If the form is rebuilt during the AJAX callback, the IDs of all elements will change, and your jQuery selector will no longer work.
Comment: This solution worked for me. Clicking on the button executed the ajax call but .click() or variations didn't however .mousedown() works perfectly.
Comment: Exactly what Eric said.  I would like to know why there's difference... seriously, this seems not to make sense.
Comment: @JohnathanElmore `mousedown()` is just "the first part" of a `click()` event, which is complete when `mouseup()` occurs. When you click on a link and then you release the mouse outside the link's area, the `click()` doesn't usually get fired and the link is not followed. Probably an ajax call prevents the `mouseup()` to be fired, but this is just a guess...
Answer: Actually, there's no need to guess.
You should use Drupal behaviors
Drupal.behaviors.yourFunctionName = {
    attach:function (context, settings) {

       // Your code goes here....

    }
}

This will give you access to the settings' ajax property,
Drupal.behaviors.yourFunctionName = {
    attach:function (context, settings) {

       console.log(settings.ajax);

    }
}

Depending on your configuration, you should see a list of triggering elements, with various properties such as the name of the callback function, the selector's id as well as the name of the triggering event.
You can then use the relevant information to trigger your event.
// $(selector).trigger(eventName);
// for example...
$('#edit-product-id-15', context ).trigger('change');

Comment: I like this answer because it offers an interesting technique to discover how to interface with generated elements for non-Drupal frontend developers that might be working on a Drupal project. +1
Comment: Really helps, thank you bro
Answer: Create ajax submit like the following.
 $form['button'] = array(
    '#type' => 'button',
    '#value' => 'Click',
    '#ajax' => array(
      'callback' => '_kf_reading_user_points',
      'wrapper' => 'reading-user-points',
      'method' => 'replace',
      'event' => 'click',
    ),
  );

function _kf_reading_user_points(&$form, &$form_state) {
  // Something within the callback function.
}

Then the jquery .click() event would be work in the drupal ajax form.
Comment: Added the callback function :)
Comment: can you post the sample callback function too , when i tried ,its not going to callback function
Answer: You can also use .trigger() jQuery method. $('#element').trigger('click');
Answer: In my case, the above recommended solutions didn't work for me, but the mention of .mousedown() led to the following idea that worked for me (Drupal 7):
$('#custom-submit-button').click(function() {
  $('#ajax-submit-button').trigger('mousedown');
});

There's some helpful background info about "why" this is the case in the Form API Reference under #ajax_prevent
Comment: I didn't need the click() wrapper, but that link to ajax prevent was the KEY!
Answer: Looking at the Better Exposed Filters module, they submit the AJAX form by finding $(.ctools-auto-submit-click') and trigging a click.
<?php
// ... near line 190 of better_exposed_filters.js

// Click the auto submit button.
$(this).parents('form').find('.ctools-auto-submit-click').click();
?>

Comment: the click event worked for me, whereas the mousedown event didn't.
Answer: You have to trigger the submit event on the form. Click and mousedown events on buttons are not working.
Comment: That is what I tried at first, and it doesn't appear to be working correctly. Which is how I got here.


Question on Riemann Integration

Question: If $S=\{a_1,...,a_p\}$ is a finite subset of the compact interval $[a,b]$, and if the bounded function $f:[a,b]\rightarrow \Bbb R$ is such that $f(x)=0$ if $x\in[a,b]∼S$, then $f$ is Riemann integrable on $[a,b]$ and  $\int_a^b f(x)\,dx=0$.
$[a,b]∼S$ refers to the complement of $S$ relative to $[a,b]$.
$$[a,b]∼S=\{x\,|\,x\in[a,b],x\notin S\}$$
I would appreciate if someone could assist me  in helping me to understand the above question and how to solve it. Thank you.
Answer: Avoiding some notation, one has $$\left|\sum_{i=1}^n f(\xi_i)\Delta x_i \right|\le \sum_{i=1}^n |f(\xi_i)|\Delta x_i\le2\,p\,k \,\|P\|$$ where $P=([x_{i-1},x_i],\xi_i)_{1\le i\le n}\,$ is a tagged partition of $[a,b]$ and $k=\max \{|f(a_1)|,\dots,|f(a_p)|\}$.
In fact the $a_1,\dots,a_p\,$ belong to the subintervals of $P$ not more than twice.
The conclusion is obvious.
The point is that the Riemann integral can be defined with the exception of a finite number of points; however you define the function at these points, you obtain the same value of the integral.$$$$

Question on Riemann Integration


Multi-class classification with binary decision tree

Question: I've built a decision tree for multi-class classification (MNIST).
My question is, whenever I want to predict the label of a test pattern and I follow the tree depending on the values of the test pattern's attributes, what happens if there is not a left or right branch for a given test pattern attribute value?
In tree building process I add branches on the left OR right depending on the training pattern attribute value I'm testing against a threshold.
Comment: no more splits -> leaf node -> assign label to test instance -> compare actual digit with predicted by tree
Answer:
What happens if there is not a left or right branch for a given test
  pattern attribute value?

This can only be the case if the instance arrives in a leaf node of the tree, in which case no further traversal of it is necessary and we classify the instance based on the class-conditional probability of the instance resulting from the class proportions in this node.
If the current node is not a leaf, the split operator is true for the given attribute value either on the right or the left, as for this purpose only $\geq$ (greater-or-equal) and $\leq$ (less-or-queal) are used.
Consider the example below, taken from page 306 of (1):
 a two-dimensional data set is iteratively split by thresholds as shown in the top right plot, starting at $X_1$ where the first threshold $t_1$ is defined. In the plot on the bottom left we see the corresponding tree structure, where the first split is representing the top node $X_1 \leq t_1$. Any given $x_1 \in X_1$ is either less-or-equal than $t_1$, in which case it continues on the left, or greater than $t_1$, in which case it continues on the right. There is no middle ground here.

(1) Friedman, Jerome, Trevor Hastie, and Robert Tibshirani. The
  elements of statistical learning. Vol. 1. No. 10. New York: Springer
  series in statistics, 2001.
Comment: I found out the algorith for binary classification. Can you point me to the mult-class case?
Comment: What is unclear to you about the multiclass case? In a given leaf node, one uses the proportions of instances per clas that arrive there as estimates of the class-conditional probability - how one *decides* based on these is another matter entirely. For simple cases it might be enough assigning the class with the highest probability, while for more complex problems this might be suboptimal.


Change date every 56 rows in excel

Question: my objective is to have the same date repeated in the first 56 rows and then to vary to the next day in row 57.
That is:
if I start with date 8/31/2013 I expect to have this same date in the following 56 rows and then change it in 57 to 9/01/2013.
So far I have been working with this formula:
=IF(MOD(ROW(),56)=1,OFFSET(B2,-56,-1)+1,"")
I got to have the dates every 56 rows but still, I need to fill row 2-55 with the same date. Is there any formula or VBA code that helps me do that?
Answer: In B1 put your desired start date.  Then in B2 put and copy down:
 =$B$1+INT((ROW()-1)/56)

Change date every 56 rows in excel


Hashtable vs Dictionary

Question: My understanding is that Dictionary does not have boxing issues and faster in performance. Are there cases that the usage of Hashtable would be more advisable compared to Dictionary? Thanks
Answer: For .Net 2.0, you pretty much always want Dictionary.  However, be warned that it's not just a "drop in replacement" for an existing Hashtable.  There are some differences in the way they work (mostly how they handle nulls) that mean you do need to check your code first.
Comment: +1 For mentioning handling of nulls. It might be good to explain that more as that can be a bit unexpected to get an exception instead of null when a key does not exist in the dictionary.
Answer: Hashtable is pretty much deprecated. It might be useful for interfacing with legacy code.
Dictionary is a generic class introduced in .NET 2.0, along with other classes in System.Collections.Generic namespace. They supersede classes in System.Collections namespace.
Answer: The main advantage of HashTable is that you can use it and target .NET < 2.0.
Otherwise, Dictionary<T,Y> (used correctly) is pretty much better in every way.
Answer: Here is What i know
1) Dictionary stores in key value pairs
2) Hastable also stores in key value pairs but uses a hash key to probe the contents.
So if i were to decide what to use, Should i use hashtable if my collection is huge and i want to search for a certain item?
And use dictionary if the collection is not so huge?
Also a followup question is , in c#, hastable does not do chaining like in c or c++ is this correct?

Hashtable vs Dictionary


pandas date_time not converting the string into date format

Question: I have data of Jan-91 (mmm-YY) format. I am trying to convert is using pandas date_time function with code -
data['Month'] = pd.to_datetime(data['Month'], format = '%ddd-%YY')
However getting the error as
time data 'Jan-91' does not match format '%ddd-%YY' (match)
time data 'Jan-91' does not match format '%ddd-%YY' (match)
I am trying to expecting the output should be DD-MM_YYYY format.
Comment: Does this answer your question? [Convert string "Jun 1 2005 1:33PM" into datetime](https://stackoverflow.com/questions/466345/convert-string-jun-1-2005-133pm-into-datetime)
Answer: your datetime format is a little off. Instead of %ddd-%YY it should read "%b-%y". i.e. the code snippet should read:
data['Month'] = pd.to_datetime(data['Month'], format = '%b-%y')

If you look at the documentation for pandas.to_datetime, under format, it says that it uses strftime syntax to get the date format. Under strftime and strptime format codes, you will see the correct format codes are %b for a 3 letter month abbreviation, and %y for a zero-padded year without a century.
Then, to get the date into your desired format, you will need a second line to reassign the Month column:
data['Month'] = data['Month'].dt.strftime(date_format = '%d-%m_%Y')

Answer: According the Pandas documents, the format argument is only for parsing not for the destination format. So to get your desired output, you have to first parse into the default format, and then use the `` to produce your expected format:
data['Month'] = pd.to_datetime(data['Month'])
data['Month'] = data['Month'].dt.strftime('%d-%m_%Y')


How to check request method inside Python class?

Question: I have a class for Flask:
class Likes(object):
    def __init__(self, model, table_id):
        self.model = model
        self.table_id = table_id

        if request.form["likes"] == 'like':
            query = self.model.query.filter_by(id=table_id).first()
            query.likes += 1
            db.session.commit()
            flash(u'Like =)) ' + query.title, 'info')
        elif request.form["likes"] == 'dislike':
            query = self.model.query.filter_by(id=table_id).first()
            query.likes -= 1
            db.session.commit()
            flash(u"Don't like =(" + query.title, 'info')

and I want to call this class every time user sent POST request, but every time I create an instance of my class I need add check request type:
# ...
if request.method == 'POST':
    Likes(Post, request.form["post_id"])
# ...

How can I improve my class and add inside it this check:
if request.method == 'POST':
    # ...

Solution:
Use decorator @app.before_request
@app.before_request
def before_req():
    if request.method == 'POST':
        flash(u'Before request', 'success')

Comment: Why are you using a class instead of a function? It sound like a bad idea to call that everytime a post request is done. Please explain what you try to achieve otherwise it looks like [XY Problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem#)
Comment: i'm trying to create class for "likes" sytem which can be used for defferent content types in my app. This class should handle post request and looking for "like" or "dislike" values on it, depending on request it should add 1 like or remove it form data base.
Using different functions for every content type is not a good idea.
Comment: you don't necessarly need a class.
Comment: ok but this question is still actual for non-class based likes system, is there any way to avoid testing for request type when i call a function. Or as i can see second argument mention to call this check before function start do their job.
Answer: You can use Flask.request_started signal to run something everytime a request arrive and then execute the code you require.

flask.request_started
This signal is sent before any request processing started but when the request context was set up. Because the request context is
  already bound, the subscriber can access the request with the standard
  global proxies such as request.

Have a look at the Flask's Signals chapter to learn more.
Use something like that in your code:
def create_like(sender, **extra):
    if request.method == 'POST':
        Likes(Post, request.form["post_id"])

from flask import request_started
request_started.connect(create_like, app)

This was adapted from the example for the documentation of Core Signals.
Comment: thank you for your help =)
you give me a good idea and right info, but instead your function variant with import use a decorator @app.before_request i found here http://stackoverflow.com/questions/14367991/


user is "nobody" when creating directory PHP

Question: I have the following code:
 mkdir($thumb_dir)

which creates a directory in the proper location, but when I view the permissions it is
Owner : nobody
Group : nobody

I don't have shell access to chown. How do I prevent the user assigned as nobody and how do I delete the folder that I have already made since I don't have permission.
It's a godaddy shared server...
Comment: And `chmod()` doesn't work. right? did you try creating directories with `exec()` eg `mkdir -p{} -m{}`?
Answer: you can delete empty directories with rmdir().
nobody is the user that runs the apache process. You can't change the owner from within php, nor you can delete the folder using shell access (or make any changes on it whatsoever) without root permissions; you can manipulate it only through php
Comment: Thanks for the tip.. I used the selected answer here to delete the directory and files http://stackoverflow.com/questions/3349753/delete-directory-with-files-in-it. Doesn't resolve my assigned owner issue but if it isn't possible this is a good work around.
Comment: ok, if the directory is not empty, I would go with the directoryIterator option in that post, but keep in mind that you need 2 passes to avoid recursion: one to delete all files and one to rmdir all folders (for example by putting them in an array, reversing it and deleting each)
Answer: This happens because the Web server is run by the nobody user. Therefore, everything you do on the file system will be done with the privileges of nobody.
There is typically no way for you to change anything about that. You'll have to manage with the Apache user being different from the FTP user you have. If you create a directory with PHP, you'll only be able to delete it with PHP (using rmdir() when the directory is empty), and if you create files you will most likely have to delete them from PHP as well.
I suggest that you create your directory structure with your FTP user and keep as little PHP-generated content around as possible because of that.
You can alleviate the symptoms using permissive authorizations (with chmod), but that's generally not a super good idea security-wise.
Comment: I wish I could use your suggestion of creating the files/folders first in ftp but they are for php generated thumbnails.
Comment: @LetterSticker, you can probably have the folder structure, then.
Answer: Use rmdir($thumb_dir); to delete it.
You cannot change your PHP user on a shared server.


ajax url gives 403 using a specific word "Altar " or "altar" other urls works fine

Question: A url I am sending to a php file using ajax as a GET is giving me a 403 error when I use the word "Altar " or "altar " followed by a space.  Its a church site, so of course they are going to use this word.
The code works perfectly fine until I use that word in the parameters.  This for example works perfectly fine, even with the url inside and special chars, and a single quote:
ad2calendar.php?ajax=1&u=testuser&d=2013-11-30&s=1&iurl=altar.jpg&eEvent=%3Ca%20href%3D'someurl.com'%20title%3D%22Phony%20URL%22%20%3EA%20Phony%20URL%3C%2Fa%3E%0ASome%20special%20chars%20!%40%26%5E%25%23%24(%23%40%22%22&notes=test&eTitle=Test&y=2013&m=11
But this gives me a 403 because it contains the word "Altar " with a space.
ad2calendar.php?ajax=1&u=testuser&d=2013-11-30&s=1&iurl=&eEvent=Altar%20&notes=test&eTitle=Test&y=2013&m=11
Any thoughts on why a simple word like this could break the URL causing a 403?
My own troubleshooting has discovered the 403 is from a higher directory than that which the php file exists( the php is in a password protected directory ).  I am thinking this may be due to some character encoding issue as I changed the files to UTF-8 recently but it seems to work fine otherwise.  Tried with a blank .htaccess file, so there is no mod_rewrites, using encodeURIComponent on the form fields.  The script is in no way checking for this character combination and redirecting.
I have php strict error reporting on, and no php errors are thrown, nor javascript errors. The only errors I seem to get are related to the 403 page being displayed in the result div, for the ajax response as the 403 page uses resources not in that directory location.
The code itself is pretty complex, so I cannot really start posting all the bits.  Just looking for some directions to troubleshoot further.  Honestly I am going to put in a hack just for this word soon.
Even stranger I was able to use this word a month or 2 ago, but if I roll back my code to that point the error persists.
From my Raw Access Logs, first contains "Altar" and gives 200, second contains "Altar " with a trailing space and gives 403.
XXX.XXX.XXX.XXX - - [11/Nov/2013:12:35:22 -0500] "GET /ad2calendar.php?ajax=1&u=testuser&d=2013-11-30&s=0&iurl=&eEvent=Altar&notes=&eTitle=&y=2013&m=11 HTTP/1.1" 200 20102 "http://XXXXX/ad2events.php" "Opera/9.80 (Windows NT 6.1; WOW64) Presto/2.12.388 Version/12.16"

XXX.XXX.XXX.XXX - - [11/Nov/2013:12:35:29 -0500] "GET /ad2calendar.php?ajax=1&u=testuser&d=2013-11-30&s=1&iurl=&eEvent=Altar%20&notes=&eTitle=&y=2013&m=11 HTTP/1.1" 403 1098 "http://XXXXX/ad2events.php" "Opera/9.80 (Windows NT 6.1; WOW64) Presto/2.12.388 Version/12.16"

Discovered the text "script" in the angle brackets will also give the 403. Example:

The above gives the 403 error.  This confirms there is some security feature or encode issue which is causing this.
Comment: What error appears in the web server's log? If you're using apache on ubuntu, you can ``tail -f /var/log/apache2/error.log`` while reproducing the error.
Comment: Is your host using any form of SQL Injection protection on this server?  Makes me wonder if something is supposed to be blocking the word alter but is instead blocking altar.
Comment: +1 for having the discipline to be able to test with a previous version of the code.... just saying.
Comment: is it just `altar` that gives a 404? What about `ltar` or, er, `aaltar`?
Comment: "ltar " gives the 404, "aaltar " works, I tried some other variations, it is possible some other odd word causes this, which is my primary concern
Comment: check `mod_rewrite` rules in `.htaccess` or server config file ?
Comment: It *sounds* to me either a `mod_rewrite` rule is looking for and redirecting based on that value, or else the script is..
Comment: There is no mod_rewrite rules at all in the .htaccess.  Should there be one to prevent this behavior?  The site is on shared hosting so the server config, I do not believe, is accessible but is most likely default.  Will look into this a bit further.
Comment: 403 is an access forbidden error, so the clue will most probably be in your apache logs, unless your script is generating the error.
Comment: 404 or 403?  It's not clear whether or not you're getting both, or just the 403 and typo'd it as 404.
Answer: The behavior you're describing sounds like the action of a badly written mod_security rule — possibly one that's trying to prevent injected SQL from containing commands such as ALTER TABLE, but with the crucial word in the rule spelled incorrectly (!). Please contact your web host for details.
Comment: Thanks, this is the only explanation I could come up with as well.  Will discuss this matter with my web host.  I actually went in and set the user permissions for the SQL to allow alter for this user, which should thus allow Alter Table, but maybe not if a higher level on the host itself has this misspelled in a rule.  I will mention, there is another database for a image slide show running on this same site, which allows this word without issue, but is using an entirely different php/sql code.
Comment: Added the raw access log entries for two requests above.  Seems strange one of these would pass a mod_security and one would not and "Alter ", which is the SQL keyword, will pass.
Comment: It occurs to me that the first request doesn't contain a space. Do you get the same result with a word other than "Altar"?
Comment: I am unable to get this to fail, with any other words I have tried, other then noted above, "ltar " with trailing space will fail as well, "tar " succeeds.
Comment: Weird! Like I said, though, talk to your web host. This is almost certainly something they're doing.
Comment: Yes, I agree very weird.  Even if I use a long string of text with the word "Altar " thrown in somewhere, it fails. Example "This is some test words blah blah Altar blah blah blah. Some more text." - fails.
Comment: Since I am on a shared hosting, I was not seeing any mod_security errors, nor did I have access to the settings or even the ability to verify mod_security was running.  Some mod_security rules were disabled on contacting my host and this issue has been checked as resolved.
Comment: In retrospect: Perhaps it wasn't about `ALTAR TABLE` (sic) at all - maybe they were trying to prevent the `tar` command from being passed into a script! Still silly, anyway.


Java type parameterized Class argument

Question: JPA has a method of the following signature:
<T> CriteriaQuery<T> createQuery(Class<T> resultClass);

How do I invoke this method when my resultClass type is, itself, type parameterized?
For example:
public class ResultDto<T> {
...
}

I tried the following but it didn't work:
createQuery(ResultDto<String>.class);

Comment: Can't type this into an IDE right now, but have you tried `> createQuery(ResultDo.class)` ?
Comment: My IDE says "incompatible types".
Answer: There is no Class instance for any specific instantiation of a generic type (e.g. ResultDto<String>, ResultDto<Integer>, ResultDto<MyObject>, ...).
No matter whether the class is generic or not there is always only one Class instance which represents raw version of the class. In your case, it is ResultDto.class.
Comment: I think I understand what you are saying - you are talking about the effect of Type Erasure, where type constraints are applied only at compile time and generic type information is removed at runtime, so only one instance can represent the raw version of the class. But I don't see how that prevents me from differentiating ResultDto and ResultDto, they are different types according to the Java compiler. I'd have to do an unchecked cast in order to get one from the other and make the compiler happy.
Comment: IMO, ultimately we can blame the type-erasure. But immediate reason here is because there is only `ResultDto.class`. If you let the compiler infer the return type by passing `ResultDto.class`, the inference system infers the return type to be `CriteriaQuery`. Which of course isn't what you want. On the other hand, if you want to avoid type inference by doing something like `obj.>createQuery(...)`, then you don't have the argument because there is no `ResultDto.class`. AFAIK, you have two choices, either make the class not generic, or suppress the warnings.
Comment: Actually, given that query results are returned in a List, I can't even cast it from List to List>. So my only choice seems to be not to use generics...
Answer: You can use createQuery(ResultDto.class)
The reason is when you are going to create a object of ResultDto , you will always create it using a type parameter
for eg
 ResultDTo<String> rs = new ResultDTo<String>()
So this type parameter will be considered in the <T> CriteriaQuery<T> createQuery(Class<T> resultClass);
Comment: I know that I can use createQuery(ResultDto.class) provided that I create the dto object as new ResultDto(). It's just that (1) I would prefer to rely on the JDK compile time check, if possible (isn't that the whole point of type parameterization?), and (2) I'd like to avoid having to do an unchecked cast - without it I won't be able to compile. Somewhere along the way the value has to be cast to the expected/correct type.
Comment: You can safely rely on the JDK compile time check. eg `public static  void test(T[] arr){
  for(T t : arr){
   System.out.println(t);
  }
 }`  you can safely call the method using Integer[] or String[] , now if you call using int[] , it will fail at compile time itself.

Java type parameterized Class argument