Zero correlation of all functions of random variables implying independence

Question: Independence between random variables $X$ and $Y$ implies that $\text{Corr}\left(f(X),g(Y)\right)=0$ for arbitrary functions $f(\cdot)$ and $g(\cdot)$ (here is a related thread).
But is the following statement, or a similar one (perhaps more rigorously defined), correct?

If $\text{Corr}\left(f(X),g(Y)\right)=0$ for all possible functions $f(\cdot)$ and $g(\cdot)$, then $X$ and $Y$ are independent.
Comment: I would say all bounded continuous functions rather than all possible functions. For some functions the variance may be infinite, so correlations will not be defined. But for bounded continuous functions that problem doesn't arise and that's a big enough class of functions to get the result.
Comment: See https://stats.stackexchange.com/a/638988/69508
Answer: Using indicator functions of measurable sets like$$f(x)=\mathbb I_A(x)\quad g(x)=\mathbb I_B(x)$$leads to$$\text{cov}(f(X),g(Y))=\mathbb P(X\in A,Y\in B)-\mathbb P(X\in A)\mathbb P(Y\in B)$$therefore implying independence. As shown in the following snapshot of A. Dembo's probability course, proving the result for indicator functions is enough.

This is due to this monotone class theorem:
Comment: (+1) I was thinking of attacking moments, but this is clearly the simplest approach.
Comment: It isn't explicit how these indicator functions account for all functions, but rather appear to be a choice of functions. Can you clarify how this proof meets this general criterion for the hypothesis?
Comment: Excellent, thank you. I think I need to brush up on measure theory, but I get the gist now.
Comment: This theorem of Halmos s incredibly powerful!
Comment: How does this prove the hypothesis? I think there are missing steps.
Answer: @Xi'an gives probably the simplest set of functions $f,\,g$ that will work.  Here's a more general argument:
It is sufficient to show that the characteristic function $E[\exp(itX+iSY)]$ factors into $E[\exp(itX)]E[\exp(iSY)]$, because characteristic functions determine distributions.
Therefore, it is sufficient to show zero correlation

when $f,\,g$ are of the form $f_t(x)=\exp(itx)$ and $f_s(y)=\exp(isy)$
so $\sin(tx)$ and $\cos(sy)$ are also sufficient
by the Weierstrass approximation theorem, the sines and cosines can be approximated by polynomials, which also suffice
more generally, by the Stone-Weierstrass theorem, any other set of continuous functions closed under addition and multiplication, containing the constants, and separating points will also do ['separates points' means for any $x_1$ and $x_2$ you can find $f$ so that $f(x_1)\neq f(x_2)$, and similarly for $y$ and $g$]
the construction of integrals from indicator functions shows you can also use constant functions as @Xi'an does
and, like, wavelets or whatever

It might occasionally be useful to note that you don't have to use the same set of functions for $f$ as for $g$. For example, you could use indicator functions for $f$ and polynomials for $g$ if that somehow made your life easier
Answer: Any continuous random variable can be mapped into a uniform [0,1] random variable using the cumulative distribution function. If the variables are independent, then the joint distribution on the 1x1 square will be the product of the two uniform margins and so uniform too. For the variables to be dependent, the joint distribution is not equal to the product, and therefore not uniform. The 1x1 square has bumps and dips in it. We then apply a permutation of intervals/blocks along each axis to rearrange those bumps along the diagonal and the dips far away from it - like permuting the rows and columns of a matrix with the Cuthill-McKee algorithm. This makes the correlation non-zero. Thus, zero correlation for all functions of continuous random variables implies independence.
Comment: Interesting, thank you!
Comment: Could the downvoter provide a comment?
Answer:
If $\text{Corr}\left(f(X),g(Y)\right)=0$ for all possible functions $f(\cdot)$ and $g(\cdot)$, then $X$ and $Y$ are independent.

In the ref that I have the opposite is affirmed. If $X$ and $Y$ are independent we have that:
$E[f(X)]E[g(Y)]-E[f(X)g(Y)]=0$  (then $corr[f(X),g(Y)]=0$)
for any $f()$ and $g()$.
In words, we have no chance to find dependencies. Indeed if exist, them must be revealed by some functional relations.  See: Econometrics – Verbeek; 5th edition pag 463. But some distributions/moments/functions conditions seems me implicit.
To move in the opposite direction is permitted, so from $\text{Corr}\left(f(X),g(Y)\right)=0$ the independence is implied.
However can be useful to note that the condition $\text{Corr}\left(f(X),g(Y)\right)=0$
imply some restrictions on the distributions/functions/moments. In some cases, this condition can fail. For example if $X$ and $Y$ are independent Cauchy r.vs: $\text{Corr}\left(f(X),g(Y)\right)=0$ not hold, or at lest not for some $f()$ and $g()$. Then, the condition in argument and the independence are not completely equivalent.
Comment: I edited my answer spending more attention on some details.
Comment: The example with Cauchy random variables is helpful.
Comment: Just to clarify: the implication from independence to lack of correlation is not my focus; I am only asking about the case of implication from lack of correlation to independence. Thus I think only your last two paragraphs are really of interest, especially *If we want move in the opposite direction, I fear that with some peculiar distributions and/or transformations some problems can appear. But in general the idea hold*. I think Xi'an's answer addresses your fear, does it not?
Answer: Two variables being dependent means that there is some value(s) of one variable that make some value(s) of the other variable more likely (the general statement is that it changes the probability, but WLOG we can assume that it increases the probability). And if that is the cases, then clearly there is positive correlation between the first variable having the value(s) in question, and the second variable having the value(s) in question. This correlation can be reflected in correlation between functions by taking functions that have different outputs depending on whether the variables take on the value(s) in question.
As a practical matter, this isn't generally a good method of proving independence. Given any countable set of functions, it's possible to construct two dependent variables for which all those functions are uncorrelated. So you have to prove that an uncountable set of functions are uncorrelated, at which point it's probably easier to just prove independence directly.
Comment: This characterization looks like a great way to prove two variables are *not* independent, though.
Comment: Thank you for the answer. Could you perhaps digest it to a more direct answer to my original question?
Comment: Is that second comment true? Since $Q := \{(-\infty, q] : q \in \mathbb Q\}$ is a $\pi$-system that generates the Borel $\sigma$-algebra, if $\mathbf 1_{A}(X)$ is uncorrelated with $\mathbf 1_B(Y)$ for every $A,B \in Q$ then $X \perp Y$, and that's a countable collection of indicators
Answer: Correlation catches only the linear dependence between two variables.
A and B are dependent but uncorrelated if $A = B^2$ for example
Pure independence implies the stochastic independence, which is that the occurrence of one does not affect the occurrence of the other. Similarly, two random variables are independent if the realization of one does not affect the probability distribution of the other (copied from the wiki)
Comment: Thanks for the general definition. How does that answer my question? Can we establish independence between $X$ and $Y$ when we know that $\text{Corr}\left(f(X),g(Y)\right)=0$ for all possible functions $f(\cdot)$ and $g(\cdot)$? The functions are of course not limited to just linear ones.
Comment: I think that if Xi'an's answer is correct, your comment must be wrong. Would you challenge his answer or concede?
Comment: @EmilMirzayev Please don't perpetuate this fallacy about $A,B$ being dependent but uncorrelated if $A=B^2$. We have $Cov(A,B) = E(B^3) - E(B^2)E(B)$ and in general this is not zero. Try an Exponential with parameter $1$, whose moments are $E(B^n) = n!$.
Comment: No we can not. Even though the correlation is zero, variables might be statistically dependent
Comment: @AlecosPapadopoulos Well, if the domain is symmetrical (e.g. [-1.1]), then they will be uncorrelated. But following Xi'an's answer, we can take indicator functions for a nonsymmetric set, revealing nonzero correlation.
Comment: @Acccumulation What we need is that $E(B)$ and $E(B^3)$ are both zero. A sufficient (but not necessary) condition for this is that the density is symmetric around zero. But it is the usual case brought forth as an example.


Problems with If Statement (ASP.NET)

Question:     Dim custEmail As String
    Dim inputEmail As String

    custEmail = dt.Rows(0).Item("email")
    inputEmail = email_add.Text

    if (custEmail.toString() == inputEmail.toString() ){
        label1.Text = custEmail

    }
    End If

This code is giving an error: Compiler Error Message: BC30201: Expression expected.
I just basically want to check if two values are equal but its saying something about expression expected although i've given the expression to evaluate.
Answer: The above is a mix of vb.net and c# syntax.  You can use either in .net with success but not both at the same time.  Get rid of the { and } to stick with vb.
Comment: and add 'Then'... and make double equals single
Comment: @Tahbaza - as Farax is a new member, accurate instructions on rewarding the answer would be good.  There is no checkmark and closing questions on SO is the opposite of showing appreciation. @Farax - since Tahbaza's answer helped you out and proved to be the most correct answer, you can upvote (with the Up arrow above the number) as well as accept as the correct answer by ticking the tick below the number.
Comment: @Michael - "checkmark" == "tick mark" in my parlance, apologies for upsetting your sensibilities.  My comment has now been deleted to avoid any confusion as you are indeed correct that "closing" != accepting.
Comment: @Tahbaza - no problems.  Sorry if it came across harsh, wasn't meaning to offend :)
Comment: Np, I should be more careful in my word choices / happy coding
Answer: Looks like you are mixing C# and VB.Net.  Assuming you are using VB.Net
Replace the '{' with Begin IF and remove the '}'.

Problems with If Statement (ASP.NET)


sort descendingly based on multiple parameters in Java

Question: I have input of multiple strings where I parse each one to fetch certain data and then display them accordingly. The point is I need to sort them accodring to some parameters before displaying them.
To clarify:
String s1 = "a1 5 2014-12-05";
String s2 = "a2 10 2014-12-06";
String s3 = "a3 5 2014-12-04":

After pasring each string, I need to sort them descendingly first according to the second parameter and then according to the date whenever I reach a tie for example.
Output should be:
a2, a1, a3

Any idea how can this be achieved or if I could change the way to a more efficient one?!
Comment: Split strings and compare according to the rule.
Comment: @mic4ael could you clarify more?!
Comment: Create an `Object` (yes, that's what the first `O` in `OO` stands for) that contains three fields: a `String`, an `int` and a `LocalDate`. Then `implements Comparable` and you can use any number of methods to sort a `Collection` of `MyObject`.
Comment: This is exactly what `Comparator`s were designed for.
Answer: You can parse the data and use Collections#sort. Your class can define some natural ordering using Comparable and in case if you want to sort descending then just pass Comparator.reverseOrder() as second arg to Collections#sort  like this
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

public class DateSorter {

    static class Entry implements Comparable<Entry> {
        String id;
        int num;
        Date date;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        public Entry(String id, int num, String date) throws ParseException {
            this.id = id;
            this.num = num;
            this.date = sdf.parse(date);
        }

        @Override
        public int compareTo(Entry o) {
            return date.compareTo(o.date);
        }

        @Override
        public String toString() {
            return id + '\'';
        }
    }

    public static void main(String[] args) throws ParseException {
        String s1 = "a1 5 2014-12-05";
        String s2 = "a2 10 2014-12-06";
        String s3 = "a3 5 2014-12-04";

        String[] split = s1.split(" ");

        List<Entry> entries = new ArrayList<>();
        entries.add(new Entry(split[0], Integer.parseInt(split[1]), split[2]));
        split = s2.split(" ");
        entries.add(new Entry(split[0], Integer.parseInt(split[1]), split[2]));
        split = s3.split(" ");
        entries.add(new Entry(split[0], Integer.parseInt(split[1]), split[2]));

    Collections.sort(entries, new Comparator<Entry>() {
        @Override
        public int compare(Entry o1, Entry o2) {
            return o2.compareTo(o1);
        }
    });

        System.out.println(entries);
    }
}

Output
[a2', a1', a3']

Comment: @omarsafwany this is an entirely different question. Post it as such with all the details and for formatted code. Rather than an illegible comment.
Comment: @omarsafwany java.sql.Timestamp extends java.util.Date so there should not be any problem with sorting. In constructor you can create new Timestamp object like new Timestamp(sdf.parse(date).getTime());
Comment: @omarsafwany I'm not sure you understand what a `Date` or a  `Timestamp` is. Read the documentation rather than make assumptions. And with all future interactions with the Java library pay attention to packages. `Timestamp` is in `java.sql`, you aren't doing anything with SQL so it isn't what you need.
Comment: @omarsafwany you need to update the code , currently you are passing only the date, now you need to pass both date and time string as 3 parameter like this entries.add(new Entry(split[0], Integer.parseInt(split[1]), split[2] + " " + split[3]));
Comment: Nearly there: _I need to sort them descendingly first according to the second parameter and then according to the date_. You need to sort by `id` then by `num` and finally by `date`.
Comment: Does OP want to sort the data twice ? I mean do we need to add   Collections.sort(entries, new Comparator() {
   @Override
   public int compare(Entry o1, Entry o2) {
    return o2.num.compareTo(o1.num);
   }
  });
Comment: @sol4me I know this may sound stupid but I got this error:
The method reverseOrder() is undefined for the type Comparator
Comment: reverseOrder is defined in JDK 8 Which JDK are you using ?
Comment: Given that you wrote the code for JDK8, why aren't you using `LocalDate`, `DateTimeFormatter` and `Comparator.thenComparing` and all their friends?
Comment: @sol4me I am using JDK 1.7
Comment: @sol4me just another question. If I'm using timestamps instead of date, can timestamps parse the date string as shown in your example? I mean would it be possible to sort according to the timestamp?
Comment: @omarsafwany why would you be using `java.sql.Timestamp`? It's for pulling a `TIMESTAMP` time out of a database - it wraps `java.util.Date`.
Comment: @BoristheSpider I want to have full time "yyyy-mm-dd hh:mm:ss" so I thuoght of using TimeStamp
Comment: @BoristheSpider I got the difference now and I changed the timestamp as it's not the on I need. The problem now is that I am getting Unparseable date when I added HH:mm:ss although I followed the exact format.
String s1 = "a1 5 2014-12-03 12:14:40";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
this.date = sdf.parse(date);

Anything wrong noticed here?!
Comment: @BoristheSpider my bad, I apologise.


Why am I unable to make OCSP Stapling work with my nginx, libressl on FreeBSD 12.0-STABLE setup?

Question: After hours of trying I have to get help for my issue.
I am trying to get OCSP stapling to work with my setup, but am not successful in doing so.
Here is my nginx configuration, without any non-relevant bits.
user www www;
worker_processes 5;
error_log /var/log/nginx/error.log;
events {
    worker_connections 1024;
}

http {
include mime.types;
index index.html index.htm;

log_format   main '$remote_addr - $remote_user [$time_local]  $status '
'"$request" $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';

aio on;

sendfile on;
autoindex on;
autoindex_exact_size off;

tcp_nopush on;
tcp_nodelay on;

ignore_invalid_headers on;

keepalive_timeout 70;

gzip on;
gzip_comp_level 5;
gzip_min_length 256;
gzip_proxied any;
gzip_types text/plain text/css application/xml application/javascript application/json font/opentype text/cache-manifest text/x-cross-domain-policy text/xml application/x-javascript;
gzip_vary on;

ssl_certificate fullchain.pem;
ssl_certificate_key server.key;
ssl_trusted_certificate trusted.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256';
ssl_ecdh_curve secp384r1;
ssl_prefer_server_ciphers on;
ssl_dhparam dh4096.pem;
ssl_session_timeout 10m;
ssl_session_cache shared:SSL:10m;
ssl_session_tickets off;
ssl_stapling on;
ssl_stapling_verify on;
resolver 22.214.171.124 184.108.40.206 valid=300s;
resolver_timeout 5s;
add_header Strict-Transport-Security "max-age=63072000";
add_header X-Frame-Options "DENY";
add_header X-Content-Type-Options nosniff;
add_header X-XSS-Protection "1, mode=block";
add_header Content-Security-Policy "upgrade-insecure-requests";
map "$scheme:$http_upgrade_insecure_requests" $shouldUpgrade {
    default 0;
    "http:1" 1;
}

map $http_accept $webp_suffix {
    default "";
    "~*webp" ".webp";
}

expires -1;
add_header Cache-Control "public";

server {
    listen 80;

    listen [::]:80;
    listen 443 ssl http2;

    server_name localhost ;
    access_log /var/log/nginx/access.log main;
    root /www/;
    error_page 404 /404.html;

    if ($shouldUpgrade) {
        return 307 https://$host$request_uri;
    }

}
}

I am getting an error in the log files:
2019/04/30 21:28:07 [error] 28718#100839: OCSP_basic_verify() failed (SSL: error:27FFF076:OCSP routines:CRYPTO_internal:signer certificate not found) while requesting certificate status, responder: ocsp.int-x3.letsencrypt.org, peer: 188.8.131.52:80, certificate: "/usr/local/etc/nginx/fullchain.pem"

No matter what I try to include in the file given to ssl_trusted_certificate, I could not fix this. I tried including the full chain, adding the root CA to it, only the CA, only the intermediary.
Adding the root CA into the fullchain.pem file given to ssl_certificate results in errors on SSL verification websites.
Despite all of that, I am still prompted by a OCSP Stapling not enabled. on https://ssldecoder.org and OCSP response: no response sent when using openssl s_client
Any help would be appreciated. I am using let's encrypt.
Comment: How did you construct `/usr/local/etc/nginx/trusted.pem`?
Comment: @SteffenUllrich The paste I linked contained the contents as described when read by OpenSSL as text. The actual file contents is https://paste.cubox.dev/Dcbav
Comment: @SteffenUllrich I agree that the response is fine when using openssl ocsp directly, this only adds to why I'm confused when nginx fails to staple.
Comment: `ssl_trusted_certificate` should contain all certificates needed to verify the OCSP response. It is not clear which certificates are this in your case since nothing is known about the CA you are using and who is issuing the OCSP responses for this CA.
Comment: @MichaelHampton I have tried both using the contents of fullchain.pem, which have the CA intermediate certificate and mine. I have also tried to add to that the root certificate of the CA, to the end of trusted.pem. The error message still mentions not finding the signer certificate in fullchain.pem, which is used by ssl_certificate only.
Comment: @SteffenUllrich I have specified that I am using https://letsencrypt.org/certificates/. The Root CA is https://letsencrypt.org/certs/isrgrootx1.pem.txt while the intermediate is https://letsencrypt.org/certs/letsencryptauthorityx3.pem.txt, their OCSP seems to be ocsp.int-x3.letsencrypt.org according to the nginx error message.
Comment: Just to make sure, I recreated trusted.pem using `cat server.crt ca.pem isrgrootx1.pem > trusted.pem` This has not helped
Comment: @Cubox: I have no idea what `ca.pem` is and `server.crt` is irrelevant for checking the OCSP response. I've just put your `letsencryptauthorityx3.pem.txt` and `isrgrootx1.pem.txt` into `trusted.pem` since these are the certificates needed to verify the OCSP response. Works perfectly for me as I expected.
Comment: @SteffenUllrich Sorry for not explaining, ca.pem is just letsencryptauthorityx3.pem.txt. I will try with just the root and intermediate certs.
Comment: @SteffenUllrich I have remade trusted.pem, like you described, with it's contents being (can't paste here : https://paste.cubox.dev/m9pJj). Still no luck...
Comment: I have tried to get an OCSP response using openssl directly `openssl ocsp -verify_other fullchain.pem -issuer trusted.pem -cert server.crt -text -url http://ocsp.int-x3.letsencrypt.org -header "Host" "ocsp.int-x3.letsencrypt.org"` and got a response (https://paste.cubox.dev/ZPoZ5)
Comment: @Cubox: there does not seem to be any problem with the response you got.
Comment: *"I have remade trusted.pem, like you described..."* - there are no actual certificates in the file you show. It contains only the textual interpretation of the certificates but not the certificates itself. Please use the contents of the PEM files instead.
Answer: FreeBSD security/libressl was recently upgraded to 2.9.1. OCSP stapling has stopped working in nginx for me as well since the version change in LibreSSL, so I'm assuming there is an underlying issue in the library or nginx' interaction with it.
Edit: In the meantime, Elias Ohm has analyzed this in more detail on the FreeBSD bug tracker. TL;DR: It's an nginx bug, it's using the wrong function to access the certificate chain when using the newer OpenSSL API.
Comment: [LibreSSL has added a fix](https://github.com/libressl-portable/portable/issues/532) in their repository today, not sure when it will land in ports.


How to get current function object in Python?

Question: Is there a way to get the current function I'm in?
I'm looking for the actual function object, not the function name.
    def foo(x,y):
        foo_again = <GET_CURRENT_FUNCTION>
        if foo_again == foo:
            print ("YES they are equal!")

I assume I could do that in Python inspect module, but I can't seem to find it.
EDIT
The reason I want that is I want to print out the arguments to my function. And I can do that with inspect. Like this
   def func(x,y):
       for a in inspect.getfullargspec(func).args:
           print (a, locals()[a])

This works, but I don't want to have to manually write the function name. Instead, I want to do
   def func(x,y):
       for a in inspect.getfullargspec(<GET_CURRENT_FUNCTION>).args:
           print (a, locals()[a])

Comment: What's so bad about writing the function name?
Comment: i updated question
Comment: i plan to copy and paste these 2 lines of code to all functions that i want to see arguments for. so i don't want to change the function name every time i need to do it.
Comment: Wouldn't a decorator be better then? And see http://xyproblem.info/
Answer: from inspect.stack you can get the function's name.
Here is a workaround that might not be optimal but it gives your expected results.
def foo(x,y):
    this_function = inspect.stack()[0].function
    for a in inspect.getfullargspec( eval(this_function) ).args:
        print(a, locals()[a])
    print(this_function)

Then
foo('a','b')
>>>
    x a
    y b
    foo

Answer: One way to accomplish this is by using a decorator.  Here's an example:
def passFunction(func):
    @functools.wraps(func)
    def new_func(*args, **kwargs):
        return func(func,*args, **kwarsgs)
    return new_func

@passFunction
def foo(f, x, y):
    ...

foo(x,y)


how to make a for loop using the dimensions of a matrix

Question: I have a 2-D array that is called dataSet which is 335 x 225. I want to fill a new empty array, called newDataSet, 1-D array that is 1 x 7537. The newDataSet should be filled from the first 7537 data points of dataSet. How can I do this?
I want to use it a for loop like so:
for row in trainingData.shape[0]
    for column in trainingData.shape[1]
    bin_1 = trainingData[:33,:255]

Comment: `7537` or `75375` ?
Comment: 7537. I want to make 10 new arrays that are made up of subsets of the original data. so the first 9 arrays (1-D) would have 7537 data and the last one would have 7542.
Comment: Possible duplicate of [From ND to 1D arrays](https://stackoverflow.com/questions/13730468/from-nd-to-1d-arrays)
Comment: `trainingData.shape[i]` will always be an integer, which is not iterable. If you want to iterate *up to* that integer, use `range(trainingData.shape[i])` for whatever value of `i`
Comment: but I am not getting this: do you want a single array or a list of arrays in the end? A single array could be troublesome because you need some alignment as the data does not fit perfectly.
Answer: You don't need for loops if you use numpy
import numpy as np
dataset = np.random.random((335, 225))

First reshape the dataset in to a 1x(335*225) array and then extract the first 7537 elements out of it
new_array = dataset.reshape(1, 75375)[:,0:7537]

Comment: Great Idea with the reshaping :) But also I dont want to reuse the data points from the original data. In other words, the first array should contain 1-7537, the second would contain 7536 - 15,073...etc. So would `new_array = dataset.reshape(1, 75375)[:,0:7537]` still work?
Comment: Use `arrays_1_to_9 = dataset.ravel()[0:7537*9].reshape((9, 7537))` and `last_array = dataset.ravel()[7537*9:]`. But there should be a more elegant way.
Answer: A one step method to generate your subsets :
subsets=np.split(a.ravel(),range(0,a.size,a.size//10)[1:-1])

In [30]: [len(s) for s in subsets]
Out[30]: [7537, 7537, 7537, 7537, 7537, 7537, 7537, 7537, 7537, 7542]

These are just views, so the data is not copied. It's normally not a problem for training sets.


Classify the fixed point at the origin

Question: Classify the fixed point at the origin for the following system for all real values of the parameter $a$.
$\dot{x}=-y+ax^3$
$\dot{y}=x+ay^3$
The Jacobian of this system incorrectly predicts that the origin is a center; it is actually a spiral if you plot the phase plane for $a\ne0$. Presumably we use polar coordinates to classify the fixed point, but how?
Comment: Remark: not "incorrectly predicts", but "can't be used in this situation"
Comment: To elaborate: whenever linear theory predicts a center, nonlinear terms may say otherwise. This is not the case with sinks, sources or saddles: these are said to be *structurally stable* because they retain their nature even when nonlinear terms are accounted for.
Answer: Hints: Let

$x = r \cos \theta$
$y = r \sin \theta$
$x^2 + y^2 = r^2 \rightarrow x x' + y y' = r r'$

Substitute and solve for $r'$ and $\theta'$
Comment: $\displaystyle \theta' = \frac{xy'-yx'}{r^2} = \frac{x(x + ay^3)-y(-y+ax^3)}{r^2} = \frac{x^2+y^2+axy^3-axy^3}{r^2} = \frac{r^2}{r^2} = 1$. Got it? Also, you can solve for $\theta$ in one of the two formulas above to find the expression I used.
Comment: Needs a TU! + 1
Comment: Thanks for the response. I get $\dot{r}=ar^3(cos^4\theta+sin^4\theta)$. Does this look right? To work out $\dot{\theta}$ should I use $\theta=arctan(y/x)$? This gives me a messy answer.
Comment: I thought $\theta' = 1$ after simplification.
Comment: How do you get this?
Comment: You can derive this equation $\theta' = \dfrac{x y' - y x'}{r^2}$. Substitute and simplify. If you look at $a = -1, a = 0 , a = 1$ and the equations for $r'$ and $\theta'$, you see what is happening and that is the point of the exercise. You can also simplufy $r'$ to make it much cleaner. Regards
Comment: I'm still not getting $\theta'=1$ and unable to simplify $r'$ further. I feel like I'm missing something here? I've been able to use polar coordinates with other systems fine.
Comment: @Amzoti Actually, when you do the multiplication, you get $\frac{x^2+y^2+axy^3-ayx^3}{r^2}$. I am having similar difficulties with using Polar Coordinates here.
Answer: Multiply the first equation by $x$, the second by $y$ and add the two resulting equations.

Classify the fixed point at the origin


Using Both Active Directory Authentication and Individual User Accounts in .NET Core

Question: I've been tasked to create a .NET Core (C# MVC) application that can be authenticated via Active Directory or Individual User Accounts.
There are a myriad of resources on the internet regarding setting up one or the other, and I've created applications with them. But is it possible to do both?
It would seem OAuth allows multiple authentication routes out of the box in .NET Core, but my guess is that Active Directory doesn't work that easily, being configured in IIS and using the operating system to authorize.
If it is not possible to do both - what are my options? I am guessing I would create two separate projects that do the same thing, but with different authentication - but maintaining two projects doesn't seem like a good idea.
Thanks in advance for any advice.
Comment: You might want to think about the Provider pattern then. Define an interface for the account security provider, and then implement that interface twice, once for internal accounts and once for active directory. Maybe even a third time for unit test mocks.
Comment: Which should take precedence? If a username exists in both AD and as an individual account, which system is authoritative for that username?
Comment: @JoelCoehoorn We would deploy it with either AD or individual accounts depending on the client.
Comment: That sounds like exactly what I want - but I am struggling to find a good resource for AD and individual, specifically. This seems to be a close one: https://learn.microsoft.com/en-us/aspnet/core/security/authentication/identity-custom-storage-providers?view=aspnetcore-2.1#reconfigure-app-to-use-a-new-storage-provider
Answer: I've cobbled together some resources, and I decided to create a simple, custom authentication that allows Active Directory and individual user accounts in my database.
First, I added ASP.NET Identity to my existing project. I made the Identity interfaces much more simpler than in the linked answer:
IdentityConfig.cs
public class IdentityConfig
{
    public void Configuration(IAppBuilder app)
    {
        app.CreatePerOwinContext(() => new Entities());
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Authentication/Login"),
        });
    }
}

Following @Sam's answer (yet again) on creating custom authentication/authorization in ASP.NET, I then created a simple Database-First user and role table in the database, not based off of Identity, and created a user manager class:
UserManager.cs
public class UserManager
{
    private Entities db = new Entities();

    public bool IsValid(string username, string password)
    {
        // TODO: salt and hash.
        return db.USER.Any(u => u.USERNAME == username && u.PASSWORD == password);
    }
}

Finally, to complete the custom authentication, I created a dead simple authentication controller. That will check if the user is valid, then create a ClaimIdentity.
AuthenticationController.cs
public class AuthenticationController : Controller
{
    private Entities db = new Entities();

    public ActionResult Login()
    {
        return View();
    }

    public ActionResult Logout()
    {
        HttpContext.GetOwinContext().Authentication.SignOut();
        return RedirectToAction("Index", "Home");
    }

    [HttpPost]
    public ActionResult Login(string username, string password)
    {
        UserManager um = new UserManager();
        bool valid = um.IsValid(username, password);

        if (valid)
        {
            // get user role and enditem
            USER user = db.USER.Where(u => u.USERNAME == username).First();
            string role = db.ROLE.Where(r => r.USERID == user.USERID).FirstOrDefault().ROLENAME;

            // create session
            Claim usernameClaim = new Claim(ClaimTypes.Name, username);
            Claim roleClaim = new Claim(ClaimTypes.Role, role);
            ClaimsIdentity identity = new ClaimsIdentity(
                new[] { usernameClaim, roleClaim }, DefaultAuthenticationTypes.ApplicationCookie
            );

            // auth succeed
            HttpContext.GetOwinContext().Authentication.SignIn(new AuthenticationProperties { IsPersistent = false }, identity);
            return RedirectToAction("Index", "Home");
        }

        // invalid username or password
        ViewBag.error = "Invalid Username";
        return View();
    }
}

This simplicity seems exactly what I want, not carrying the massive bulk that is Identity or ASP.NET membership, and it works great.
Now to answer my original question - how do I also accommodate Active Directory users?
While I abstracted out and greatly simplified my USER and ROLE classes, there will be significant extra data that will be required for a USER (roles, permissions, etc) - and that data will not be in Active Directory - we need to create a USER regardless.
Therefore, all I need is to validate the username and password in Active Directory!
A quick configuration variable can change the control flow in the Login action, and execute this:
bool isValid = false;
if (authConfig == "AD") {
    using(PrincipalContext pc = new PrincipalContext(ContextType.Domain, "US"))
    {
        // validate the credentials
        isValid = pc.ValidateCredentials(username, password);
    }
} else if (authConfig == "Custom") {
    isValid = um.IsValid(username, password);
}
// create claim...

This solution was possible because the only purpose of Active Directory authentication is to verify their user - no additional data was required from AD. Additionally, since we need to specify Role and other data in our custom tables, a custom user record had to be created anyway.
My confusion that spurred the answer was the lack of understanding of how flexible it is to create custom authentication in .NET, without using what they have baked in (like checking the "Individual User Accounts" option when creating a new project).
Other suggestions are welcomed, since this is the extent of my ASP.NET knowledge - but I believe this will work for my application. I hope this helps someone's authentication setup.
Answer: you can work on authentication with the way you thought of or you can turn your focus to picking up IdentityServer4, a fully-featured authentication project for what would suit your needs.
Here's another stackoverflow question that is close to what you're looking for. If you're unfamiliar with how IS4 works, you can create a project based on their templates here;
dotnet new -i "identityserver4.templates::*"

Comment: Thank you for the resource @Nicholas! Although I would prefer not having to use a 3rd party solution, I will consider it.
Comment: @chakeda I'm a fan of not using 3rd party solutions! fret not because IS4 is a hyper supportive library. It's pretty much the first thing someone would think about when it comes to working on a new auth server on .NET Core.


How to calculate the probability of $\Pr(U>t\mid U<Z)$ for two independent exponential random variables $Z$ and $U$

Question: Suppose we have two independent random variables $Z$ and $U$ with exponential probability distributions with two rates $\lambda_z$ and $\lambda_u$, respectively.
Can we write as follows:
$\Pr(U>t\mid U<Z)=\frac{\Pr(U>t \And Z>U)}{\Pr(U<Z)}=\frac{\Pr(t<U<Z)}{\Pr(U<Z)}$
If yes, how to calculate $\Pr(t<U<Z)$?
Answer: Yes, you can write it that way.
$P(t<U<Z)=\int_t^{\infty} \int_u^{\infty} \lambda_u e^{-\lambda_u v}\lambda_z e^{-\lambda_z v}dvdu$ and $P(U<Z)=\int_0^{\infty} \int_u^{\infty} \lambda_u e^{-\lambda_u v}\lambda_z e^{-\lambda_z v}dvdu$.
Comment: Thank you very much, but why $dv$?
Comment: I just used two different variables for integration because you are using subscript $u$ and $z$ in the $\lambda$ parameters and I thought that may cause some confusion.  @OptimizeLife


How can I identify these time series processes? (AR/MA/ARIMA/random walk with drift)

Question: I don't understand how one would identify the stochastic process of the following models, if they are AR or MA or ARIMA etc.

Consider the following models estimated over a sample $t = 1, 2, \dots,T$. In each case $\epsilon_t$ is white noise and $p$
  and $\mu$ are less than one in absolute value.
\begin{align}
 y_{t} &=\alpha+\rho y_{t-1}+\epsilon_{t} \tag1\\
 y_{t} &=\alpha+y_{t-1}+\epsilon_{t} \tag2\\
 y_{t} &=\alpha+\epsilon_{t}+\mu \epsilon_{t-1}\tag3 \\
\Delta y_{t}&=\alpha +\rho \Delta y_{t-1}+\epsilon_{t}+\mu \epsilon_{t-1} \tag4
\end{align}
Comment: Please type your question as text, do not just post a screenshot (see
[here](https://stats.meta.stackexchange.com/a/3176/)). When you retype the question,
add the `[self-study]` tag & read
[its wiki](https://stats.stackexchange.com/tags/self-study/info).
Then tell us what you understand thus far, what you've tried & where you're stuck.
We'll provide hints to help you get unstuck. Please make these changes as just
posting your homework & hoping someone will do it for you is grounds for closing.
Comment: Which econometric text suggesting ECM  (i.e. equation 4 ) is this question from ? or was it classrom notes ? Just curious !
Answer: Compare the models to the definitions.  Using your notation, I will paraphrase Wikipedia articles because these are accessible for further study.
All four models rely on a white noise series of random values $\epsilon_t.$
The Autoregressive (AR) model of order $p$ with parameters $\phi_1, \ldots, \phi_p,$ a "constant" $c$, and white noise $\epsilon_t$ is given by
$$y_t = c + \phi_1 y_{t-1} + \cdots + \phi_p y_{t-p} + \epsilon_t.\tag{AR}$$
"Autoregressive" means each successive value $y_t$ is modeled as a linear combination of immediately preceding values (that is, "regressed" on them).  Comparing this to the options in the question, it is apparent that (1) can be written in this form with $p=1,$ $\alpha=c$, and $\rho=\phi_1.$
The Moving Average (MA) model of order $q$ with parameters $\theta_1, \ldots, \theta_q$ and constant $c$ is given by
$$y_t = c + \epsilon_t + \theta_1\epsilon_{t-1} + \cdots + \theta_q \epsilon_{t-q}.\tag{MA}$$
The expression on the right is a weighted combination--or, through abuse of the term, a weighted "average"--of the immediately preceding white noise terms, whence the term "moving average".  This creates a correlation between $y_t$ and successive values $y_{t+1}, \ldots$ because they share some of the $\epsilon_j$ in their definitions.
It is apparent that (3) is in this form with $q=1,$ $\alpha=c,$ and $\mu=\theta_1.$
The Autoregressive Integrated Moving Average (ARIMA) model of order $(p,d,q)$ combines the AR and MA models with the idea of "differencing" a time series.  (The "Integrated" part undoes the differencing.)  It is combines an AR$(p)$ and MA$(q)$ model for the differenced time series $\Delta y_t = y_t - y_{t-1}.$  ($d$ is the number of times differencing is applied.) The combined "ARMA" model is given by $p, q,$ and coefficients $\phi_1, \ldots, \phi_p;$ $\theta_1,\ldots, \theta_q$ as
$$y_t = \left(\phi_1 y_{t-1} + \cdots + \phi_p y_{t-p}\right)\, +\, \left(\epsilon_t + \theta_1 \epsilon_{t-1} + \cdots + \theta_q \epsilon_{t-q}\right).\tag{ARMA}$$
It is apparent that (4) posits an ARMA model for the differences $\Delta y_t.$  This makes it an ARIMA$(1,1,1)$ model.
Finally, the special case where each successive value $y_t$ is obtained by displacing the preceding value $y_{t-1}$ randomly by a zero-mean value $\delta_t$ is known as a "random walk."  When this white noise term $\delta_t$ is replaced by a random displacement with nonzero mean $\alpha,$ we have a "random walk with drift."  An alternative way to express this is to write $\delta_t = \alpha + \epsilon_t$ where now the random term $\epsilon_t$ has zero mean, whence model (2)
$$y_t = \alpha + y_{t-1} + \epsilon_t\tag{RW}$$
is a random walk with drift.  (It is also clear that it is a special case of an AR$(1)$ model with $\phi_1=1,$ but since the problem specifies that $|\phi_1| \lt 1,$ it rules out this characterization.)

Although we do not have data, we can simulate such models by choosing appropriate starting values at time $t=0$ and generating subsequent values as prescribed by each one.  I thought it might be helpful to see such simulations. Here is an example using the R code below.  All four plots use exactly the same white noise series. You may modify the parameters in that code to see other examples of these models.
Because it is useful to see what an unusual value, or "impulse," does to these models, I have modified one of the noise values to make it unusually large.  The time of modification is marked by a vertical red line in each plot.

#
# Specify data length and parameter values.
#
n <- 192      # Series length, including initial value
alpha <- -0.1
rho <- 0.9
mu <- -0.9
y.0 <- 0      # Initial value of y
dy.0 <- 0     # Initial value of the first difference of y (ARIMA only)
#
# Generate the random terms.
#
set.seed(26) # 17 gives qualitatively unusual plots
eps <- rnorm(n-1)
eps[floor(n/2)] <- 10 # Show what an "impulse" does
#
# Generate time series.
#
y.AR <- Reduce(function(y, e) alpha + rho*y + e, eps, init=y.0, accumulate=TRUE)

y.RW <- Reduce(function(y, e) alpha + y + e, eps, init=y.0, accumulate=TRUE)

e.MA <- eps + mu*c(0, eps[-(n-1)])
y.MA <- alpha + c(y.0, e.MA)

dy <- Reduce(function(y, e) alpha + rho*y + e, e.MA[-(n-1)], init=dy.0, accumulate=TRUE)
y.ARIMA <- cumsum(c(y.0, dy))
#
# Plot them.
#
models <- list(Autoregressive=y.AR,
               `Random walk`=y.RW,
               `Moving average`=y.MA,
               ARIMA=y.ARIMA)
par(mfrow=c(2,2))
for (s in names(models)) {
  y <- ts(models[[s]])
  plot(y, main=s)
  abline(v=floor(n/2), col="#e0000080", lwd=2)
}
par(mfrow=c(1,1))

Comment: +1. Excellent answer.
Answer: Try all 4 and select the one with the smallest error sum of squares given that all coefficients are statistically significant.
Comment: Answering this *theoretical* question about *models* requires no data at all, nor will it benefit from using data.
Comment: Apply the definitions.
Comment: If data is not required then please answer the question.
Comment: -1. The models have different degrees of freedom, so in-sample error will definitely tend to overfit.
Comment: you are right if there are insignificant coefficients. You are wrong if they are significant as I required.
Comment: I await all non-data oriented answers to this question .... from any and all as to how "one would identify"  . Can I offer a bounty on this question ?


Add PHP Echo to End of WordPress Titles

Question: Editing my theme to place a facebook icon immediately to the right of my page titles.
With the old icon (HTML) the following code worked and the icon was placed beside the title:

<?php _e( 'Nothing Found', 'catch-adaptive' ); ?>Facebook

Now I am trying to use the php code given to me by a plugin:
<?php echo DISPLAY_ULTIMATE_PLUS();?>

I've done this:

<?php the_title(); echo DISPLAY_ULTIMATE_PLUS();?>

The problem is that the echo is displaying the icon below the page title instead right beside it.
How do I position the icon to the right of the title using this plugin's PHP code?
You can view the live site with the new misplaced icon at http://healthylifeadvisors.com/
Answer: See if this works;

<?php the_title(); ?>

<?php echo DISPLAY_ULTIMATE_PLUS(); ?>

Obviously if you can easily edit the CSS files, you could add the following statements (instead of putting them inline in the HTML), like so;
.entry-title {
     float: left;
}
.entry-header > div {
     display: inline-block;
}

Add PHP Echo to End of WordPress Titles


How to use puppet-apache mod (v8.3.0) with hiera?

Question: Queston: Using the roles & profiles method, is it possible to use 'puppetlabs-apache', '8.3.0' with a hiera lookup?
Context:

I am using mod 'puppetlabs-apache', '8.3.0' to configure an apache server. I have a large number of apache re-write rules for various sites.

Each site is configured hiera, e.g hiera.yaml:
 paths:
    - site/%{::site}.yaml
    - role/%{::role}.yaml

where a webapp.pp role installs & configures apache

it would be nice to lookup apache config in a site-dependent fashion, but can't find any documentation that helps

Notes

I have found a similar question here, but don't think that covers my particular use-case
If hiera is unavailable for this module I could perform some logic in webapp.pp, e.g. something like this: If ($facts['site'] == 'SITE-A') {outline rewrites for SITE-A}
however, this approach feels rather messy
Answer: Ok so just in case anyone benefits, the solution was really straightforward and shows my puppet noob status.
Solution:
Looking at the docs you'll see the majority of data types are arrays, take the following example:
  apache::vhost { 'aliases.example.com':
      serveraliases => [
        'aliases.example.org',
        'aliases.example.net',
      ],
      port          => 80,
      docroot       => '/var/www/aliases',
    }

here serveraliases is an array. So you can simply lookup an array through hiera:
        class profiles::apache::secure_vhost(
            # Hiera lookup
            Array $site_serveraliases    = lookup('apache_site_serveraliases') )
            {
            apache::vhost { 'aliases.example.com':
            serveraliases => $site_serveraliases,
            port          => 80,
            docroot       => '/var/www/aliases',
            }
           )

Where $apache_site_serveraliases is a yaml array that varies between sites, e.g.:
apache_site_serveraliases:
  - paris.site.name
  - london.site.name
  - nyc.site.name

This way you can lookup apache_site_serveraliases in a site-dependent fashion.


Erro em utilizar ViewBag no DropDownListFor ASP NET MVC

Question: Tenho um DropDown que lista as categorias do meu sistema, mais quando submeto o formulário sem escolher uma categoria, ele da um erro de servidor dizendo que o Valor não pode ser nulo.
Coloquei uma validação com o ValidationMessageFor, mais mesmo assim não funciona e da erro. Se tirar meu DropDown ele valida os outros campos, inclusive um outro DropDown q tenho no mesmo formulário, mais que não utiliza ViewBag.
Se alguém puder me ajudar..
Segue Controller:
public ActionResult Adicionar()
    {
        var cookie = DinheiroControlado.Repositorios.RepositoriosUsuarios.VerificaSeOUsuarioEstaLogado();
        ViewBag.teste = cookie.IDUsuario;

        ViewBag.Categoriaslist = db.Categorias.ToList();

        var lista = new List<Categorias>();
        lista = db.Categorias.ToList();

        return View();
    }

    [HttpPost]
    public ActionResult Adicionar(Movimentacoes movimentacoes)
    {
        var cookie = DinheiroControlado.Repositorios.RepositoriosUsuarios.VerificaSeOUsuarioEstaLogado();

        movimentacoes.IDUsuario = cookie.IDUsuario;
        var contador = movimentacoes.Parcelas;
        if (contador > 0)
        {
            for (int i = 0; i < contador; i++)
            {
                if (ModelState.IsValid)
                {
                    if (i == 0)
                    {
                        db.Movimentacoes.Add(movimentacoes);
                        db.SaveChanges();
                    }
                    else
                    {
                        var data = movimentacoes.Data.Day + "/" + (movimentacoes.Data.Month + 1) + "/" + movimentacoes.Data.Year;
                        movimentacoes.Data = Convert.ToDateTime(data);
                        movimentacoes.Parcelas = movimentacoes.Parcelas - 1;
                        db.Movimentacoes.Add(movimentacoes);
                        db.SaveChanges();
                    }

                }
            }
            return RedirectToAction("Index");
        }
        else
        {
            if (ModelState.IsValid)
            {
                db.Movimentacoes.Add(movimentacoes);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(movimentacoes);
        }

        return View(movimentacoes);
    }

Segue View:
@model DinheiroControlado.Models.Movimentacoes
@{
   ViewBag.Title = "Adicionar";
   Layout = "~/Views/Layout2.cshtml";
 }

Movimentações

Lance suas despesas e suas receitas de maneira fácil e rápida!

Home

Movimentações

     @using (Html.BeginForm()) {
     @Html.AntiForgeryToken()
     @Html.ValidationSummary(true)

    <fieldset class="registration-form">

            <legend>Movimentacoes</legend>
            @Html.RadioButtonFor(x => x.ReceitaDespesa, "DESPESA") Despesa

            @Html.RadioButtonFor(x => x.ReceitaDespesa, "RECEITA") Receita

            @Html.ValidationMessageFor(model => model.ReceitaDespesa)

            @Html.TextBoxFor(model => model.Data, "", new { @class = "form-control", @placeholder = "Data", @id = "datepicker"})
            @Html.ValidationMessageFor(model => model.Data)

            @Html.TextBoxFor(model => model.Descricao, "", new { @class = "form-control", @placeholder = "Descrição" })
            @Html.ValidationMessageFor(model => model.Descricao)

            @Html.TextBoxFor(model => model.Valor, "{0:C2}", new { @class = "form-control", @placeholder = "Valor"})
            @Html.ValidationMessageFor(model => model.Valor)

            @Html.TextBoxFor(model => model.Parcelas, "", new { @class = "form-control", @placeholder = "Parcelas", @type = "number", @mim = "0", @max = "400"  })

            @Html.DropDownListFor(model => model.Mensal, new List<SelectListItem> { new SelectListItem { Value = "0" , Text = "SIM" }, new SelectListItem { Value = "1" , Text = "NÃO" } }, "Mensal", new { @class="form-control"} )

            @Html.DropDownListFor(model => model.IDCategoria, new SelectList(ViewBag.Categoriaslist, "IDCategoria", "SubCategoria"), "Categoria", htmlAttributes: new { @class = "form-control"})
            @Html.ValidationMessageFor(model => model.IDCategoria)

            <input type="submit" value="Cadastrar" class="btn btn-primary"/>

            Retornar

    </fieldset>

    }

Segue Erro:
Erro de Servidor no Aplicativo '/'.
Valor não pode ser nulo.
Nome do parâmetro: items
Descrição: Ocorreu uma exceção sem tratamento durante a execução da atual solicitação da Web. Examine o rastreamento de pilha para obter mais informações sobre o erro e onde foi originado no código.

Detalhes da Exceção: System.ArgumentNullException: Valor não pode ser nulo.
Nome do parâmetro: items

Erro de Origem:

Linha 67:
Linha 68:

Linha 69:                 @Html.DropDownListFor(model => model.IDCategoria, new SelectList(ViewBag.Categoriaslist, "IDCategoria", "SubCategoria"), "Categoria", htmlAttributes: new { @class = "form-control"})
Linha 70:                 @Html.ValidationMessageFor(model => model.IDCategoria)
Linha 71:

Arquivo de Origem: c:\TCC\C#\DinheiroControlado\DinheiroControlado\Views\Movimentacao\Adicionar.cshtml    Linha: 69

Rastreamento de Pilha:

[ArgumentNullException: Valor não pode ser nulo.
Nome do parâmetro: items]
   System.Web.Mvc.MultiSelectList..ctor(IEnumerable items, String dataValueField, String dataTextField, IEnumerable selectedValues) +102
   CallSite.Target(Closure , CallSite , Type , Object , String , String ) +155
   System.Dynamic.UpdateDelegates.UpdateAndExecute4(CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3) +738
   CallSite.Target(Closure , CallSite , Type , Object , String , String ) +309
   ASP._Page_Views_Movimentacao_Adicionar_cshtml.Execute() in c:\TCC\C#\DinheiroControlado\DinheiroControlado\Views\Movimentacao\Adicionar.cshtml:69
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +197
   System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +103
   System.Web.WebPages.StartPage.RunPage() +17
   System.Web.WebPages.StartPage.ExecutePageHierarchy() +64
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +78
   System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +235
   System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +107
   System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +291
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13
   System.Web.Mvc.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17() +23
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +245
   System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() +22
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +245
   System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() +22
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +176
   System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +75
   System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +99
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +50
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
   System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +14
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +16
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +50
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +36
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +16
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +50
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
   System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +25
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +16
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +50
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9723757
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

Comment: Pode ser que o modelState não esteja válido e com isso retorna pra view,  sem preencher a ViewBag.Categoriaslist de acordo com o seu código. Tente retornar ViewBag.Categoriaslist preenchida novamente se o ModelState não estiver válido.
Comment: Janderson, deu certo usar sua alternativa, resolveu meu problema cara, muito obrigado! Abraço.
Comment: Blz, coloquei como resposta ai você marca como certa.
Answer: Pode ser que o modelState não esteja válido e com isso retorna pra view, sem preencher a ViewBag.Categoriaslist de acordo com o seu código. Tente retornar ViewBag.Categoriaslist preenchida novamente se o ModelState não estiver válido.


How to use a StateListDrawable at runtime?

Question: I have a problem with some code. I want to create a ColorPicker DialogFragment. At the moment I use a GridView and a custom BaseAdapter to show some color shapes. For each color I use a round ShapeDrawable. To set the color of the default state, I use the following code:
getView() of my "ColorAdapter"
ImageView imageView;
if (convertView == null) {
    imageView = new ImageView(ctx);
    imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
    imageView.setPadding(8, 8, 8, 8);
} else {
    imageView = (ImageView) convertView;
}

Drawable drawable = ctx.getResources().getDrawable(R.drawable.color_item);
imageView.setBackground(drawable);

StateListDrawable states = (StateListDrawable) imageView.getBackground();

GradientDrawable shape = (GradientDrawable) states.getCurrent();
shape.setColor(colors[i]);

return imageView;

That works fine for me.
But I want to change the color of an icon, when it is pressed. So I use a StateListDrawable.
<selector xmlns:android="http://schemas.android.com/apk/res/android"
     android:constantSize="true" >

     <item
          android:state_pressed="true"
          android:drawable="@drawable/circle" />
     <item
          android:drawable="@drawable/circle" />

</selector>

But, because I have different colors for each entry in the GridView, I have to change the color of the state at runtime.
As you can see I use the same drawable resource for both states. Maybe I can set the color of one state, as I do it with states.getCurrent()?
I have also tried to use a ColorFilter to decrease the brightness level. But when I try to do that, the ImageView is always black, when it`s pressed.
Does anybody know how to do that?
Answer: Ok, I found a solution. I use a LayerDrawable with two layers, the first one contains my shape, the second one a StateListDrawable. This StateListDrawable contains one empty shape for default state and one grey shape with lower alpha value. So now, when I press my color circle, the grey shape is put over my color shape.


Setting up multilingual nodes

Question: I am trying to set up a D8 (8.7.9 to be precise) multilingual site and hitting some weird bug.
I have a node type basic page consisting of the title field and a body text field.
Initially I create the page in German (title: "test page de" / content "test content de"), then click Translate to add an english version, save it. So far, so good - the german page pops up at /de/node/12, the english one at /en/node/12, the language switcher works fine.
Then, I edit the German page to say "test page de-1"/"test content de-1", and submit. The German page shows the proper content, as does the English one, but now, when I edit the English page, I suddenly get the title set to "test page de-1" and the body to "test content de-1". What is going on here?
Comment: Go to `/admin/config/regional/content-language` and make sure that title and body field checked as translatable.
Comment: They are marked as such and were when creating the nodes - and the initial translation did work. Only the first edit of a translated page is where the issue appears.
Answer: Found the issue: I had the language detection under /admin/config/regional/language/detection messed up - content language detection was identical to UI language detection (which was User account first, URL second). Used URL only for content language detection and now it works.

Setting up multilingual nodes


Are JAR files in WebContent/WEB-INF/lib available to Java design elements in Domino Designer?

Question: When using Domino Designer 8.5.3, I have a bunch of custom classes added using the Java design element. I want to use a 3rd party JAR in my custom classes in the same way you would when using external JARs in xPages SSJS, via Package Explorer:
WebContent-->WEB-INF-->lib
However my custom classes aren't picking the JAR up.
Is this a known limitation or have I got my configuration screwed up somewhere?
Comment: Do you mean Agents? If so, no it can't use them.
Comment: They aren't being picked up in Designer or at runtime?  You can do this.  I have done it from managed beans.
Comment: Russell, they aren't being picked up in Designer. So I'm just getting "...cannot be resolved" errors when saving.
Answer: They are after you do:
Project -> Properties -> Java Build Path -> Libraries -> Add JARS...
update:
Frantisek Kossuth tells us about a nice shortcut in his comment:

in Package Explorer view (Java perspective, or add this view to
  XPages/Domino Designer perspective), simply right click JAR file and
  use "Build Path/Add to Build Path" menu
Comment: If you are in Package Explorer view (Java perspective, or add this view to XPages/Domino Designer perspective), simply right click JAR file and use "Build Path/Add to Build Path" menu.
Comment: Hi Paul. Yes that solves the issue of the Java class picking up the JAR in Designer. However when the code then runs via the xpage through the browser, a NoClassDefFoundError is thrown.
Comment: I often have to clean the project or rebuild when that kind of errors appear.
Comment: Yes that was my thinking too so have done a clean and a rebuild but still no luck.
Comment: Some suggestions here: http://lotusandjava.blogspot.fi/2012/10/xpage-javalangnoclassdeffounderror.html
Comment: Thanks Panu. I created a fresh NSF and tried what you suggested which then worked fine. Led me to think there must be an issue with the NSF I was working on. Removed my replica and pulled a fresh one. Tried what you suggested and it worked. Frustrating! Thanks for your help.
Comment: If you use these jar files often it would best to add them to the jvm/ext directory on your server directly. Because adding Jar files to a notes designer increases build times enormously for some reason.
Answer: I had a similar problem (Accessing methods from imported jars in managed beans). It seems you need to import them in your machine/server's file system.


Server 2008 - Search for Files and Delete.. very slow!

Question: Windows Server 2008 R2.  Old ish server (4 cores, 2GB RAM) fairly average disks running no raid.
I've used windows F, then searched for .svn files
Selected all, and deleting them.  631 files and 220MB.  It is going to take about 45mins to delete!!
Problem:  How to delete files quickly?
No antivirus or windows serach service running.  Out of the box install of 2008R2.  No other users on the system.  Using terminal services to admin onto the box as a development machine.
Cheers
Dave
Comment: did it really take 45 minutes to complete, or did you cancel the operation?
Comment: disks may have bad blocks. Any else is slow ? Or only file deletion? Raid is software raid or there is hardware raid? If hardware raid, is it with BBWC? what type of disks You have? In event log isn't anything aboud disks?
Comment: Good thoughts... a few years ago so no idea!!
Answer: Do you delete or shift-delete? If you delete to recycle bin it takes longer. Try shift-deleting. Plus: check whether recycle bin is full, if so it takes even longer deleting old files from bin while deleting the .svn folders.
Answer: A script might be a faster way to accomplish this, especially if you're going to do this multiple times.
for /f "tokens=* delims=" %%i in ('dir /s /b /a:d *.svn') do (
 del /q "%%i"
)
Comment: or from the root: del *.svn /s


Observable.fromCallable() method inside not getting called

Question: This is how i'm using the Observable.fromCallable(). In other classes its working fine, but not in some of the classes. Any help would be appreciated.
Observable
.fromCallable(() ->
    getWorkTypeId(tem.getId(), tem.getTypeId())
    .flatMap(oldEntities ->
        replaceTempAuth(tem.getId(), tem.getTypeId(),
           getTemes(tem, oldEntities), oldEntities
        )
    )
    .flatMap(deletedEntities ->
        deleteAllWithId(deletedEntities.stream()
                       .map(TempEntity::getTemId)
                       .collect(Collectors.toList()), tem.getId())
    )
);

Here replaceTempAuth method and deleteAllWithId is not getting called.
Comment: Just add .subscribe()
Comment: You return an `Observable` which then needs to be subscribed by something. Try `Observable.defer` instead of `fromCallable`.
Comment: Even I tried with defer, but still the result is same. @akarnokd
Answer: Got the answer from @kristyWelsh
Added .subscribe() works perfectly.


Evaluating the model stability using bootstrapping

Question: I need help with the following.
Using our alternate data for external clients, we have built a model for identifying fraudulent customers (classification).
we used the auto-ml package to arrive at the best model and gave the results back by scoring the client's holdout data that was without the target.
Now, the client wants us to check on model stability by performing 50 bootstrapping and we are not sure how to benchmark the stability after the bootstrapping.
Any guidance on the same would be appreciated.
Note : the client is from a banking institution.
Answer: Bootstrapping involves randomly resampling a dataset with replacement to generate multiple bootstrap samples. These samples can be used to estimate the sampling distribution of a statistic or to evaluate the stability of a model.
Here are some general steps you can follow to evaluate the stability of your model using bootstrapping:

Randomly sample your data with replacement to create multiple bootstrap samples.
For each bootstrap sample, fit your model and evaluate its performance on a validation set or using cross-validation.
Calculate a performance metric for each bootstrap sample.
Examine the distribution of the performance metric across the bootstrap. If the distribution is narrow and symmetric, it indicates that the model is stable. If the distribution is wide or skewed, it indicates that the model is unstable.
Optionally, you can calculate confidence intervals for the performance metric using the bootstrap samples. This will give you an estimate of the range of values within which the true population parameter is likely to fall.


How do I develop a formula to find the height of a male using his femur?

Question: I'm a grade eleven math student and I need a formula to find the height of a 15/16 year old male subject using only the length of his femur. I'm very confused on how to do this, please help, it's for a very important assignment!
Also, I would prefer it in a polynomial function format but if not I can work with that.
Thanks :)
Answer: HINT
This website makes a claim that

In an adult, the femur is said to be approximately a quarter of a
  person's height.

So given the length $x$ of the femur, how would you find the height of the entire person?
Answer: Maybe this is a statistics exercise.  You measure the hight and femur length in a number of males, then plot the data in 2D.  Perhaps you can fit a straight line to the plot.


Prove that critical damping converges fastest to equilibrium postion.

Question: I have just read this PDF from ocw.mit.edu.
How to prove that critical damping gives the fastest return to the equilibrium position?
I thought of proving that it converges faster than 1) the overdamped case & 2) the underdamped case. The overdamped case seems to be conceptually (with the two roots) clear but not how to prove it under all initial conditions. I don't know how to start with the underdamped case since the exponent is the same as in the critical case.
How to prove that the assumption is true under all initial conditions? I don't really know how to deal with the $(c_1+c_2t)$, especially the $t$, in the critical damping solution $$x=(c_1+c_2t)e^{-bt/2m}$$
I would appreciate any help.
Comment: The second answer is just plain wrong. I have two issues with Jeffrey Rolland's answer: 1. It is not clear why you are taking the limit at t tends to 0? Why are you comparing the values of the positions initially? After all they are not helpful in determining which falls to equilibrium position faster. 2. I noticed you used l'hopital's rule in differentiating. This is just not valid. You can only apply l'hopital's when it's in the case of 0/0 or infinity/infinity, which is not the case when you plug the value t = 0 in. Both of these issues are solved however if you instead take the limit as t
Answer: You have simply the General solution of the differential equation; this is given in dependence of two constants $c_1,c_2$ and holds for all initial condition. For example the solution of the critical damped System is:
$(c_1+c_2t)e^{-bt/(2m)}$.
This holds for every initial conditions (requiring that the System is damped critically); any initial condition can be computed with this equation (one has only to adjust $c_1,c_2$). The $t$ can be understood as the time elapsed after the System Begins to oscillate. From the duration of the oscillation $T$ you can compute the ratios $\frac{x(t+T)}{x(t)}$ and look how small These ratios are to analyze how fast the System tends to Equilibrium.
The factor $(c_1+c_2t)$ arises as the most General solution of the critically damped oscillation equation.
Answer: In the overdampened case, if we set $\lambda = \frac{b}{2m}$, $\omega_0 = \sqrt\frac{k}{m}$, and $a = \sqrt{\lambda^2 - \omega_0^2}$, then we have
$\lim\limits_{t \to \infty} \frac{(c_1 + c_2t)e^{-\lambda t}}{c_3e^{-(\lambda + a)t} + c_3e^{-(\lambda - a)t}}$
$= \lim\limits_{t \to \infty} \frac{(c_1 + c_2t)}{c_3e^{-at} + c_3e^{+at}}$
$\stackrel{\text{L'H}}{=} \lim\limits_{t \to \infty} \frac{c_2}{-ac_3e^{-at} + ac_3e^{+at}}$
$= 0$
so the critically-dampened case goes to the equilibrium position faster than any of the overdampened cases.
In the underdamped case, the mass actually reaches the equilibrium position in a finite amount of time, whereas in the overdampened case, the mass never quite reaches the equilibrium position in finite time.
Comment: If $-\frac{c_1}{c_2} < 0$, the mass never reaches the equilibrium position in a finite amount of (forward) time; I suppose this is what I meant, thinking about your comment ...? Certainly, after that amount of time, if $-\frac{c_1}{c_2} > 0$, the mass then proceeds back towards the equilibrium position, taking forever to do so, and is always closer to the equilibrium position than any of the overdampened cases, as well, I suppose.
Comment: What do you mean the mass never reaches equilibrium in finite amount of time?
In the critically damped case, the general solution is $x(t)=c_1e^{rt} + c_2te^{rt}$ which has root $t=-\frac{c_1}{c_2}$ which is finite... But I definitely see that the graph is asymptotic... where am I going wrong?


How to store all rows of a column name returned as a MySQL query result in a string array

Question: I want to store all rows of a column name returned as a MySQL query result in a string array. I am new to PHP. I have retrieved the rows but how do I store all rows of a column in an array?
I mean how to iterate the counter of rows and store the column in an array? Or is there any direct function/method call? Please see my code below and its possible ways of storing in an array:
$dbhost = 'localhost';
$dbuser = 'user';
$dbpass = 'password';

$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to mysql');
$dbname = 'users';
mysql_select_db($dbname);

$result = mysql_query("SELECT users.email FROM users");

//  AND THEN FINALLY STORING IN A STRING ARRAY:

$array = $result;

//  OR SOMETHING LIKE:

Store($array, $result);

//  OR SOMETHING LIKE:

for(int i = 0; i < $result.Rows.Count; i++)
{
    if (null != $row[0])
    {
        $array[i] = $result[i];
    }
}

//  OR SOMETHING LIKE:

while($null != result.read())
{
    $array.Add($result.Read());
}

Comment: http://www.php.net/manual/en/mysqli-stmt.get-result.php
Comment: Please, don't use `mysql_*` functions to write new code. They are no longer maintained and the community has begun [deprecation process](http://goo.gl/q0gwD). See the [red box](http://goo.gl/OWwr2)? Instead you should learn about [prepared statements](http://goo.gl/orrj0) and use either [PDO](http://goo.gl/TD3xh) or [MySQLi](http://php.net/mysqli). If you can't decide which, [this article](http://goo.gl/YXyWL) will help you. If you pick PDO, [here is good tutorial](http://goo.gl/b2ATO). Also see [Why shouldn't I use mysql functions in PHP?](http://goo.gl/J5jAo)
Answer: This is how you can do it
$rec = mysqli_query("SELECT users.email FROM users");
$data   =   array();
$i=0;
while($row = mysql_fetch_assoc($rec)){
    $data[$i]['column1']    =   $row['column1_from_table'];
    $data[$i]['column2']    =   $row['column2_from_table'];
    $data[$i]['column3']    =   $row['column3_from_table'];
}

Answer: MySQL Fetch Array
$result = mysql_query("SELECT users.email FROM users");

while($row = mysql_fetch_array($result)){
    $array[] = $row;
}

This will return an array of associated arrays. The $row will contain the index of the column name along with integer index.
For example:
echo $row['email'];
//or
echo $row[0];

In the end you can get the first row by:
$array[0]['email']; //or $array[0][0];

NOTICE: Do not use MySQL_* for it has been deprecated as of PHP 5.5. Use MySQLi_* or PDO instead.


How to correctly convert Year-month to Year-quarter

Question: I am trying to convert a pandas dataframe containing date in YYYYMM format to YYYYQ format as below
import pandas as pd
dat = pd.DataFrame({'date' : ['200612']})
pd.PeriodIndex(pd.to_datetime(dat.date), freq='Q')

However this generates output as 2012Q2, whereas correct output should be 2006Q4
What is the right way to get correct Quarter?
Answer: Explicitly specific the input format:
dat = pd.DataFrame({'date' : ['200612']})
pd.PeriodIndex(pd.to_datetime(dat.date, format='%Y%m'), freq='Q')

Output:
PeriodIndex(['2006Q4'], dtype='period[Q-DEC]', name='date')


Config split settings file generated into split directory

Question: Drupal 8.7
I have a multisite split. The config_split.config_split.<sitename>.yml files are supposed to go into the config/default directory. For some reason when updating a split on one of my sites, instead of updating the existing file in that location, it creates a new file in the config/sitename directory. It only does it on this one site. When I compare the newly generated file to the one for that site in the default directory, only the new changes are different. The rest is the same.
Answer: Have you checked the $config_directories array in the settings.php/settings.local.php files.
It might be a good idea to explicitly set it via config as per https://www.drupal.org/docs/8/configuration-management/changing-the-storage-location-of-the-sync-directory:
$config_directories[CONFIG_SYNC_DIRECTORY] = '../config/sync';

Answer: It turns out that this was caused by the actual config split config item being listed in the graylist of the file... So, in config/default/config_split.config_split.www.yml was the entry for config_split.config_split.www in the graylist which then made them "different" and a new file would be created (if we had deleted it) or updated in the config/default/www directory. Since that entry was removed, it has behaved as it should.


What's the matter with IntelliJ's Groovy console?

Question: When I try to use the groovy console it just doesn't seem to recognize and understand the previous stements entered. And code completion does not work either. Below is a VERY simple example that fails. Creating a list and trying to add an integer to that list. The created list isn't found!
> def list = []
[]
> list.add(10)
groovy.lang.MissingPropertyException: No such property: list for class: ideaGroovyConsole
Possible solutions: class
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:50)
at org.codehaus.groovy.runtime.callsite.PogoGetPropertySite.getProperty(PogoGetPropertySite.java:49)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGroovyObjectGetProperty(AbstractCallSite.java:231)
at ideaGroovyConsole.run(ideaGroovyConsole.groovy:1)
at groovy.lang.GroovyShell.runScriptOrMainOrTestOrRunnable(GroovyShell.java:257)
at groovy.lang.GroovyShell.run(GroovyShell.java:481)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSite.invoke(PogoMetaMethodSite.java:231)
at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.call(PogoMetaMethodSite.java:64)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:120)
at console.run(console.txt:25)
at groovy.ui.GroovyMain.processReader(GroovyMain.java:563)
at groovy.ui.GroovyMain.processFiles(GroovyMain.java:473)
at groovy.ui.GroovyMain.run(GroovyMain.java:373)
at groovy.ui.GroovyMain.process(GroovyMain.java:361)
at groovy.ui.GroovyMain.processArgs(GroovyMain.java:120)
at groovy.ui.GroovyMain.main(GroovyMain.java:100)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.codehaus.groovy.tools.GroovyStarter.rootLoader(GroovyStarter.java:106)
at org.codehaus.groovy.tools.GroovyStarter.main(GroovyStarter.java:128)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.intellij.rt.execution.CommandLineWrapper.main(CommandLineWrapper.java:121

Answer: Don't def and you should be good.
> list = []
[]
> list.add(10)

The behaviour is more like groovyShell than groovyConsole.
Perhaps this link explains why: http://groovy-lang.org/groovysh.html#GroovyShell-Variables
Comment: code completion works if you do something very tedious: type cast.

list = (java.util.ArrayList) list;
list. <- code completion will pop up
Comment: Thanks! That worked, but one problem remains and that is that intellij's code completion doesn't work, ie it doesn't recognize the list variable.
Comment: url above is now http://groovy-lang.org/groovysh.html#GroovyShell-Variables
Comment: Thanks @diarmuid for the new link. updated the answer.


retorno de um pagina PHP para montagem de gráfico highcharts

Question: Estou montando um gráfico highcharts dinâmico, porém estou com um problema, preciso pegar um valor de uma página PHP e colocar no ponto y do gráfico, para isso uso uma função javascript denominada a priori  de "teste" segue o código do gráfico:
 $(document).ready(function () {

    Highcharts.setOptions({
        global: {
            useUTC: false
        }
    });

    Highcharts.chart('container', {
        chart: {
            type: 'spline',
            animation: Highcharts.svg, // don't animate in old IE
            marginRight: 10,
            events: {
                load: function () {

                    // set up the updating of the chart each second
                    var series = this.series[0];
                    setInterval(function () {
                        var x = (new Date()).getTime(), // current time
                                y = teste();//FUNÇÃO PARA PEGAR VALOR DA PAGINA PHP
                        series.addPoint([x, y], true, true);
                    }, 1000);
                }
            }
        },
        title: {
            text: 'Ligacoes Online'
        },
        xAxis: {
            type: 'datetime',
            tickPixelInterval: 150
        },
        yAxis: {
            title: {
                text: 'Valor'
            },
            plotLines: [{
                    value: 0,
                    width: 1,
                    color: '#808080'
                }]
        },
        tooltip: {
            formatter: function () {
                return '' + this.series.name + '
' +
                        Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '
' +
                        Highcharts.numberFormat(this.y, 2);
            }
        },
        legend: {
            enabled: false
        },
        exporting: {
            enabled: false
        },
        series: [{
                name: 'Data da ligacao',
                data: (function () {
                    // generate an array of random data
                    var data = [],
                            time = (new Date()).getTime(),
                            i;

                    for (i = -19; i <= 0; i += 1) {
                        data.push({
                            x: time + i * 1000,
                            y: Math.random()
                        });
                    }
                    return data;
                }())
            }]
    });
});

a função "teste" tem que colocar um valor no gráfico, (por exemplo: 2), segue o código da função teste, onde a mesma pega um valor de um SELECT no banco de dados, é valido ressaltar que está funcionando (visto pelo console.log), porem quando uso o return json ele não retorna:
function teste() {
    $.ajax({
        type: 'POST',
        url: 'file_get_value.php',
        cache: false,
        dataType: 'json',
        success: function (json) {
            console.log(json);
             return json;
        }
    });
}

como ainda estou em processo de melhora da minha programação em javascript me deparei com esse problema que aparentemente é simples, mas está me dando dor de cabeça.
Answer: Bom resolvi meu problema utilizando um variavel global que colocando o retorno do ajax.
var chart_live_calls = 0;
function requestData() {
var passar = 'qtdChamadas=' + 1;
$.ajax({
    type: 'POST',
    dataType: 'json',
    url: 'enviandoDashboardAdmin.php',
    data: passar,
    success: function (point) {
        console.log(point);
        chart_live_calls = point;
    },
    cache: false
});}

e no gráfico:
load: function () {

                // set up the updating of the chart each second
                var series = this.series[0];
                setInterval(function () {
                    var x = (new Date()).getTime(), // current time
                        y = chart_live_calls;
                    series.addPoint([x, y], true, true);
                }, 1000);

fica a solução se alguém tiver algum problema parecido.


make Dynamic JSONArray from Exiting Data in React-Native

Question: I am new to React-native
can any one tell me how to make a dynamic array from existing api data?
for example , I have an array like this:
[
  {name: 'ajay', time: '09:00', class: 'one',title: 'Archery Training', description: 'The Beginner Archery and Beginner Crossbow course does not require you to bring any equipment, since everything you need will be provided for the course. ', circleColor: '#009688',lineColor:'#009688'},
  {name: 'vijay',time: '10:45', class: 'two',title: 'Play Badminton', description: 'Badminton is a racquet sport played using racquets to hit a shuttlecock across a net.'},
  {name: 'zoya',time: '12:00', class: 'six',title: 'Lunch'},
  {name: 'prem',time: '14:00',class: 'five', title: 'Watch Soccer', description: 'Team sport played between two teams of eleven players with a spherical ball. ',lineColor:'#009688'},
  {name: 'ram',time: '16:30',class: 'ten', title: 'Go to Fitness center', description: 'Look out for the Best Gym & Fitness Centers around me :)', circleColor: '#009688'}
]

now I want to convert it in to like this:
[
  {time: '09:00', title: 'Archery Training', description: 'The Beginner Archery and Beginner Crossbow course does not require you to bring any equipment, since everything you need will be provided for the course. ', circleColor: '#009688',lineColor:'#009688'},
  {time: '10:45', title: 'Play Badminton', description: 'Badminton is a racquet sport played using racquets to hit a shuttlecock across a net.'},
  {time: '12:00', title: 'Lunch'},
  {time: '14:00', title: 'Watch Soccer', description: 'Team sport played between two teams of eleven players with a spherical ball. ',lineColor:'#009688'},
  {time: '16:30', title: 'Go to Fitness center', description: 'Look out for the Best Gym & Fitness Centers around me :)', circleColor: '#009688'}
]

thanks in advance
Answer: hi you can write javascript that ist the point from React-Native.
in that case i would create a function, that takes the data and return the new array. i just made an example for your case. keep in mind that working with data from any API could be more dificult than this example. so if you really get an Array that should be converted in a new one, it would be like that..

var yourAPIData = [
  {name: 'ajay', time: '09:00', class: 'one',title: 'Archery Training', description: 'The Beginner Archery and Beginner Crossbow course does not require you to bring any equipment, since everything you need will be provided for the course. ', circleColor: '#009688',lineColor:'#009688'},
  {name: 'vijay',time: '10:45', class: 'two',title: 'Play Badminton', description: 'Badminton is a racquet sport played using racquets to hit a shuttlecock across a net.'},
  {name: 'zoya',time: '12:00', class: 'six',title: 'Lunch'},
  {name: 'prem',time: '14:00',class: 'five', title: 'Watch Soccer', description: 'Team sport played between two teams of eleven players with a spherical ball. ',lineColor:'#009688'},
  {name: 'ram',time: '16:30',class: 'ten', title: 'Go to Fitness center', description: 'Look out for the Best Gym & Fitness Centers around me :)', circleColor: '#009688'}
]

const convertDataFromAPI = (data) => {
 var newArr = [];
 for ( var a = 0; a < data.length; a++){
 var myObject = {};
 data[a].time ? myObject['time'] = data[a].time : null
 data[a].title ? myObject['title'] = data[a].title : null
 data[a].description ? myObject['description'] = data[a].description : null
 data[a].circleColor ? myObject['circleColor'] = data[a].circleColor : null
 data[a].lineColor ? myObject['lineColor'] = data[a].lineColor : null
    newArr.push(myObject)
  }

  return newArr
}

console.log(convertDataFromAPI(yourAPIData))

Additionally you could  install axios. it helps you to make hppt requests. and if you need to convert the data into a json type, it will be easier for the subsequent data handling. keep in mind objects must be processed in a different way than arrays in the future convertDataFromArray function.
axios.get(request)
  .then(response => response.json())
  .then(response => convertDataFromAPI(response))
  .catch(error => console.log(error.message))

i hope this helps you!
Answer: Not sure what is the easier way.
Here is how I do using lodash library.
First, install it.
npm i --save lodash

Then import in your application.
import { omit, map } from 'lodash'

Then here is to make that array object.
const data = [
   {name: 'ajay', time: '09:00', class: 'one',title: 'Archery Training', description: 'The Beginner Archery and Beginner Crossbow course does not require you to bring any equipment, since everything you need will be provided for the course. ', circleColor: '#009688',lineColor:'#009688'},
   {name: 'vijay',time: '10:45', class: 'two',title: 'Play Badminton', description: 'Badminton is a racquet sport played using racquets to hit a shuttlecock across a net.'},
   {name: 'zoya',time: '12:00', class: 'six',title: 'Lunch'},
   {name: 'prem',time: '14:00',class: 'five', title: 'Watch Soccer', description: 'Team sport played between two teams of eleven players with a spherical ball. ',lineColor:'#009688'},
   {name: 'ram',time: '16:30',class: 'ten', title: 'Go to Fitness center', description: 'Look out for the Best Gym & Fitness Centers around me :)', circleColor: '#009688'}
]

const newData = map(data, (obj) => {
  const mappedObj = omit(obj, ['name', 'class'])
  return mappedObj
})

Let me know if it is work or not


What should I use to implement a shopping cart process?

Question: I'm developing a website for a group of human resource professionals.
The customer wants a way for people to go to their site and do the following:

If they have a job listing they want to post to the website, they'll click on a "Post a Job" link.
The job submitter will then fill out the content for a job posting
Before the job can go online, the job poster will have to pay a fee to have it posted
Once the payment is received, the job posts to the website

I'm curious if anyone has any experience with this, and if so, what would you use to build it? It's a fairly simple shopping cart experience I suppose. It's certainly not like a store or anything. But, I don't have previous experience with something like this.
Can anyone guide me down the correct path?
Answer: Here are a few typical solutions for implementing an online store:

Drupal Commerce, or its related Commerce Kickstart.
Ubercart.

However, as per your "Simple shopping cart experience", it looks like none of these is what you're looking for. So here are some other modules you may want to look at (excerpts are from their project pages):

Basic Cart:

... a very simple shopping cart / checkout process for Drupal, that just sends 2 emails after each order. Along with the shopping cart, this module also provides a block where you can view your cart's content. It's ideal for small websites with only a few products or other content types being sold, for example touristic offers.

Rules:

Allows site administrators to define conditionally executed actions based on occurring events (known as reactive or ECA rules).

Flag:

Flag is a flexible flagging system that is completely customizable by the administrator.

The 'Basic Cart' implements the cart, while with the 'Rules' and 'Flag' modules you can implement appropriate business logic (which does not require any PHP coding skills).
If you're not familiar (enough/yet) with Rules, then checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework, organised in 7 chapters.
Possibly also the similar set of 8 video tutorials about the Flag module, often considered as a natural complement to the Rules module.


Why is network stack ignoring icmp replies from non-default interface?

Question: I have following situation:

eth0 - default gateway ( ip: 172.28.183.100, gw: 172.28.183.1 )
eth0 - secondary network connection ( ip: 172.28.171.2, gw: 172.28.171.2).

routing looks like this:
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
172.28.183.0    0.0.0.0         255.255.255.0   U     0      0        0 eth0
172.28.171.0    0.0.0.0         255.255.255.0   U     0      0        0 eth2
172.28.173.0    0.0.0.0         255.255.255.0   U     0      0        0 eth1
22.214.171.124      172.28.171.1    255.255.255.0   UG    0      0        0 eth2
169.254.0.0     0.0.0.0         255.255.0.0     U     1000   0        0 eth0
0.0.0.0         172.28.183.1    0.0.0.0         UG    100    0        0 eth0

As you can see there is special route for 184.108.40.206/24 - this traffic should go by the secondary net eth2.
Which works. I can do any kind of tcp connections to machines in 126.96.36.199/24.
But, when I try to mtr them, I got weird result:
root@blob:~# mtr --report --report-cycles=5 22.214.171.124
HOST: blob                        Loss%   Snt   Last   Avg  Best  Wrst StDev
  1. 172.28.171.1                  0.0%     5    0.6   0.6   0.5   0.6   0.0
  2. ???                          100.0     5    0.0   0.0   0.0   0.0   0.0

In tcpdump output I see returned replies of time-to-live exceeded:
10:16:28.158888 IP 172.28.171.2 > 126.96.36.199: ICMP echo request, id 2092, seq 59520, length 44
10:16:28.159363 IP 172.28.171.1 > 172.28.171.2: ICMP time exceeded in-transit, length 72
10:16:28.259153 IP 172.28.171.2 > 184.108.40.206: ICMP echo request, id 2092, seq 59776, length 44
10:16:28.359546 IP 172.28.171.2 > 126.96.36.199: ICMP echo request, id 2092, seq 60032, length 44
10:16:28.408129 IP 10.9.208.1 > 172.28.171.2: ICMP time exceeded in-transit, length 36
10:16:28.428193 IP 10.9.208.2 > 172.28.171.2: ICMP time exceeded in-transit, length 36
10:16:28.459953 IP 172.28.171.2 > 126.96.36.199: ICMP echo request, id 2092, seq 60288, length 44
10:16:28.560260 IP 172.28.171.2 > 188.8.131.52: ICMP echo request, id 2092, seq 60544, length 44
10:16:28.618138 IP 10.9.213.6 > 172.28.171.2: ICMP time exceeded in-transit, length 36
10:16:28.660678 IP 172.28.171.2 > 220.127.116.11: ICMP echo request, id 2092, seq 60800, length 44
10:16:28.708130 IP 10.9.212.253 > 172.28.171.2: ICMP time exceeded in-transit, length 36
10:16:28.730193 IP 220.127.116.11 > 172.28.171.2: ICMP time exceeded in-transit, length 36
10:16:28.761086 IP 172.28.171.2 > 220.127.116.11: ICMP echo request, id 2092, seq 61056, length 44
10:16:28.861380 IP 172.28.171.2 > 126.96.36.199: ICMP echo request, id 2092, seq 61312, length 44
10:16:28.938167 IP 188.8.131.52 > 172.28.171.2: ICMP time exceeded in-transit, length 36

but, with strace on mtr i see that these ICMP replies are not delivered to mtr!
I think that the reason might be that the source ip of icmp response comes from "wrong" interface" - i.e. ICMP reply comes from (for example) 10.9.212.253 (some intermediary router), but this ip should be routed via eth0, while it comes to eth2.
Is it sensible reason? What can I do about it to make mtr work even to my "special" network?
iptables are set using:
iptables -P INPUT   DROP
iptables -P FORWARD DROP
iptables -P OUTPUT  ACCEPT

iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -i lo                                  -j ACCEPT
iptables -A INPUT -i eth1                                -j ACCEPT
iptables -A INPUT -p icmp                                -j ACCEPT

iptables -A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A FORWARD -i eth1                              -j ACCEPT

iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
iptables -t nat -A POSTROUTING -o eth2 -j MASQUERADE

iptables -A INPUT   -j LOG --log-prefix 'IPTABLES: '
iptables -A FORWARD -j LOG --log-prefix 'IPTABLES: '

But I don't see any icmp-related packages with kern.log.
Answer: Thanks to Rafał Ramocki - solution is simple - you have to turn off rp_filter-ing on eth2 interface:
echo 0 > /proc/sys/net/ipv4/conf/eth2/rp_filter

From kernel docs:
rp_filter
---------

Integer value determines if a source validation should be made. 1 means yes, 0
means no.  Disabled by default, but local/broadcast address spoofing is always
on.

If you  set this to 1 on a router that is the only connection for a network to
the net,  it  will  prevent  spoofing  attacks  against your internal networks
(external addresses  can  still  be  spoofed), without the need for additional
firewall rules.

While nice for preventing spoofing attacks (at least some), it definitely kills some functionality if you have more internet connections.


Dúvida no  do

Question: Estou tentando utilizar a variável SESSION para passar valores para os campos, como foi utilizado no "login", onde se existir algo dentro da variável, será mostrado no campo, mas se não existir, não será mostrado nada. Como posso fazer o mesmo no select?

    Login

        <input type="text" class="form-control" name="login" placeholder="Login" value="<?php echo $_SESSION['login_consultar']; unset($_SESSION['login_consultar']);?>">

    Nível de Acesso

        <select class="form-control" name="nivel_acesso">
            <option value="1">Administração</option>
            <option value="2">Informática</option>
        </select>

Comment: Faça um `include` no meio desse arquivo. Ante de exibir este formulario, você faça o include.
Comment: Se exercite bastante na linguagem. Sempre que ver uma função nova e não conhece-la apreenda sobre ela. Após isso comece a programar encima de Frameworks. Vai ficar mais facil.
Comment: E como o amigo @FelipeDuarte respondeu. Da pra fazer assim, mas não se usa essa forma de fazer isso. Você deve gerar esse conteúdo e passar o valor com uma variável.
Comment: E como faço isso? Comecei a utilizar a linguagem faz pouco tempo.
Comment: Como você está definindo esta `$_session`? De onde vem o valor?
Comment: Estou utilizando dessa forma: $_SESSION['nivel_acesso_consultar'] = $resultado['nivel_acesso']; - Onde $resultado é uma _mysqli_fetch_assoc_ de uma consulta mysql
Comment: Porque ta passando para um session? porque não passa direto? Ta em outro arquivo a consulta?
Comment: Sim, está em outro arquivo.
Comment: Vou fazer isso. Obrigado!
Answer: Dessa forma
<?php if(isset($_SESSION['teste'])) : ?>
    <option value="<?= $_SESSION['teste'] ?>"> teste </option>
<?php endif; ?>

Porém se estiver usando sessions somente para passar valores referente ao conteúdo, é melhor rever sua lógica.
Comment: Para passar valores pelas páginas use $_POST ou $_GET, mediante a um formulário, se necessita recuperar dados,entre as páginas, já entra na questão de banco de dados, a superglobal $_SESSION é para controle de sessão exemplo verificar se um usuário foi setado ou não, e a mesma tem de ser destruída.
Comment: O que você me recomenda, então? Comecei a trabalhar com a linguagem faz pouco tempo.
Answer: Neste caso você precisa verificar o valor da variável para cada option, e caso seja o option seleciona, imprimir o atributo selected no option. Exemplo:

    Login

        <input type="text" class="form-control" name="login" placeholder="Login" value="<?php echo $_SESSION['login_consultar']; unset($_SESSION['login_consultar']);?>">

    Nível de Acesso

        <select class="form-control" name="nivel_acesso">
            <option value="1"<?php if($_SESSION['login_consultar'] == '1') { echo ' selected="selected"'; } ?>>Administração</option>
            <option value="2"<?php if($_SESSION['login_consultar'] == '2') { echo ' selected="selected"'; } ?>>Informática</option>
        </select>

Dúvida no  do