Converting an  tags track time into Mins:Secs

Question: I created a frankensteined audio player, and need a little help with the track timing. I have it now so it counts from 0 -> whatever the track time is, in seconds. I can't seem to figure out how to convert those seconds into mins:secs.
I'm new to timing/converting with JS, so any help is appreciated!
HTML
    <audio src="" id="player"
        ontimeupdate="document.getElementById('tracktime').innerHTML = Math.floor(this.currentTime) + ' ' + Math.floor(this.duration);">\
</audio>

    0  0:00

CODE UPDATE
Alright, so I now have it so it just shows minutes as a single digit (ie: 1:00 = 1, 2:00 = 2, 3:00=3, etc)
I need it to show it as 3 digits, ie: 1:00 = 1:00, 2:00 = 2:00, etc.
Here is my current audio tag:
<audio src="http://dosh.dk/bb/track.mp3" id="player" ontimeupdate="document.getElementById('tracktime').innerHTML = Math.floor(this.currentTime / 60) + ' ' + Math.floor(this.duration / 60);">

    </audio>

I just can't seem to concatenate the seconds onto the minutes.
Comment: Math.floor(this.currentTime / 60) + ' ' + Math.floor(this.currentTime % 60)
Comment: That ended up making my left side (the counting one) stay static at 0, and my right side (the total time) count up (updated my question to show current code).
Answer: Figured it out, just had to reformat somethings..
HTML

0:00

0:00

JS
//var audio = link to my audio file
audioplayer.addEventListener("ended", replay, false);
    audioplayer.addEventListener("timeupdate", timeUpdate, false);

    function reskinTime(secs, format) {
            var hr = Math.floor(secs / 3600);
            var min = Math.floor((secs - (hr * 3600)) / 60);
            var sec = Math.floor(secs - (hr * 3600) - (min * 60));
            if (sec < 10) {
                    sec = "0" + sec;
            }
            return min + ':' + sec;
    }

    function timeUpdate() {
            playPercent = (audioplayer.currentTime / duration) * 100;
            playhead.style.width = playPercent + "%";
            timer.innerHTML = reskinTime(audioplayer.currentTime.toString());
    }

Comment: No need to calculate hours first, just use: var min = Math.floor((secs % 3600) / 60); var sec = Math.floor(secs % 60);
Answer: In CMS Effcore we have applied the following simple and ingenious solution:
function formatTime(time) {
  var h =        Math.floor(time /    3600);
  var m = ('0' + Math.floor(time / 60 % 60)).slice(-2);
  var s = ('0' + Math.floor(time      % 60)).slice(-2);
  return h + ':' + m + ':' + s;
}


How to find the general formula of an arithmetic progression?

Question:
I'm very new to combinatorics and graph theory and I was doing some work and I was asked to find certain values which I tabulated above.
The table follows this general pattern and continues along.
My problem is this;
How do I go about solving for the GENERAL FORMULA of tables of values such as this?
OBSERVATION
I've made some deductions and with respect to the $D_1 \quad D_2 .....$ values etc
So what I first did was collect ALL the values of $D_1$ in terms of $V$ and then $D_2$ in terms of $V$ etc until I reached $D_8$
The reason for focusing on the '$V$' value is that the graph theory work used to find the respective $D$ values is dependent upon $V$ , where $V$ denotes the vertex of the graph
So for example $D_1 = V -1$
$D_2 = (V) + (V+1) + (V+2) + (V+3) + (V+4) + (V+5)....$
$D_3 = (V-1) + (V+1) + (V+3) + (V+5) +(V +7) + (V+9) ....$
And I did this all the way till $D_8$
Is this the correct method to try and find a formula to solve for the SB value ,assuming that this is a method , what do I need to do next?
I need to find a formula such that when I enter the value of the vertex and edge I am able to compute the SB value in all cases.
Can anyone point me in the right direction of what I need to do to achieve this?
Is there any software that computes such a formula?
What are some recommended reading materials to help me better solve these kinds of problems?
The only book that I currently used is the Graph theory by Harary.
Answer: So your pattern seems to be that when $V = n+1$, $D_n = n$, and then it increases by $n$ each time. In other words, when $V = n+k$, $D_n = kn$; or, in terms of $V$ directly, $D_n = (V-n)n = nV - n^2$.
The SB column is the sum $D_1 + D_2 + \dots + D_{V-1}$, giving us
$$
   \sum_{n=1}^{V-1} D_n = \sum_{n=1}^{V-1} (nV - n^2) = V \sum_{n=1}^{V-1} n - \sum_{n=1}^{V-1}n^2.
$$
The first sum is the sum $1 + 2 + \dots + (V-1)$ and such sums are easy to compute: the values are uniformly spaced, and so we can take the average value (which is $\frac V2$) and multiply it by the number of terms (which is $V-1$). We get $\frac{V(V-1)}{2}$ for the first sum, or $\frac{V^2(V-1)}{2}$ when you take the factor of $V$ in front into account.
The second sum is the sum $1^2 + 2^2 + \dots + (V-1)^2$, and this is trickier to compute. But there's a well-known formula for this sum: $$1^2 + 2^2 + \dots + (V-1)^2 = \frac{V(V-1)(2V-1)}{6}.$$ If you know the formula, then it can be verified using induction.
Putting these together, we get
$$
   D_1 + D_2 + \dots + D_{V-1} = \frac{V^2(V-1)}{2} - \frac{V(V-1)(2V-1)}{6} = \frac{V(V-1)}{2} \cdot \left(V - \frac{2V-1}{3}\right) = \frac{(V+1)V(V-1)}{6}.
$$
So that gives you the answer.
However, since the formula we got is just a different way of writing $\binom{V+1}{3}$, you should see if there's a more direct argument for the thing you're counting: whatever it is, maybe you can interpret it as picking $3$ things out of $V+1$?
Comment: Once we have found a formula for $D_n$, we split up the sum $D_1 + D_2 + \dots + D_{V-1}$ into two parts. Since $D_n = nV - n^2$, we can first compute the sum of $nV$, and then subtract the sum of $n^2$. This doesn't correspond to any row or column in your table exactly.
Comment: Please clarify the following for me if you can
1.The sum 1+2+.... + (V - 1) which you obtained did you get by summing the first column of $D_1$ ? Or was this done by summing the first row to obtain the first SB value?

2. Also when getting the second sum did you sum along the $D_2$ column? I'm just a little confused where exactly you are computing $1^{2} + 2^{2} + ... + (V - 1)^{2}$

Is the methodology one where you try to find a pattern along the rows and then compute the first two , as you have done , and then this will give a general formula?
@MishaLavrov
Comment: Ok , thanks for clearing that up for me

I have tried using the formula $\displaystyle\frac{(V+1) V (V-1)}{6}$ to solve the SB value of a similar problem with the same pattern but it does not yield the same results , is there something that I'm missing from the equation?[See link attached]

For example to find $D_4$ , $D_4 = 4 \times k$ and $ 7 = 4 + k$

So $k=3$ and $D_4 = 4 \times 3 = 12$ , So it works!

but , using the formula gives $\displaystyle\frac{(7)(6)(5)}{6} = 35 $ which is not equal to SB value of 29 for row 1
https://imgur.com/a/dIIzQjX @MishaLavrov
Comment: Uh, yes, if you change the numbers in the table, the formula will stop working...


Closing Unhelpful Questions Which Have No Need of a Solution

Question: The https://magento.stackexchange.com/questions/4733/change-order-state question was asked, the OP eventually came back in the comments and said "problem solved. It was one inappropriate order"
IMO this should be closed because the question will not be helpful to others. There is no context for why the code the question was being asked about was not working since it was a botched order… or in other words, it's too localized to the OPs environment/data.
Trying to flag it to be closed, I noticed the 'Too Localized' option no longer exists. What banner would you suggest questions like these be marked for closure under? Do we need a new closure reason?
Answer: I chose to flag it for closure as Off Topic, after finding this option beneath the OT group of reasons: "Questions describing a problem that can't be reproduced and seemingly went away on its own (or went away when a typo was fixed) are off-topic as they are unlikely to help future readers."


text-align:centre not aligning text correctly in

Question: I am experimenting with following HTML code. It displays a paragraph and two buttons at the bottom (Back and Next).
    <!DOCTYPE html>

        <meta charset="UTF-8">
        <title>HTML Test</title>

I want the text in  to be centrally aligned but it doesn't. I have used text-align:centre to set style of . What am I doing wrong?

        1. Some Para.

 Back

 Next

Comment: Try `text-align: center`?
Answer: You need to use text-align: center, rather than 'centre'.
ul#navigation li a {
    display: block;
    padding: .2 em;
    color: #fff;
    width: 5em;
    background-color:#00f;
    text-align: center;
    text-decoration: none;
}

Answer: centre;<-- wrong word... it's center

#navigation {
            list-style-type:none;
            border-top:1px solid red;
            margin:0;
            padding:0;
            }
            ul#navigation .left{
                float:left;
                width:5em;
                margin: 10px 0 0 0;
            }
            ul#navigation .right {
                float:right;
                width:5em;
                margin: 10px 0 0 0;
            }
            ul#navigation li a {
            display:block;
            padding:.2 em;
            color:#fff;
            width:5em;
            background-color:#00f;
            text-align:center;/*centre;<-- wrong word... it's center */
            text-decoration:none;
            }

        1. Some Para.

 Back

 Next

Answer:

#navigation {
  list-style-type: none;
  border-top: 1px solid red;
  margin: 0;
  padding: 0;
}
ul#navigation .left {
  float: left;
  width: 5em;
  margin: 10px 0 0 0;
}
ul#navigation .right {
  float: right;
  width: 5em;
  margin: 10px 0 0 0;
}
#navigation ul li {
  color: #fff;
  width: 100%;
  background-color: #00f;
  text-align: center;
  text-decoration: none;
}

1. Some Para.

 Back

 Next


GLM link function for bimodal probit fitting?

Question: I am trying to model a set of data I have physical reason to believe can be represented by a bimodal normal cumulative distribution function (Technically it is a bimodal log-normal CDF, but I think I can handle transforming the predictor by log(x) ). I can successfully find the best fit to the data using MLE, e.g. $$ \hat{y}(x;\mu_1,\sigma_1,\mu_2,\sigma_2) = \frac{1}{2} + \frac{w}{2}erf \left(\frac{x-\mu_1}{\sqrt{2}\sigma_1} \right) + \frac{(1-w)}{2}erf \left(\frac{x-\mu_2}{\sqrt{2}\sigma_2} \right) $$
However, I also want to establish a prediction interval on the data for theoretical future measurements of y at some x. The only way I have come up with to do this is to set up a GLM with what I would interpret as a sort of bimodal probit model, e.g. $$ \hat{y} = \Phi ( b_0 + b_1x ) * b_2 + \Phi ( b_3 + b_4x ) * (1-b_2)  $$
However, I can't invert the CDF to get the right side to be some sort of linear function like I can with a mono-modal CDF, e.g. $$ G(\hat{y}) = \Phi^{-1}(\hat{y}) = b_0 + b_1x $$
Am I thinking about this incorrectly? Is there a way to do a bimodal CDF link function? Perhaps there is a better way of determining how well a dataset fits a given bimodal CDF and establish a prediction interval that does not use a GLM?
Answer: I think your chosen function may be inherently nonlinear, though it's partially linearizable (each of $(b_0,b_1)$, $(b_3,b_4)$ and $b_2$ may be made linear in a transformed model, given the others).
If you need a binomial model for your response, you might need to use generalized nonlinear models.
Comment: Thanks. I think you are right that I can't do this with a GLM. Perhaps I should just look for a better way to estimate variance of y and use that.


Woocommerce redirect after registration

Question: I am trying to redirect user after Woocommerce registration. I have tried everything and it is not working.
I have tried some methods found on internet but they didn't work…
When I change 'myaccount' to another permalink it just freezes when you click register.. not sure why.
wp_safe_redirect( apply_filters( 'woocommerce_registration_redirect', wp_get_referer() ? wp_get_referer() : wc_get_page_permalink( 'welcome' ) )

I even tried with the page id
wp_safe_redirect( apply_filters( 'woocommerce_registration_redirect', wp_get_referer() ? wp_get_referer() : wc_get_page_permalink( '1072' ) )

Any help?
Answer:
Important update (working on last version 3.2.x)

First the woocommerce_registration_redirect is a filter hook, but NOT an action hook.
A filter hook has always at least one argument and always require to return something. It can be the main function argument (the first one) or some custom value.

The correct tested and functional code is:
add_filter( 'woocommerce_registration_redirect', 'custom_redirection_after_registration', 10, 1 );
function custom_redirection_after_registration( $redirection_url ){
    // Change the redirection Url
    $redirection_url = get_home_url(); // Home page

    return $redirection_url; // Always return something
}

Code goes in function.php file of your active child theme (or theme)...

Some common redirections urls used in woocommerce:

Get the "Home" page Url: $redirection_url = get_home_url();
Get the "Shop" page url: $redirection_url = get_permalink( wc_get_page_id( 'shop' ) );
Get the "Cart" page Url: $redirection_url = wc_get_cart_url();
Get the "Checkout" page Url: $redirection_url = wc_get_checkout_url();
Get the "My account" or registration page Url: $redirection_url = get_permalink( wc_get_page_id( 'myaccount' ) );
Get other post or pages by ID: $redirection_url = get_permalink( $post_id ); (where $post_id is the id of the post or the page)
Get post or pages by path (example): $redirection_url = home_url('/product/ninja/');
Comment: Thank you for this, searched all day and this was the best solution I've seen!
Comment: @LoicTheAztec After registration from registration form on account page , I want user to auto-login and directly enters to the Dashboard page rather than going back to login page.
Answer: The accepted answer didn't work for me. What worked for me was this:
// After registration, logout the user and redirect to home page
function custom_registration_redirect() {
    wp_logout();
    return home_url('/');
}
add_action('woocommerce_registration_redirect', 'custom_registration_redirect', 2);

Comment: Why would you want to log the user out after registration?
Comment: @claytronicon We needed to implement an approval mechanism at that time. The user needed to be approved first before being able to login. `wp_logout()` deleted the user session directly after it was created.
Comment: This will fail if you deactivate Woocommerce
Comment: It seems the redirect doesn't work when pointed to other than home's domain, even to it's subdomain. Falls back to my-account/
Answer: You want to use a filter like this:
function plugin_registration_redirect() {
    return home_url( '/page-to-show' );
}

add_filter( 'registration_redirect', 'plugin_registration_redirect' );

Or, specifically to your code:
function plugin_registration_redirect() {
    $url = wp_get_referer() ? wp_get_referer() : wc_get_page_permalink( 'welcome' );
    return $url;
}

add_filter( 'registration_redirect', 'plugin_registration_redirect' );

Answer: WP WooCommerce Redirect is a WordPress plugin to redirect your WooCommerce website after register or login!  You can set any custom page or custom redirect according to user role.
You can set user login and register redirection page without any codding knowledge to your WooCommerce website . Your customer reduce time for using this plugin and get their destination easily.
I have developed a plugin for this issue. Also given bellow of raw code for redirect without any plugin.
//Redirect users to custom URL based on their role after login
function wp_woo_custom_redirect( $redirect, $user ) {

// Get the first of all the roles assigned to the user
$role = $user->roles[0];
$dashboard = admin_url();
$myaccount = get_permalink( wc_get_page_id( 'my-account' ) );

if( $role == 'administrator' ) {

    //Redirect administrators to the dashboard
    $admin_redirect = get_option('admin_redirect');
    $redirect = $admin_redirect;
} elseif ( $role == 'shop-manager' ) {

    //Redirect shop managers to the dashboard
    $shop_manager_redirect = get_option('shop_manager_redirect');
    $redirect = $shop_manager_redirect;
} elseif ( $role == 'customer' || $role == 'subscriber' ) {

    //Redirect customers and subscribers to the "My Account" page
    $customer_redirect = get_option('customer_redirect');
    $redirect = $customer_redirect;
} else {

    //Redirect any other role to the previous visited page or, if not available, to the home
    $redirect = wp_get_referer() ? wp_get_referer() : home_url();
}
return $redirect;
}
add_filter( 'woocommerce_login_redirect', 'wp_woo_custom_redirect', 10, 2 );

If you feel comfort to work with plugin or without code? You can download and install my plugin "WP WooCommerce Redirect"
Answer: Add this filter in theme function file.
function filter_woocommerce_registration_redirect( $var ) {
    // make filter magic happen here...
    return get_page_link(3598); // 3598 id page id.
};

Add the filter:
add_filter( 'woocommerce_registration_redirect',
    'filter_woocommerce_registration_redirect', 10, 1 );

Answer: If anyone is looking for the Login redirection version that works for the woocommerce my-account login:

add_filter('woocommerce_login_redirect', 'hs_login_redirect');
function hs_login_redirect( $redirection_url ) {
    $redirection_url = get_home_url();
    return $redirection_url;
}

Woocommerce redirect after registration


Django Rest Framework: Converting a model object number into its corresponding string

Question: I've an application which contains two different models, related by a Many-to-Many relationship as follows:
from django.db import models

class Genres(models.Model):
    genre = models.CharField(max_length = 128, unique = True)

class Movies(models.Model):
    popularity = models.FloatField()
    director = models.CharField(max_length = 128)
    genre = models.ManyToManyField(Genres, related_name = 'movies')
    imdb_score = models.FloatField()
    movie_name = models.CharField(max_length = 500)

serializers.py
from shoppy.models import Movies, Genres
from rest_framework import serializers

class GenresSerializer(serializers.ModelSerializer):

    class Meta:
        model = Genres
        fields = ('genre',)

class MoviesSerializer(serializers.ModelSerializer):
    #genre = serializers.CharField(max_length = 128, choices = Movies.GENRE_CHOICES)

    class Meta:
        model = Movies
        fields = ('popularity', 'director', 'imdb_score', 'genre',
                        'movie_name')

This is how my API endpoint form at http://localhost:8000/movies/ looks like:

Now, instead of different genres appearing as instances of Genres object numbers, how can I make them appear as the actual string corresponding to each object number? For example, Genres object-1 corresponds to Comedy, and that is what I want to be displayed in the API endpoint form to make the genre choices more human-readable.
What's the way to do something like that?
Answer: You need to implement a __str__ method in your Genres model.
class Genres(models.Model):
    genre = models.CharField(max_length = 128, unique = True)

    def __str__(self):
        return '%s'%self.genre

Comment: This works just fine. However, in the generated JSON format, the selected `genres` are still displayed with their corresponding numerical values. How do I make them appear as their string equivalents in the generated API formats?
Comment: By numerical values, you mean the `genre` ids? Can you post a sample json
Comment: Yes, the genres are being represented by their respective ids in the generated API format.
Comment: You might need to override the `to_represention`  method for `ManyToManyField` and then return `str(value)` instead of `value.pk` which it is returning now.`str(value)` will call the `__str__` method of `Genres` model.
Comment: In your serializer, you need to define the `depth` property of `class Meta`. Setting `depth = 1` should give you the representation you are looking for,


Skewed data for regression analysis

Question: I have 30 features in my self-collected dataset where I want to build a regression model. When I look at my data, most of the attributes (95% of the data points) are skewed on a very small range. Out of 30 features, only 2 features has sort-of normal distribution and other features are ranged within a majority range. Here is a graph of the distribution of some of the attributes:

My question is: is it safe/normal to work with such data? Or should I treat the 5% of the data as outliers and remove them, so that the rest of the 95% will have a normal-like distribution?
Intuitively, since majority of the attributes have very similar values, I am afraid that they won't have a distinguishing effect in the prediction. But I might be wrong, so I would like to ask here.
Comment: Hi @Weka and welcome to the site. First, I would discourage you from excluding 5% of the data just that the rest looks like a normal distribution. If these 5% data were correctly measured, you should include them in the analysis. Maybe a [transformation](http://stats.stackexchange.com/questions/61217/transforming-variables-for-multiple-regression-in-r/61226#61226) would be applicable in your case, but remember: it is a common misunderstanding that the original variables in a linear regression must be normally distributed. The *residuals,* though, should be approximately normal.
Comment: There is a procedure called [support vector regression (SVR)](http://eric.univ-lyon2.fr/~ricco/tanagra/fichiers/en_Tanagra_Support_Vector_Regression.pdf) that shares many similarities with SVM but is for a continuous dependent variable. To run it in Weka, go to "Classify"->"Choose"->"Functions"->"SMOreg".
Comment: A sample of the attributes: http://i.imgur.com/ZRKOX7c.png
Comment: Actually my main problem is: I want to use optimization family with this data and I believe I have to transform this data into discrete values. However, when I do that via Weka->Filter->Discretize, almost all of the values fall into the same bucket. This also applies to the value I want to predict. So basically, I end up with a dataset where 95% of the labels are assigned to 1 single majority class. Do you think this is a problem, or is it not important?
Comment: I don't know what you mean by "optimization family"? Why do you have to discretizie the data for that? Do you want to do a classification? In your question, you state that you want to build a regression model. In any case: please edit your question and include more information about what exactly you want to do and with what software etc. Thanks.
Comment: I mean optimization algorithms like SVM. Since SVM doesn't work with numerical data, I thought of discretizing the data and then applying SVM algorithm. I am using Weka tool. My main goal for this dataset is to predict user's bandwidth usage.
Answer: First thing I'd suggest is that it looks like the huge spikes are zero. What do the graphs look like if you exclude zero? There is a class of problem called Zero Inflation Models where you have a lot of zero values and need to distinguish between zeros during times when non-zeros are possible, and zeros that are during times where non-zeros aren't really possible.
For example, if you're looking at the network traffic for desktop computers in a business, you might find that people turn off their machines (or the machines go to sleep) outside of normal business hours, so you can't get non-zero usage for those machines during those hours. During the day, you might see zero usage, but it's more random and depends on what the user is doing.
Second, are you concerned about extreme values (for say bandwidth provisioning)? There is an entire field of statistics called Extreme Value Theory, from which you may find the Weibull distribution useful.
Answer: I would recommend keeping all data. As @COOLSerdash notes, the inputs to a regression don't need to be normally distributed, the residuals do (in order to do certain statistical tests - if you don't care about inference, you can disregard normality).
The long tails may be just the input data values that are most important to your dependent variable! Look at some transformations, e.g., logs or Box-Cox, and use cross-validation to choose the best predictive model.
Answer: I would suggest exploring some common data transformations such as square-root and log transforms. Examine the normality of each and remember which ones you have used when interpreting your coefficients. In terms of outliers, there are quite a few approaches to how to handle them. One thing you can always try when there are a few outliers is run the regression with and without them...and compare the results.

Skewed data for regression analysis


Solution attempt $xu_x+u_y-(y+z)u_z=0$

Question: Solve $$
\begin{cases}
xu_x+u_y-(y+z)u_z=0\\
u(x,1,z)=xz\\
\end{cases}
$$
I got:
\begin{cases}
x_t=x\\
y_t=1\\
z_t=-y-z\\
u_t=0
\end{cases}
Therefore:
\begin{cases}
x(t,s_1,s_2)=e^tf_1(s_1,s_2)\\
y(t,s_1,s_2)=t+f_2(s_1,s_2)\\
z(t,s_1,s_2)=e^{-t}f_3(s_1,s_2)-t-f_2(s_1,s_2)\\
u(t,s_1,s_2)=f_4(s_1,s_2)
\end{cases}
Using initial condition:
\begin{cases}
s_1=x=f_1(s_1,s_2)\\
1=y=f_2(s_1,s_2)\\
s_2=f_3(s_1,s_2)-f_2(s_1,s_2)\\
s_1s_2=u=f_4(s_1,s_2)
\end{cases}
So:
\begin{cases}
x(t,s_1,s_2)=e^ts_1\\
y(t,s_1,s_2)=t+1\\
z(t,s_1,s_2)=e^{-t}(s_2+1)-t-1\\
u(t,s_1,s_2)=s_1s_2
\end{cases}
I am writing $$u=s_1s_2$$ by $x,y,z$ term and get $$x(z+y)-xe^{1-y}$$
which is incorrect, where is the problem?
Comment: The condition is not compatible with your equation.
Comment: @Isham sorry, edited
Answer: $$xu_x+u_y-(y+z)u_z=0$$
The Charpit-Lagrange system of characteristic ODEs is :
$$\frac{dx}{x}=\frac{dy}{1}=\frac{dz}{-(y+z)}$$
A first characteristic equation comes from $\frac{dx}{x}=\frac{dy}{1}$
$$\frac{1}{x}e^y=c_1$$
A second characteristic equation comes from $\frac{dy}{1}=\frac{dz}{-(y+z)}$
The solution of this ODE is :$\quad z=c_2e^{-y}-y+1$
$$(z+y-1)e^y=c_2$$
The general solution of the PDE on the form of implicit equation $u=F(c_1\:,\;c_2)$ is :
$$\boxed{u(x,y,z)=F\big(\frac{1}{x}e^y,(z+y-1)e^y\big)}$$
The arbitrary function $F$ has to be determined according to the specified condition.
CONDITION : $u(x,1,z)=xz$
$$xz=F\big(\frac{1}{x}e,(z+1-1)e\big)$$
Let $X=\frac{e}{x}\quad\implies\quad x=\frac{e}{X}$
and $Y=ez\quad\implies\quad z=\frac{Y}{e}$
$xz=\frac{e}{X}\frac{Y}{e}=\frac{Y}{X}=F(X,Y)$
Now the function $F$ is determined :
$$F(X,Y)=\frac{Y}{X}$$
We put it into the above general solution where $X=\frac{1}{x}e^y$ and $Y=(z+y-1)e^y$
$$u(x,y,z)=\frac{(z+y-1)e^y}{\frac{1}{x}e^y}$$
$$\boxed{u(x,y,z)=x(z+y-1)}$$
$$ $$
ADDITION as an answer to OP's comment.
The OP asked why $\frac{1}{x}e^y=c_1$ was used instead of $xe^{-y}=C_1$.
Answer : Both can be used equivalently. For example with the second $xz=\Phi(C_1,c_2)$
$$xz=\Phi\big(xe^{-1},(z+1-1)e\big)$$
Let $X=xe^{-1}\quad\implies\quad x=eX$
and $Y=ez\quad\implies\quad z=\frac{Y}{e}$
$xz=eX\frac{Y}{e}=XY=\Phi(X,Y)$
Now the function $\Phi$ is determined :
$$\Phi(X,Y)=XY$$
We put it into the above general solution where $X=xe^{-y}$ and $Y=(z+y-1)e^y$
$$u(x,y,z)=(xe^{-y})(z+y-1)e^y$$
$$\boxed{u(x,y,z)=x(z+y-1)}$$
$$ $$
COMMENT :
The system of equations that you wrote :
$\begin{cases}
\frac{dx}{dt}=x\\
\frac{dy}{dt}=1\\
\frac{dz}{dt}=-y-z\\
\frac{du}{dt}=0
\end{cases}$
is exactly he same as the Charpit-Lagrange written on this form
$$dt=\frac{dx}{x}=\frac{dy}{1}=\frac{dz}{-z-y}=\frac{du}{0} .$$
Of course, both lead to the same characteristic equations. Fundamentally there is no difference except presentation and symbolism. The approach that you use which introduces a lot of new parameters is especially usefull when it is simpler to express the result on the form of parametric solution. In the present case where the result can be expressed on explicit form, one can discuss the interest of introducing more parameters which are eliminated at the end. But it doesn't matter, that's up to you to chose the approach appearing the most intelligible for you.
It seems that there is a mistake in your calculus when solving the coupled equations $\frac{dy}{dt}=1\quad,\quad\frac{dz}{dt}=-y-z$.
Unfortunately the intermediate steps are not edited and the further steps not sufficiently detailed. One cannot check them. Possibly you should get :
\begin{cases}
x(t,s_1,s_2)=e^tf_1(s_1,s_2)\\
y(t,s_1,s_2)=t+f_2(s_1,s_2)\\
z(t,s_1,s_2)=e^{-t}f_3(s_1,s_2)-t-f_2(s_1,s_2)+1\\
u(t,s_1,s_2)=f_4(s_1,s_2)
\end{cases}
$+1$ is missing in your third equation. As a consequence your further calculus has to be slightly corrected.
Using initial condition:
\begin{cases}
s_1=x=f_1(s_1,s_2)\\
1=y=f_2(s_1,s_2)\\
s_2=f_3(s_1,s_2)-f_2(s_1,s_2)+1\\
s_1s_2=u=f_4(s_1,s_2)
\end{cases}
So:
\begin{cases}
x(t,s_1,s_2)=e^ts_1\\
y(t,s_1,s_2)=t+1\\
z(t,s_1,s_2)=e^{-t}s_2-t\\
u(t,s_1,s_2)=s_1s_2
\end{cases}
and finally
$s_1=e^{-t}x$
$s_2=e^t(z+y-1)$
$$u=s_1s_2=x(z+y-1)$$
Comment: It doesn't matter. $\frac{1}{x}e^y=C_1$ is the same as $xe^{-y}=c_1$ with $C_1=\frac{1}{c_1}$. Both $c_1$ and $C_1$ are arbitrary. Chosing one or another will change the further calculus but at end the result is the same.
Comment: See the addition to my main answer.
Comment: Thanks, for the  Charpit-Lagrange method, why did your first ode is $\frac{1}{x}e^y=c_1$ and not $xe^{-y}=c_1$?
Comment: Correct, I got the same answer for the Charpit-Lagrange method, still can't find the solution using method of characteristics
Comment: See the comment at end of my answer.

Solution attempt $xu_x+u_y-(y+z)u_z=0$


How to improve run on guitar

Question: I'm currently learning Capricho Arabe by Francisco Tarrega (Youtube link to song).I am struggling with the run at the beginning of the piece (0:35):

and was wondering how I can speed it up and make it sound clear.
P.S. It also has to be rest stroke.
Answer: Using rest stroke (apoyando) this can be made very clear. As always, the way to approach a piece you find difficult is to start off slow.

Find a speed at which you can comfortably play this
Ensure you play it accurately
Choose which fingers you are going to use (to me this feels like apoyando with i, m and a, but you may wish to play it differently)

Then gradually increase your speed. If you find you are tense or tiring, make a conscious effort to relax. You should also try altering the angle of your right hand, as some positions will be faster than others. Generally work towards finger movements at 90 degrees to the strings.
Apoyando should pluck the string then come to rest against the next string. To ensure clarity of sound, it is straightforward to only allow the chosen string to sound, with all others damped as needed.
Comment: Great concise but perfect answer.  Plus 1 of many more to come!
Comment: You may also want to consider a new right hand fingering. AMI scales are very intuitive to the hand, and can really increase your speed, although you may need to change some things in the left hand to optimize for this technique. Also I am curious to know why it needs to be played using rest stroke?
Answer: Practice scales. And more scales. And when you've done that, practice more scales. What this does is gets you ready for passages such as this. Be sure to alternate when practicing!... i m i m i m i m or m i m i m i m i. You got this!

How to improve run on guitar


file.width e file.height - Não funciona no Dropzone.js

Question: Estou implementado o sistema de Dropzone.js em um sistema, porem, preciso limitar o tamanho da imagem.
Como pego estas informações para limitar o upload que não esteja dentro dos padrões?

 Dropzone.options.dropzoneFrom = {
  autoProcessQueue: false,
  acceptedFiles:".jpg, .jpeg",
                maxFilesize: 1,
  maxFiles:3,
  addRemoveLinks:true,
                dictFileTooBig: "Imagem supera o tamanho permitido ({{filesize}}Mb). Tamanho maximo: {{maxFilesize}}Mb.",
                  createImageThumbnails: false,
                accept: function(file, done) {
                console.log(file.width)
                if (file.name === "teste.jpg") {
                  done("Naha, you don't.");
                }
                    else { done(); }
                },

  init: function(){
   var submitButton = document.querySelector('#submit-all');
   myDropzone = this;
   submitButton.addEventListener("click",function(){
    myDropzone.processQueue();
   });
   /*this.on("complete",function() {
    if(this.getQueuedFiles().length == 0 && this.getUploadingFiles().length == 0)
    {
     var _this = this;
     _this.removeAllFiles();
    }
   });*/
  },
 };
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />

 <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/dropzone.css"/>

Upload de arquivo

   <form action="upload.php" class="dropzone" id="dropzoneFrom" style="  border: 2px dashed rgb(54, 183, 0);">
   </form>

    <button type="button" class="btn btn-info" id="submit-all"> Upload</button>

Answer: As propriedades file.width e file.height não existem no Dropzone. Basta você fazer um console.log(file) e verá que elas não existem, apenas o file.name e outras (como o peso em bytes), mas não o .width e o .height.
Use a APIFileReader() para pegar as dimensões da imagem. Coloque na função do accept:
var reader = new FileReader();
reader.onload = (function(entry) {
   var image = new Image();
   image.src = entry.target.result;
   image.onload = function() {
      console.log(this.width); // mostra o width
      console.log(this.height); // mostra o height
   };
});
reader.readAsDataURL(file);

Só que, como a função do .onload é assíncrona, você terá que fazer os devidos tratamentos dentro dela.
Comment: Veja aí e qualquer coisa pode me chamar aqui.
Comment: Blz, obrigado, vou tentar implantar aqui e ver o resultado
Comment: Funcionou perfeitamente, obrigado pela ajuda!!!


If $x_n=o(\alpha_n)$ and $y_n=o(\alpha_n)$, then $x_n+y_n=o(\alpha_n)$.

Question: If $x_n=o(\alpha_n)$ and $y_n=o(\alpha_n)$, then $x_n+y_n=o(\alpha_n)$.
All I know is the definition of little oh notation being used, that is, $x_n=o(\alpha_n)$ means that there exists a sequences $\epsilon_n\geq 0$ with $\epsilon_n \to 0$ as $n\to \infty$ and $|x_n|\leq \epsilon_n |\alpha_n|$. I'm not sure how to prove this result. Any solutions or hints are greatly appreciated.
Answer: Note that
$$
\bigg| \frac{x_{n}+y_{n}}{\alpha_{n}} \bigg| \leq \bigg| \frac{x_{n}}{\alpha_{n}} \bigg| + \bigg| \frac{y_{n}}{\alpha_{n}} \bigg|
$$
and that the right side $\to 0$ by assumption.
Comment: While this is useful for intuition, it requires particular care if $\alpha_n = 0$ for some $n$.
Comment: That depends on the original requirement as to whether $\alpha_{n} \neq 0$ for all $n$. @Omnomnomnom
Answer: Hint: Note that if $|x_n| \leq \delta_n \alpha_n$ and $|y_n| \leq \epsilon_n |\alpha_n|$, then
$$
|x_n + y_n| \leq |x_n| + |y_n| \leq (\delta_n + \epsilon_n)|\alpha_n|
$$
Comment: Can we take $\gamma_n=\delta_n + \epsilon_n$ and then we have that $x_n+y_n=o(\alpha_n)$?
Comment: @DerpMagoo that's exactly right.  We note that $\gamma_n \to 0$.
Comment: awesome, thank you : )


XGBoost paper - time complexity analysis

Question: I'm reading through the XGBoost paper and I'm confused by the subsection of 4.1 titled "Time Complexity Analysis". Here the authors assert that the exact greedy algorithm with $K$ trees, a maximum depth of $d$ per tree, and $\|\mathbf{x}\|_0$ "non-missing entries in the training data", using the original sparse-aware algorithm, incurs a time complexity of
$$O(Kd\|\mathbf{x}\|_0\log n).$$
The first 3 factors make sense to me (the $Kd\|\mathbf{x}\|_0$ part) - I'm interpreting it as:

There's $K$ trees, giving you a factor of $K$
At each of the $d$ layers of each tree, you need to scan through $\|\mathbf{x}\|_0$ block entries to find the optimal split. (My understanding is that $\|\mathbf{x}\|_0$ is the total number of nonzero feature values, aggregated across all feature columns and all training examples. This would mean that each block consists of $3\|\mathbf{x}\|_0$ numbers in CSC format.) This gives a factor of $d\|\mathbf{x}\|_0$.

However, I'm not sure what $n$ is supposed to signify (it's not specified in this section of the paper) or where the $\log n$ factor comes from. Based on earlier usage in the paper, I'd assume that $n$ is the number of training examples, but it's not clear to me how that results in a multiplicative $\log n$ increase in time complexity of the exact greedy algorithm.
Does anyone understand how the authors got to this time complexity? Any help would be much appreciated.
Comment: Does $||x||_0$ show the total number non-missing items? If there are no missing features $||x||_0 = m n$?
Answer: Answered my own question - turns out I misread the paper.
The original sparse greedy algorithm doesn't use block storage. Thus to find the optimal split at each node, you needed to re-sort the data on each column. This ends up incurring a time complexity at each layer that is very crudely approximated by $O(\|\mathbf{x}\|_0 \log n)$: basically, say you have $\|\mathbf{x}\|_{0i}$ nonzero entries for each feature $1 \le i \le m$; then at each layer you're sorting lists, each of length at most $n$, whose lengths sum to $\sum_{i=1}^m \|\mathbf{x}\|_{0i} = \|\mathbf{x}\|_0$, which can't take more than $O(\|\mathbf{x}\|_0 \log n)$ time. Multiplying by $K$ trees and $d$ layers per tree gives you the original $O(Kd\|\mathbf{x}\|_0 \log n)$ time complexity.
On the other hand, with the block structure, since the data is already pre-sorted by every column at the start, you don't need to re-sort at each node, as long as you keep track at each node of which data points have made it to that node. As the authors note, this brings the complexity down to $O(Kd\|\mathbf{x}\|_0)$ (since the optimal splits at each layer can now be found via a single scan over the block) plus whatever the cost of preprocessing is (the authors claim it to be $O(\|\mathbf{x}\|_0 \log n)$, which makes sense).
Comment: I just wish someone would build an online complexity calculator for all these popular algos like XGBoost


treatment effect on unbalanced panel data

Question: I have an unbalanced dataset that contains movie sales data along with some of the characteristics of the movies for several years.
One treatment (event) happened in the society in a specific year in between.
Now, I want to investigate using R software whether this treatment affected sales of the movies with some special characteristics or not. My issue is that as I checked a lot of difference-in-differences (DiD) and fixed effects (FE) models, the treatment population is the same before and after the treatment which is not in my case. The movies released before the event are completely different from the ones released after that event, and I am looking for any change in the coefficient of a movie character on its sale.
Kindly, would you please guide me to which model or R package should I use?
Comment: That's exactly what repeated cross-section means. Now you might worry about compositional changes over time (say if some periods may have lots of comedies and other don't), but your controls may take care of some of that.
Comment: Welcome. Two things. First, is there a group (society) that did not experience the event (i.e., a control group)? Second, panel data is not required in DiD settings. Could you describe your treatment in a bit more detail?
Comment: You can do DID in a repeated cross section setting.
Comment: @ThomasBilach thank you for your comment. yes, the non US movies does not experience the treatment. I have movies descriptive stats of weekly box office for US and NonUs movies, including its genre, production year, the distributor, production budget, number theatres and its total duration and the duration of violence scenes. so, I want to check whether the coefficient for the violence science proportion (on movies sales) changed after 2011 on US movies or not.
Comment: @DimitriyV.Masterov from which r package?
Comment: You can just use regression. Not special package is needed.
Comment: thanks, doesn't it matter that my population (movies) varies before and after the treatment? I mean that there's no after treatment box office data for movies released before the treatment time and vice versa.
Comment: thanks a lot Dimitriy :)
Answer: Take note of the comments by @DimitriyV.Masterov. Difference-in-differences works well with repeated cross-sections data. Your equation would look something like the following:
$$
y_{ist} = \alpha + \gamma S_s + \lambda A_{t} + \delta (S_s \times A_{t}) + \theta X_{ist} + \epsilon_{ist}
$$
where $y_{ist}$ denotes movie $i$ in society $s$ at time period $t$. The variable $S_s$ is a treatment dummy equal to 1 for your non-US society, 0 otherwise. If I understood you correctly, you only observe movie sales within two societies (i.e., US and non-US) across time. $A_{t}$ is a post-treatment indicator for all years after 2011 in both treatment and control groups. $X_{ist}$ is a vector of all your individual level (i.e., movie-level) covariates and/or any other time-varying controls at the society level. Often times we think about this equation as only applying to panel data. This is not true, though. In your setting, all that's required is random samples of movies from your societies before and after treatment.
If you think about it, you could create a pseudo-panel by aggregating your data up to the society level. In other words, in each society $s$ and time period $t$ you calculate the proportion of sales for violent Sci-Fi movies. It wasn't clear what your outcome is but you get the general idea. Given the richness of your data at the individual (movie) level, there is no requirement to aggregate your data up to the level of the society. I only noted this to help with your intuition. Again, all that's necessary is a random collection of movies from societies in the periods pre- and post-shock. Moreover, this shock (i.e., treatment) is usually at some higher, well-defined level of aggregation. In your case, your treatment influences all non-US movies so you can certainly proceed with the classical difference-in-differences approach.
As for question regarding software, models such as the one suggested earlier can be run in base R using the lm() function (e.g., lm(y ~ S*A + X, data = ...). Everything should run smoothly once the variables are coded properly. If you want to extend this model to more societies (i.e., regions, counties, cities, etc.) and/or time periods and also introduce group and/or time fixed effects, then you may want to look into the plm or lfe packages.
Comment: The `lfe` package was recently removed from the CRAN repository. You can go to the daily [Microsoft's CRAN snapshots](https://blog.revolutionanalytics.com/2019/05/cran-snapshots-and-you.html) site to help find archived CRAN pages. I'm not really sure why it was taken down.
Comment: I got it, thanks for your comprehensive response :)


How to run angular tests using protractor with safari under ubuntu?

Question:
I want to know if there is a good way to test angular application using protractor with safari.
capabilities: [
{
browserName: 'safari',
seleniumAddress: 'http://localhost:4444/wd/hub',
},
],
I got this message when i tried to run my spec:
E/launcher - SessionNotCreatedError: Unable to create new service: SafariDriverService
I'm using ubuntu 18.04.5 / protractor 7.0.0 / webdriver-manager 12.1.7
Answer: Unfortunately you need MacOS host to run safari browser. Thats the only OS were Safari can be installed.
Answer: A workaround is https://www.browserstack.com/ with this tool you can control the real MacOS machine and any browser you want (including older versions)
When configured correctly, tests can be ran from any OS including Ubuntu
BUT the license is pricey
Try to lookup cheaper analogues, is you have budget for any license at all


how to get target of an angular event?

Question: Maybe I'm looking in the wrong place. I just want to manipulate the DOM of the target of an event. As you can see, I'm mashing some jquery in there.
How does angular give me the DOM object so I can manipulate its relatives? i.e. what are the valid properties of ev? I would have thought that ev.target or ev.currentTarget gave me the DOM object.

  Go
Tooltip

$scope.rollover = function(ev){
  $(ev).parents('.table-cell').css('overflow','visible');
  $(ev).find('.tip').show();
};

Answer: ng-mouseover="rollover(this)"
this keyword refers to scope. You need to pass $event in your rollover function then use $event.target.
Go
Tooltip

But you should create directive if you want to manipulate DOM.
Go
Tooltip

app.directive("myDir", function () {
  return {
    link: function (scope, element, attrs) {
        $(element).on("mouseover", function () {
            $(element).parents('.table-cell').css("background-color", "yellow");
            $(element).find('.tip').toggle();
        });
    }
  };
});

DEMO
Comment: I see. Thank you.

Wow that was surprisingly tough to solve.
I guess because I'm not doing it the angular way, using a directive.

(In fact, I can probably simply use bootstrap's tooltip, if I could get it to work...)

how to get target of an angular event?


How to create an embedded Queue list for discord bot the updates

Question: I am making a discord bot that plays music. Currently, the embedded list works fine and every time I add a song to the queue, the list deletes itself and creates a new embedded queue list updated with the new song. However, I can't figure out how to make this queue list update itself when I use the skip button I have implemented (I'm new to programming).
Example of how it works now:

Pressing the button skips the song, but as stated before, how would I refresh the list every time I press the button?
const ytdl = require('ytdl-core');
const ytSearch = require('yt-search');
process.setMaxListeners(1000000000000);
const { MessageEmbed } = require('discord.js');

ffmpeg_options = {
    'options': '-vn',
    "before_options": "-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5"
}

//Global queue for your bot. Every server will have a key and value pair in this map. { guild.id, queue_constructor{} }
const queue = new Map();

module.exports = {
    name: 'play',
    aliases: ['skip', 'stop'], //We are using aliases to run the skip and stop command follow this tutorial if lost: https://www.youtube.com/watch?v=QBUJ3cdofqc
    cooldown: 0,
    description: 'Advanced music bot',
    async execute(message, args, cmd, button, skip, client, Discord){

        //Checking for the voicechannel and permissions (you can add more permissions if you like).
        const voice_channel = message.member.voice.channel;
        if (!voice_channel) return message.channel.send('You need to be in a channel to execute this command!');
        const permissions = voice_channel.permissionsFor(message.client.user);
        if (!permissions.has('CONNECT')) return message.channel.send('You dont have the correct permissions.');
        if (!permissions.has('SPEAK')) return message.channel.send('You dont have the correct permissions.');

        //This is our server queue. We are getting this server queue from the global queue.
        const server_queue = queue.get(message.guild.id);
        let checker = false;

        if (cmd === 'stop' && !server_queue){
            return message.channel.send("The bot is not in the channel, you dont have to stop him.");
        }

        //If the user has used the play command
        if (cmd === 'stop') stop_song(message, server_queue);
        else if(skip === true) {
          skip_song(message, server_queue);
        }
        else if (cmd === message.content){
            //if (!args.length) return message.channel.send('You need to send the second argument!');
            let song = {};

            //If the first argument is a link. Set the song object to have two keys. Title and URl.
            if (ytdl.validateURL(args[0])) {
                const song_info = await ytdl.getInfo(args[0]);
                song = { title: song_info.videoDetails.title, url: song_info.videoDetails.video_url }
                message.delete({ timeout:1000 })
            } else {
                //If there was no link, we use keywords to search for a video. Set the song object to have two keys. Title and URl.
                const video_finder = async (query) =>{
                    const video_result = await ytSearch(query);
                    return (video_result.videos.length > 1) ? video_result.videos[0] : null;
                }

                const video = await video_finder(args.join(' '));
                if (video){
                    song = { title: video.title, url: video.url }
                } else {
                     message.channel.send('Error finding video.');
                }
                message.delete({ timeout:1000 })
            }

            if (skip === true && server_queue) {

            }
            //If the server queue does not exist (which doesn't for the first video queued) then create a constructor to be added to our global queue.
            if (!server_queue){

                const queue_constructor = {
                    voice_channel: voice_channel,
                    text_channel: message.channel,
                    connection: null,
                    songs: []
                }

                //Add our key and value pair into the global queue. We then use this to get our server queue.
                queue.set(message.guild.id, queue_constructor);
                queue_constructor.songs.push(song);

                //Establish a connection and play the song with the vide_player function.
                try {
                    const connection = await voice_channel.join();
                    queue_constructor.connection = connection;
                    video_player(message.guild, queue_constructor.songs[0]);
                } catch (err) {
                    queue.delete(message.guild.id);
                    message.channel.send('There was an error connecting!');
                    throw err;
                }
            } else {
              server_queue.songs.push(song);
              message.channel.bulkDelete(2)
                .then(messages => console.log(`Bulk deleted ${messages.size} messages`))
                .catch(console.error);

                //where I actually make the embeded queue list
                const queueList = server_queue.songs.map((song, i) => `[${++i}] - ${song.title}`);
                const queueEmbed = new MessageEmbed()
                 .setDescription(queueList);
                 return message.channel.send(queueEmbed, button);

            }
        }

    }

}

const video_player = async (guild, song) => {
    const song_queue = queue.get(guild.id);

    //If no song is left in the server queue. Leave the voice channel and delete the key and value pair from the global queue.
    if (!song) {
        song_queue.voice_channel.leave();
        queue.delete(guild.id);
        return;
    }
    const stream = ytdl(song.url, { filter: 'audioonly' });
    song_queue.connection.play(stream, { seek: 0, volume: 0.5 })
    .on('finish', () => {
        song_queue.songs.shift();
        video_player(guild, song_queue.songs[0]);
    });
    //await song_queue.text_channel.send(` Now playing **${song.title}**`)
}

const skip_song = (message, server_queue) => {
    if (!message.member.voice.channel) return message.channel.send('You need to be in a channel to execute this command!');
    if(!server_queue){
        return message.channel.send(`There are no songs in queue `,);
    }
    server_queue.connection.dispatcher.end();
    //message.delete({ timeout:20000})
}

const stop_song = (message, server_queue) => {
    if (!message.member.voice.channel) return message.channel.send('You need to be in a channel to execute this command!');
    server_queue.songs = [];
    server_queue.connection.dispatcher.end();
    //message.delete({ timeout:20000})
}

Answer:  return message.channel.send(queueEmbed, button);

That line above returns a Promise which resolves to a Message object. Change it to something like this:
const embeddedMessage = await message.channel.send(queueEmbed, button);
return embeddedMessage;

So when a user clicks the skip button you can simply call
embeddedMessage.edit(your_new_embed, button)

Comment: This does not help. The OP does not have a problem with this statement, and this is just a callback, and also, `return` does not require `await`. It has the same result.
Comment: Thank you for the advice, but as mythical stated, I tried this and got the same result unfortunately.


how to submit a text field input from a user in a views filter form to a javascript ?

Question: I am trying to fetch the user entered text value precisely a zip code which will be taken as input in the views exposed filter form and this value should be sent to the Java script function and I have this java script function which calculates the required LAT LON based on the zipcode and gives back the result.
The problem is I can use the drupal_add_js function to add the js file and also pass the value of zip code (I think so I am not sure though) I am wondering if I can send the zipcode value entered by the user only on form submit to the js file i.e can I send the value of zipcode to the js file only when the user submits the views exposed filter form by pressing the apply button?
I know that we can add a js file and send the values using drupal_add_js function but just not sure if this can be synced with the form submission button ?
 how can this be done?  please help me in this, any pointers in this regard are appreciated.
Answer: got it I never used Jquery before and jquery is magic it when used with drupal behaviours as magic just listens to click or any event you want it to listen to and passes the value and you can retrieve it using $(# id of the field).val()[.val() is a function to retrieve the value].


Infinite $\sigma$-algebras are uncountable proof error

Question: I was posed this problem this morning, and I thought I had come up with a nice solution. I went to the internet to see if anyone proved it the same way I did, and found that there appears to be one standard proof that, while not hard to follow, is more involved than what I thought of. Usually when I'm in this situation I soon realize I have made an error, but I cannot find what's wrong with my idea. It goes as follows:
Let $\mathcal{M}$ be an infinite $\sigma$-algebra on the (infinite) set $X$. Suppose $\mathcal{M}$ is countable. Then we can list the elements of $\mathcal{M}$ as $A_1,A_2,...$. Let $A=\bigcup_{A_n\subset X} A_n$. That is, $A$ is the union of all sets in $\mathcal{M}$ that are proper subsets of $X$. Since this is a countable union, $A\in \mathcal{M}$. Therefore for some $j\in\mathbb{N}$ we have $A=A_j$, and $A_N=A_j$ for all $N\geq j$. In which case $\mathcal{M}$ is finite, contradicting our hypothesis. Thus, if $\mathcal{M}$ is infinite it must be uncountable infinite.
Answer: For one, $X$ is one of the sets $A_j$ so the union is $X$. But that does not mean that the tail of the sequence is all $X$, they don't hva eany effect on the union as soon as $X$ is in it..
Answer: I don't believe there is any reason why we would get $A_N = A_j$ for all $N \geq j$.  The listing $A_1, A_2, \ldots$ was essentially arbitrary.
You might try to fix this by asking that if $i < j$ then $A_i \subset A_j$, but there's no reason why such an arrangement should be possible (in general $\subset$ is not a linear order on subsets of $X$).
Answer: Even if you consider only the members of $\mathcal{M}$ which are proper subsets of $X$, the union will be $X$.
Since $\mathcal{M}$ is infinite, there exists $A\in\mathcal{M}$ such that $A\ne\emptyset$ and $A\ne X$. But then $X\setminus A\in\mathcal{M}$ and therefore the union you're considering is $X$.


TFS2010: Single Server Deployment wizard, Bad sharepoint URLs

Question: I just installed TFS2010, and set it up with the single server wizard. It installed me Sharepoint Services an let everything working pretty well.
But, the sharepoint URLs it generates from the Server name "server". As my setup is without a domain, the URLs work okay only from the server computer, not from the others.
I have to give access to LAN clients, and Internet Clients, both connected thought my Public Ip.
How can I change those sharepoint IPs from TFS to be generated From the IP, not from the Server's name??
Thanks in advance
Answer: Sharepoint is simply an ASP.Net web application sitting on IIS so all the configuration for host headers etc can be added in IIS itself - if you have multiple instance of sharepoint running on the server, you'll have to add URL's using the sharepoint configuration site but most stuff can be tweaked through IIS (IP's its listening on etc)
If you not on an domainan and want people to have access to the site though you'll have to add your machines IP to the DNS server that you clients are using
Comment: Yes but, the issue is that TFS shows on the Web Access Page, a link to a "Project Portal", with the URL as this: http://server/ProjectName
I need it to be: http://someIP/projectName
Comment: This can be changed in the TFS Administration once its setup.
Open TFSAC then click on "sharepoint web applications" select your web app and click "change" then change the hostnames to your servers IP instead. Easy fix :)


AnHarmonic oscillator for pendulum

Question: The ODE for ''small angles'' of a pendulum is given by $\frac{d^2\theta}{dt^2}+\frac{g}{l}\theta=0$. Without small angle approximations the right ODE is:

$$\frac{d^2\theta}{dt^2}+\frac{g}{l}\sin{\theta}=0 \tag{1}$$

Is there a closed form of $\theta(t)$ for $(1)$?
Answer: Yes but only in terms of special functions; see Equation (31) of this paper, given as
$$ \theta(t) = 2\arcsin\left\{\sin\frac{\theta_{0}}{2}\,\operatorname{sn}\left[K\left(\sin^{2}\frac{\theta_{0}}{2}\right) - \omega_{0}t;\,\sin^{2}\frac{\theta_{0}}{2}\right]\right\}$$
where $\theta_{0}$ is the initial angle, $\omega_{0} = \sqrt{g/l}$, $K$ is the elliptic integral of the first kind, and $\operatorname{sn}$ is a Jacobi elliptic function.

AnHarmonic oscillator for pendulum


Need some explanation with CSS font declaration

Question: I have this font declaration:
font: 700 16px/36px HelveticaNeue,Roboto,sans-serif;

But if I want to specify each value separately I can to this:
font-weight:700;
font-family: HelveticaNeue,Roboto,sans-serif;

But how to separately value 16px/36px specify in that case?
Answer: font-size:16px;
line-height:36px;

Answer: The CSS property you are looking for is line-height, so to properly replicate the shorthand with separate values you would do the following:
font-weight:700;
font-size:16px;
line-height:36px;
font-family: HelveticaNeue,Roboto,sans-serif;


Is a decision stump a linear model?

Question: Decision stump is a decision tree with only one split. It can also be written as a piecewise function.
For example, assume $x$ is a vector, and $x_1$ is the first component of $x$, in regression setting, some decision stump can be
$f(x)= \begin{cases}
 3& x_1\leq 2 \\
 5     & x_1 > 2 \\
   \end{cases}
$
But is it a linear model? where can be written as $f(x)=\beta^T x$? This Question may sound strange, because as mentioned in the answers and comments, if we plot the piecewise function it is not a line. Please see next section for why I am asking this question.

EDIT:

The reason I ask this question is logistic regression is a (generalized) linear model and the decision boundary is a line, also for decision stump. Note, we also have this question: Why is logistic regression a linear model? . On the other hand, it seems not true that decision stump is a linear model.

Another reason I asked this is because of this question:
In boosting, if the base learner is a linear model, does the final model is just a simple linear model?
where, if we use a linear model as a base learner, we get nothing more than linear regression. But if we select base learner as a decision stump, we are getting very interesting model.

Here is one example of decision stump boosting on regression with 2 features and 1 continuous response.
Comment: @hxd1011 important to distinguish between the decision boundary and the decision function here
Comment: If you draw a line in the plane (say y = 0), and take *any* function $f(x)$, then $g(x, y) = f(x)$ will have contour lines which are actual lines (parallel to the $y$ axis), but it will *not* be a linear function.
Comment: This is a strange question. Can you plot the function from your example (which is equal to 3 for x<2 and 5 for x>2)? Look at it -- is it a straight line? If it is not a straight line, then it is not a linear function.
Comment: @amoeba, i agree with you, the function plot is a not linear. I think my question is confusing also because it is not really clear what is "linear model"
Comment: Why would you consider it to be linear..?
Comment: I could call it a 1000th order polynomial with all orders from 1 to 1000 equal zero.  I could call it a zero-order (aka constant) model and it would more succinctly communicate the key features.  A classic tree is piecewise constant.  The trivial tree, a stump, is a single split in the space where the model on one side is constant and the the other is a different constant.  It isn't globally constant, but it isn't poly1 either.  The "cubist" library in R fits with actual linear (poly1) models instead of constant models.  You might try that.
Comment: If we pretend like we know that the split happens when x1 is equal to 2 then we can write it as a linear model.  Decision trees/stumps don't do this though - that part is estimated. So if we are considering the split value to be estimated then it isn't a linear model.
Comment: Generalized Linear Model =/= Linear Model
Answer: No, unless you transform the data.
It is a linear model if you transform $x$ using indicator function:
$$
x' = \mathbb I \left(\{x>2\}\right) = \begin{cases}\begin{align} 0 \quad &x\leq 2\\ 1 \quad &x>2 \end{align}\end{cases}
$$
Then $f(x) = 2x' + 3 = \left(\matrix{3 \\2}\right)^T \left(\matrix{1 \\x'}\right)$
Edit: this was mentioned in the comments but I want to emphasize it here as well. Any function that partitions the data into two pieces can be transformed into a linear model of this form, with an intercept and a single input (an indicator of which "side" of the partition the data point is on). It is important to take note of the difference between a decision function and a decision boundary.
Comment: It *is* a linear model in the parameters.  And it *is* affine linear in the dummy $x'$.
Comment: I'd suggest you edit your answer to include "no, unless you transform the data" (from your last comment) into it. Currently your opening words are "It is a linear model", and people can get confused.
Comment: @MichaelM how is it linear in the parameters? I assume by "parameters" you mean the choice of $x \leq 2$
Comment: @hxd1011 the answer is "no, unless you transform the data"
Comment: "transform" is tricky, i think neural network (MLP) is non-linear, but after transform, it is linear..
Comment: You can easily prove an only if: a decision stump is linear only if the domain of $x$ (the variable being split on) contains exactly one or two values.
Comment: so, the answer is it is not a linear model?
Comment: so, your answer to this question is "yes"? http://stats.stackexchange.com/questions/215696/do-all-machine-learning-algorithms-separate-data-linearly/215763#215763
Comment: I should have been more correct and precise. I had in mind a true model of the form $\alpha + \beta x'$, which would be linear in $\alpha, \beta $.
Comment: @amoeba done, good idea
Comment: "No unless you transform the data" is a meaningless statement.
Answer: Answers to your questions:

A decision stump is not a linear model.
The decision boundary can be a line, even if the model is not linear. Logistic regression is an example.
The boosted model does not have to be the same kind of model as the base learner. If you think about it, your example of boosting, plus the question you linked to, proves that the decision stump is not a linear model.
Answer: This answer is more verbose than is needed to just answer the question.  I hope to provoke some comments from real experts.
I once was in a court room and the judge asked (for good reason in context) , if we call a dog's tail a leg, does that mean a dog has 5 legs ?  So what is a linear model ?
In the context of statistics I've been told by an expert that a linear model means a statistical model constructed from a set of functions $ f_1, f_2, \ldots, f_n$ of the form $ y = \sum a_i f_i $ with the important constraint that the error terms are independent and normally distributed.  With that definition, one can't say if your model is linear because you have given no information about the error term. If one drops the error term constraint, then it is tautologically linear in the function you give or in the function ssdecontrol gives.  However naively, in the context of this question, that may be unsatisfactory.  Any function can be considered as the basis of a linear in that sense.  That is because any space of functions can be turned into a vector space of functions.
If you are asking on the nose, that is mathematically, if your function linear, then the answer is no.  A linear function is one whose graph is a straight line, while clearly your function doesn't have that property. In answer to the question you pose at the end, that is can one find $\beta$ so that $ f(x) = \beta^{T} x $ , then no.
Any function of the class you give would satisfy $f(x+y) = f(x) + f(y) $ for any (real) numbers $x$ and $y$. Notice that your function satisfies $ f(1.5) = 3$ and $f(3) = 5$, so $ f(3) \neq f(1.5) + f(1.5)$ as would be required if your function was of the form $f(x) = \beta^T x$.  Notice the class you propose for linear functions is a sub-class of what are usually called linear functions.
Comment: Linearity has nothing to do with error terms. It has to do with the fact that it consists of a _linear combination of the parameters_. This represents a straight line in 2D space (but more generally represents a plane).
Comment: @ssdecontrol - I can only tell you that a probability Ph.D. (and a student of Kolmogorov at that) insisted to me that the term 'linear model', when used in statistics, included a statement about the error term.  I'm actually very interested in how common this view might be.  Linear has many meanings.  For example, if one has an equation in N space $f(x) = 0 $, then we could say it is linear if the zero set is a hyperplane. Of course that would mean we could write $ f(x) = a_0 + \sum_{i=1}^{i=N} a_ix_i $ .  However the function would be linear $\iff a_0 = 0$ i.e. $f(x+y) = f(x) + f(y) $.
Comment: if that's what he insists, then that's his opinion and not some kind of hard fact. As far as I'm aware, there is no rigorous accepted definition for a "linear model", nor is there a need for one in my mind. For me, the fact that there is an error term involved just turns the model from a "linear model" to a "statistical linear model". I don't see anything inherently linear about her terms, nor do I see anything inherently statistical about linear models.
Comment: IMO insisting on the presence of an error term just discounts what, say, and engineering or physicist might deem a "linear model" of a deterministic physical process.

Is a decision stump a linear model?


Why exactly is normality an assumption in a T-test but not a Wilcox rank sum/Mann Whitney U test when obtaining a p-value?

Question: In addition to the question, please do correct anything below that I have incorrect.
I understand how the test statistics for a t-test and WRS/MWU test are calculated. In a t-test, $t=\frac{\bar x_{1}-\bar x_{2}}{SE}$, where the formula for $SE$ comes from a normal approximation, which is justified by the central limit theorem.
Even though the central limit theorem is used to justify generating a sampling distribution using a normal approximation, I understand from other posts on this site that the CLT isn't always guaranteed to generate a normal sampling distribution from non-normal date. It is my understanding that this is why normality is still a standard assumption for a t-test.
On the other hand, the calculation of $W$ or $U$ in a WRS/MWU is obviously a little more involved but does not involve any invocation of a distribution up to this point. Thus, why this test is considered distribution free.
However, once you try to calculate a p-value from a WRS/MWU test, I am confused as to how it remains different from a t-test in it's reliance on normality.
Just looking at wikipedia, the process for generating a p-value from $U$ simply involves generating a Z-score from the standard form $Z = \frac{U - m_{u}}{\sigma_{u}}$, where $m_{u} = \frac{n_{1}n_{2}}{2}$ and $\sigma_{u} = \sqrt{\frac{n_{1}n_{2}(n_{1} + n_{2}+ 1)}{12}}$, the latter two equations being derived from a normal approximation, when the sample sizes are "large enough." This sounds a lot like the CLT to me.
At this point, the steps for obtaining a p value seem the same between a t-test and a WRS/MWU test:

The t-score in the t-test and z-score in WRS/MWU are both obtained using sampling distributions calculated from normal approximations
These scores are then used on sampling distributions (t-distribution vs. normal distribution) to obtain the probability of an equal or more extreme score given the null hypothesis

Therefore, given that:

Both these test utilize normal approximations to obtain p-values
That the justification for both of these approximations seem to come from the CLT
The reason that normality is an assumption for the t-test is because it is still possible for the CLT to be affected by non-normal data

Why is normality not also an assumption for p-values calculated from a WRS/MWU  test?
Thanks for your help!
Comment: In its original form, the t-test does not require a normal approximation. Its distribution is derived from the fact that the variables are **exactly** normal. If that is not the case then it only holds asymptotically, because of the CLT as you say.
Answer: First, let us address the problem with the link you posted. Assume there is a distribution with finite mean ($\mu$), variance ($\sigma^{2}$ and skew (third central moment = $\rho$). The Berry-Essen theorem states that
$|F_{N}(x) - \Phi(x)| \leq \frac{0.8 \rho}{\sigma^{3} \sqrt{N}}$
where $F_{N}(x)$ is the CDF obtained after a standard CLT-type scaling of a sum. Notice that for a fixed mean and variance, the larger the skew, the slower the convergence to normality. The author in the previous account uses loose parsing when he says it 'fails'. What he means is normality like behavior is not achieved. (Heavy tailed distributions have high skew)
For the Mann-Whitney test, the reason for non-normality is as $N \rightarrow \infty$, $\sigma_{U}$ and $\mu_{U}$ blow up. Finiteness is required for the CLT. When this condition is violated, you can end up converging in distribution to something else (see the section titled 'Relation to the law of large numbers' in  http://en.wikipedia.org/wiki/Central_limit_theorem)
Comment: $\rho$ in Berry-Esseen is not the third central moment\* (nor strictly speaking is third central moment the same as skewness; since skewness is unit free but third central moment is in the original variable's units cubed). Look carefully at the definition of $\rho$ here: https://en.wikipedia.org/wiki/Berry-Esseen_theorem


MongoDB, WriteConcern: need some clarification

Question: I need some help to clarify the concept of WriteConcern
I'm using MongoDb 4.0.2 (with a replicaset) and java-mongo-driver 3.8.1
I already added on mongo configuration the last default write concern with
{
    "w": "majority",
    "wtimeout": 5000
}

In code-side, when can I use the ack response from the database?
I found that the library, when you use delete or update, return an object of Result (as DeleteResult) that contain a function wasAcknowledged() for take the result of delete/update on the majority replica in the set.
But I'm not able to find a similar Result for all insert function. Someone could explain me how to use WriteConcern in order to avoid data loss?
My goal is catch an Exception when insert/write/update on replica-set going in error
Hope the question is clear, I'm waiting for your answer. Thanks
Just to know, is enough set this preferences on db, or I have to set the write-concern preferences also on my code?
Answer: You can catch MongoWriteConcernException.  Below are the source codes and comments for insertOne.
/**
 * Inserts the provided document. If the document is missing an identifier, the driver should generate one.
 *
 *
Note: Supports retryable writes on MongoDB server versions 3.6 or higher when the retryWrites setting is enabled.

 * @param document the document to insert
 * @throws com.mongodb.MongoWriteException        if the write failed due some other failure specific to the insert command
 * @throws com.mongodb.MongoWriteConcernException if the write failed due being unable to fulfil the write concern
 * @throws com.mongodb.MongoException             if the write failed due some other failure
 */
void insertOne(TDocument document);

Comment: Note that it is an uncheck method of an interface `public interface MongoCollection`.  You don't have to add the throws clause to the interface if it's a `RuntimeException`.
Comment: Okay, I've already seen this docs, in this case my question is: why is not throwed on method signature? @simagix
Comment: effectively is true, as user I would have found it useful. Btw, thank you!


Is it possible to model list / dict like elements in HTML forms?

Question: I wrote a python script that is creating switch configs out of .yaml files.
And I'm not sure how to create a web form that fits my needs.
I'm completely open on how to accomplish this. I just need a way to post values to my python script.
My HTML Form looks like this:
<form method="POST">
<input type="text" name="port"></input>
<input type="text" name="port.mode"></input>
</form>

The posted data gets into Flask like this:
[('port', 'Port1'), ('port.mode', 'Access')]
I'd like to have the data like this:
{ "ports": { "port1": {"mode": "Access"}}}
++Update
I'm already using Jinja to create the template.
Sample Jinja Template:
{%- for name,options in ports.items() %}
interface {{ name }}
{%- if options.mode == 'access' %}
switchport mode access
{% else %}
switchport mode trunk
{% endif %}

My Problem is between the HTML form and the template engine. I'm not sure how to model my HTML form to fit my needs.
2 ways I can think of accomplish this.
 1. Alter the HTTP Post request in Javascript before submitting
 2. Writing a sever-side python code to bring the HTTP Posted data into the correct form for my jinja Template.
But I' completely open to the method I use. I'm not limited to flask, jinja and python.
Comment: Use jinja or some templating engine, they support loops natively, which is what you are trying to do.
Also if you are using flask they commonly go toghether take a look http://jinja.pocoo.org/
Comment: What do you mean exactly by "posting values from a web form to a Python script"?  I think you would use JavaScript for something like this, assuming the Python script resides on the web server.  Or are you trying to generate HTML dynamically based on the .yaml configuration file?
Comment: He is already using flask, he needs to pass the form to the template renderer, it is pretty common practice but not that straightforward
Comment: Hi,
thanks for your comments.
I edited my answer to clarify it. The problem ist not creating the template. My problem is to getting the HTTP posted data into the form i want.
Answer: is this a solution?
In [1]: x = [('port', 'Port1'), ('port.mode', 'Access')]
In [2]: {x[0][0]: {x[0][1]: {x[1][0]: x[1][1]}}}
Out[2]: {'port': {'Port1': {'port.mode': 'Access'}}}

Comment: Hi Paul,

yes it's kind of what I'm trying to accomplish. But I got nearly 100 different attributes. And I'm trying to avoid mapping every single attribute by hand.


when going to admin giving error site url does not exist

Question: When i am trying to go admin path in the it is giving me error that saying that site matching query does not exist this never happens to me before

from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('accounts/', include('allauth.urls')),
    path('', include('core.urls', namespace='core'))
]

here is my main project url
from django.urls import path
from .views import (
    ItemDetailView,
    CheckoutView,
    HomeView,
    OrderSummaryView,
    add_to_cart,
    remove_from_cart,
    remove_single_item_from_cart,
    PaymentView,
    AddCouponView,
    RequestRefundView
)

app_name = 'core'

urlpatterns = [
    path('', HomeView.as_view(), name='home'),
    path('checkout/', CheckoutView.as_view(), name='checkout'),
    path('order-summary/', OrderSummaryView.as_view(), name='order-summary'),
    path('product/<slug>/', ItemDetailView.as_view(), name='product'),
    path('add-to-cart/<slug>/', add_to_cart, name='add-to-cart'),
    path('add-coupon/', AddCouponView.as_view(), name='add-coupon'),
    path('remove-from-cart/<slug>/', remove_from_cart, name='remove-from-cart'),
    path('remove-item-from-cart/<slug>/', remove_single_item_from_cart,
         name='remove-single-item-from-cart'),
    path('payment/<payment_option>/', PaymentView.as_view(), name='payment'),
    path('request-refund/', RequestRefundView.as_view(), name='request-refund')
]

my app urls
Answer: It is most likely something to do with your urls. Please double check you have included the admin route in the urls and make sure there are no path conflicts. For more help, you should paste your code of urls or settings where you think the error might be.
This is the admin path for reference:
from django.contrib import admin

urlpatterns = [path("admin/", admin.site.urls)]

Comment: I have edited the question with urls
Comment: Try adding `django.contrib.sites` in django `INSTALLED_APPS` and also add `SITE_ID=1` in your django setting file.
Comment: adding site_is=1 works but can you explain why this happen improve the answer and i will accept this thank you man
Comment: SITE_ID means in the database table you create a object where you will add site name according to your app like apple.com.
Here is the reference if you need more information, hope this helps!(https://docs.djangoproject.com/en/3.1/ref/contrib/sites/#enabling-the-sites-framework)


connected components algorithm in pig

Question: we looked around for a simple algorithm to find connected components in a graph where the diameter is sometimes large (the largest components can sometimes reach 1m).
We found lots of very sophisticated MR algorithms:

http://codingwiththomas.blogspot.de/2011/04/graph-exploration-with-hadoop-mapreduce.html
http://blog.piccolboni.info/2010/07/map-reduce-algorithm-for-connected.html
http://chasebradford.wordpress.com/2010/10/23/mapreduce-implementation-for-union-find/

What's wrong with a very simple algorithm:

foreach component, generate flatten(nodes_bag) as node, node_with_the_smallest_id as comp_id;
group by node
filter nodes with more than one comp_id, and build "update big comp_id to small comp_id" table
update all nodes with a big comp_id to the corresponding new small comp_id, and mark them as dirty

and continue to the next iteration with these dirty nodes...
what are we missing here?
Comment: How many iterations could this end up taking?
Comment: log(largest_diameter) iterations
Answer: Isn't your proposed algorithm quadratic?  Tarjan's connected components algorithm is linear.
Comment: What do you mean by quadratic? IMO The number of iterations would be log(largest_diameter), agree?
Comment: Sorry, I misread the start of your algorithm, where you say "foreach _component_ ...".
Answer: Ok. The reason we can't use this very simple algorithm is that it has a bug = the build "update big comp_id to small comp_id" stage could be recursive. E.g, when there are 3 components from the previous iteration:
A->{1,2}
B->{2,3}
C->{3,4}

The group by and filter would build us this translation table:
A->B
B->C

And this would cause the number of iterations to be linear(biggest diameter) in some cases = long chains like in this mini example would take a long time to converge.

connected components algorithm in pig


what is making try: exit early?

Question: in the following function, what is making try: exit early? If I put the same code outside a def block it works fine.
tiles = ['095D', '094M']
in_file = 'in_file'
out_file = 'out_file'
expression = ''' "FIELDNAME" LIKE 'STUFF' '''

def foobar(in_file, out_file, expression):
    print in_file, out_file, expression
    try:
        print 'this is trying'
        #pretty print tile list, from http://stackoverflow.com/questions/2399112/python-print-delimited-list
        tiles = ','.join(map(str,tiles))
        print 'made it past tiles!'
        print 'From %s \nselecting %s \ninto %s' % (in_file, tiles, out_file)

    except:
        print 'Made it to the except block!'

foobar(in_file, out_file, expression)

Results:
D:\> python xx-debug.py
in_file out_file  "FIELDNAME" LIKE 'STUFF'
this is trying
Made it to the except block!

Results with the same code not in a def:
this is trying
made it past tiles!
From in_file
selecting 095D,094M
into out_file

Comment: @aaronasterling  "Pokemon Exception Handling - Gotta catch'em all!"
Comment: You should not `except:` without specifying an exception. That will also catch things like KeyboardInterrupt which is almost never what you want.
Comment: easy there, beginners will do such things.
Answer: The reason it's not working is because you defined tiles in the global scope. In the function you're assigning to tiles. This makes tiles a local scoped name in the function. This, in turn, means that the code in the function won't look for tiles in the global scope at all.
In the assignment, you're trying to get tiles (this is before it has been assigned locally.) This results in an exception being raised, since you tried to access an unassigned local variable.
The quick fix is to use global:
...
def foobar(in_file, out_file, expression):
    global tiles
    ...

As others said, don't just catch exceptions without doing something with them. When debugging code, you want exceptions to be thrown so you can find and fix the cause! Either remove the try...except, or make the except take an exception and print useful information about it, like this:
try:
    ...
except Exception, e:
    print 'Oh noes!', e

This may be a lot to read, but you will understand Python much better if you do read it:
http://docs.python.org/reference/executionmodel.html
It explains how Python handles variable definitions in the module scope and function scopes, etc. It also covers exceptions.
Comment: the real except block is `except:\n\tprint gp.GetMessages()\n` [(ref)](http://webhelp.esri.com/arcgiSDEsktop/9.3/body.cfm?tocVisable=1&ID=924&TopicName=Error%20handling%20with%20Python) I took it out when building the simplest possible reproduction of the error. Thanks for cluing me in to what was going on.
Answer: Exception output:
Traceback (most recent call last):
  File "sof.py", line 19, in <module>
    foobar(in_file, out_file, expression)
  File "sof.py", line 11, in foobar
    tiles = ','.join(map(str,tiles))
UnboundLocalError: local variable 'tiles' referenced before assignment

Now, this happens because tiles is actually defined in the global space.  So, your function should look like this:
def foobar(in_file, out_file, expression):
    global tiles
    ...

Comment: You should probably explain that it's happening because `tiles` is defined locally in the function, which means that any global variable will be ignored unless you use the `global` keyword. This error would happen even if you didn't define `tiles` globally.
Comment: how did you get that UnboundLocalError message? All I get is silence.
Comment: `except` swallows the exception. Without `except` you would get that error.
Answer: That's an interesting bug you have. So there's a module-scoped tiles outside the function, and since you're not using global, you're creating a new tiles variable inside the function. This is fine. Or it would be fine, except that it appears (when I mess around in interactive Python) that the lvalue of the statement (the tiles on the left) being local, makes the entire statement think that any reference to tiles means the local one. So in that map construct, instead of using the module tites it uses the local one, except the local one doesn't exist yet.
This may be a bug in Python, but probably it's as-intended.
Comment: Not a bug, it's very well-defined in fact. There's a difference between global and local variables. It's cases like these that you have the `global` keyword for. :)
Comment: Right but you'd think it would evaluate the right side first using (as far as it knows at that point) global scope, then create a local variable and assign to that. It appears that Python scans ahead to see if a local variable by that name is ever created.

what is making try: exit early?


How to get the value of a button inside click eventListener

Question: I'm trying to show the value of a button when that button is clicked. If I write the code for this inside the eventListener the alert pops up but there is no text showing.
I have tried moving the alert above the eventListener and inside the for loop and this shows the correct values when the page loads.
HTML for buttons:
<button class="buttonA" value="A">A</button>
<button class="buttonB" value="B">B</button>
<button class="buttonC" value="C">C</button>
<button class="buttonD" value="D">D</button>
<button class="buttonE" value="E">E</button>
<button class="buttonF" value="F">F</button>
<button class="buttonG" value="G">G</button>
<button class="buttonH" value="H">H</button>
<button class="buttonI" value="I">I</button>
<button class="buttonJ" value="J">J</button>

Javascript:

Answer: You need to to add a parameter argument e.g. e to the event listener or use arguments[0].
Then you can use e.target.value to get the value of the button.

document.querySelectorAll('button[class^=button]').forEach(button => {
  button.addEventListener('click', onClickEvent);
});

function onClickEvent(e) {
  try {
    alert(e.target.value); // or `arguments[0].target.value`
  } catch (error) {
    console.log(error);
  }
}
<button class="buttonA" value="A">A</button>
<button class="buttonB" value="B">B</button>
<button class="buttonC" value="C">C</button>
<button class="buttonD" value="D">D</button>
<button class="buttonE" value="E">E</button>
<button class="buttonF" value="F">F</button>
<button class="buttonG" value="G">G</button>
<button class="buttonH" value="H">H</button>
<button class="buttonI" value="I">I</button>
<button class="buttonJ" value="J">J</button>

Update
Here is a more elegant modern way that uses object destructuring and a shared class.

const onClickEvent = ({ target: { value } }) => {
  try {
    alert(value);
  } catch (error) {
    console.log(error);
  }
};

document.querySelectorAll('.alert-button').forEach(btn => {
  btn.addEventListener('click', onClickEvent);
});
html, body {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}

body {
  display: flex;
  justify-content: center; /* horizontal alignment */
  align-items: center;     /* vertical alignment   */
}

.alert-button {
  margin: 0.25em;
  font-family: monospace;
}
<button class="alert-button" value="A">A</button>
<button class="alert-button" value="B">B</button>
<button class="alert-button" value="C">C</button>
<button class="alert-button" value="D">D</button>
<button class="alert-button" value="E">E</button>
<button class="alert-button" value="F">F</button>
<button class="alert-button" value="G">G</button>
<button class="alert-button" value="H">H</button>
<button class="alert-button" value="I">I</button>
<button class="alert-button" value="J">J</button>


Angular 7 - Comparar Listas

Question: Eu tenho duas listas no meu componente.
listPermissoesOfUser: UsuarioPermissoes[];
listAnotherPermissoes: UsuarioPermissoes[];

E quando eu carrego a pagina, eu exibo elas em um picklist do primeNG (Dois containers). Só que quando eu carrego, eu preciso comprar as duas listas, o que tiver na listPermissoesOfUser não pode aparecer na listAnotherPermissoes
A função que carrega as informações da página está abaixo:
loadPage() {
    this.idUser = this.route.snapshot.params.id;

    this.route.paramMap.pipe(
      switchMap(params => this.usuarioPermissoesService.getPermissoesOfUser(+params.get("id")))
    ).subscribe(
      (listPermissoesOfUser: UsuarioPermissoes[]) => {this.listPermissoesOfUser = listPermissoesOfUser; },
      (error) => {console.log(error); }
    );
    this.usuarioPermissoesService.getListFuncionalidades().subscribe(
      (listAnotherPermissoes: UsuarioPermissoes[]) => {this.listAnotherPermissoes = listAnotherPermissoes},
      (error) => {console.log(error); }
    );
    //Funcionalidades que o usuario tem, não aparece na listAnotherPermissoes

  }

Alguma ideia de como fazer isso?
Comment: Criei outra pergunta: [MySql - Comparar duas listas e filtrar informações](https://pt.stackoverflow.com/questions/380092/mysql-comparar-duas-listas-e-filtrar-informa%C3%A7%C3%B5es)
Comment: Não é melhor isso já vir pronto no retorno, ou seja, da onde vem essas informações? não seria de lá, fiz formatada todas as informações.
Comment: Você quer dizer no banco de dados? Qual seria o comando para um `SELECT` que faça uma busca e não retorne as linhas em comum com o "**id_usuario**"?
Comment: Então o seu problema não é ai e sua pergunta acaba sendo outra ...
Comment: Eu perguntei isso porcausa que já tentei fazer isso no banco de dados, e a consulta não dá certo por causa das poucas Fk's nas tabelas. Já tentei usar LEFT JOIN, Where IS NOT, <> entre outros, ma snenhum atende ao que preciso, por isso acho mais fácil tentar fazer no Angular ou, talvez, no PHP.
Comment: Olha se esse pesquisa não está dando certa se deve ter problemas no seu back end e ai fica complicado dizer qualquer coisa.
Comment: Eu tenho dois SELECT's no DB, um deles busca as permissões do usuário; a outra busca todas as permissões. No segundo SELECT, eu teria que fazer uma busca que, por causa da maneira como está ligada as tabelas, não teria com fazer em uma consulta, teria que fazer duas consultas separadas e trazer o resultado delas, mas se eu fizer isso, teria que fazer no PHP. Fazer no PHP ou no Angular daria no mesmo.
Comment: Se quiser, posso postar as tabelas pra vocês analisarem melhor a situação.
Comment: Tem que ser em outra pergunta, porque, ficaria duas perguntas.
Answer: Você poderia fazer assim:
var x = [1,2,3];
var y = [3,4,6];
x.filter(x => y.find(y => y == x)); // [3]

Ele vai resultar em um array composto pelas duplicatas, assim você pode remover estes na lista de todas permissões.
var x = [1,2,3];
var y = [3,4,6];
x.filter(x => y.indexOf(x) < 0); // [1,2]

Angular 7 - Comparar Listas


Implications of bounded support on regression equation

Question: I am reading an academic paper right now, and the following claim is made without much explanation:

Suppose that the joint distribution $F(\textbf y)$ of the $n \times 1$ random vector  $\textbf Y$ has a density  $f(\textbf y )$ with bounded support $\mathscr Y$. Without loss of generality assume that the true coefficient equals $\beta_0=0$ and that  $\sigma^2=1.$
Because $\textbf Y$ has bounded support $\mathscr Y$ there is a set $B \subset \mathbb R^m$ such that  $|\textbf y' \Sigma^{-1}\textbf X \beta|<1$ for all $\beta \in B $ and $\textbf y \in \mathscr Y$.

I  don't understand how we are able to conclude that $|\textbf y' \Sigma^{-1}\textbf X \beta|<1$. Can anyone explain how this follows from the assumption of bounded support?
Comment: I think you will need some bounds on the elements of $X$ also. Did they assume so?
Comment: The proof treats X as fixed. I suppose you could regard $Y=X \beta + e$ as a constraint.
Comment: It is page 9 here: https://www.ssc.wisc.edu/~bhansen/papers/gauss.pdf
Answer: Because $Y$ has bounded support $\mathcal S,$ the set $\mathcal S \Sigma^{-1}X = \{y\Sigma^{-1}X\mid y\in\mathcal S\}$ is bounded, too.   Let $c\gt 0$ be any upper bound of the norms of its elements.
For $\beta\in\mathbb{R}^m$ and $y\in\mathcal S,$ the Cauchy-Schwarz Inequality implies
$$|y \Sigma^{-1}X\beta| \le ||y\Sigma^{-1}X||\,||\beta|| \le c||\beta||.$$
We may therefore choose for $B$ any nonempty subset of ball of radius $1/c$ in $\mathbb{R}^m,$ for which $\beta\in B$ implies
$$||y\Sigma^{-1}X||\,||\beta|| \le (c)(1/c) = 1,$$
QED.

This demonstration began with the claim that when $\mathcal S \subset \mathbb{R}^n$ is bounded and $A = \Sigma^{-1}X = (a_{ij})$ is any $n\times m$ matrix, then $\mathcal S A \subset \mathbb{R}^n$ is bounded, too.  To see this, let $s$ be any upper bound for the norms of elements of $\mathcal S$ and let $a$ be an entry in $A$ with largest absolute value.  Then for any $y\in \mathcal S,$ write $y_k$ for an entry of largest absolute value and--noting that $|y_k|^2 \le \sum_i |y_i|^2 = ||y||^2$--observe that
$$||yA||^2 = \sum_{i=1}^m \left(\sum_{j=1}^n y_j a_{ji}\right)^2 \le \sum_{i=1}^m\left(\sum_{j=1}^n |y_k| |a|\right)^2 = mn||y||^2|a|^2  \le mns|a|^2 ,$$
demonstrating $mns|a|^2$ is an upper bound for $\mathcal S A.$
This should make it clear that $\mathbb{R}^m$ and $\mathbb{R}^n$ can be replaced by any dual normed linear spaces and $A$ need only be a bounded linear operator for the result to be true.  In other words, everything results from the fact that finite matrices represent bounded operators.

Finally, the converse is not always true.  A characteristic counterexample has $\mathcal S = \{(x,0)\} \subset \mathbb R^2$ and $B \subset \{(0,y)^\prime\}\subset \mathbb R^2$ (with $\Sigma^{-1}X$ the identity transformation).  By construction, $|y\beta|=0$ for all $y=\mathcal S$ and all $\beta\in B,$ even though $\mathcal S$ is unbounded.
This helps show that the point to the claim in the question is that a bounded set $\mathcal S$ is bounded in all possible directions (as represented by $\Sigma^{-1}X\beta$).  In the counterexample, $\mathcal S$ is bounded in some special directions (namely, those spanned by the vector $(0,1)^\prime$) but not in all of them.  When the image of the map $\beta \to \Sigma^{-1}X \beta$ does not span all possible directions (that is, $\Sigma^{-1}X$ is not of full rank), such counterexamples can always be constructed.
Answer: A try a proof using the notation of the linked paper A Modern Gauss-Markov Theorem.  As this is a finite-sample result, $n$ is a fixed integer $\Sigma>0$ is a known, fixed, positive-definite (posdef) matrix, and the design matrix $X$ is assumed known, so a constant. The range of $Y$, $\mathscr{Y}$, is a bounded set, so contained in a compact set, so we can assume it is compact.
Interest is in the expression $y^T \Sigma^{-1} X\beta$ which we can write as the continuous function
$$ T(y,\beta)=y^T \Sigma^{-1} X\beta $$ it is not necessary to include the constants as arguments. For each $\beta$, the image set $T(\mathscr{Y},\beta)$ is a compact set, by continuity of $T$. It is clear that $T(\mathscr{Y}, 0)=\{ 0 \}$ so the condition $ | T | < 1$ is fulfilled at least for one $\beta$, namely $\beta=0$.
Now write
$$ \sup_{\beta\in B,~ y \in \mathscr{Y}} = | T(\mathscr{Y}, B) |
$$ Now fix one nonzero $\beta$ and observe that
$$
| T(\mathscr{Y}, c\beta)| = |c| |T(\mathscr{Y}, \beta) |
$$ so is increasing linearly along $\beta$-rays from the origin. If this last value is $| c | G >0$, the condition $ |T | <1 $ will be fulfilled for $ |c| <  G^{-1}$.
We can conclude that the sought-for set $B$ is non-empty, larger than just $\{ 0 \}$, and it is in fact a cone.