Seaborn hexbin plot with marginal distributions for datetime64[ns] and category variables

Question: I'm uploading a spreadsheet from excel to a dataframe. In this table, I am only interested in two columns. The first column is the date and time in the format %Y-%m-%d %H-%M-%S. The second column is a categorical variable, namely the type of violation (for example, being late).
There are few types of violations in total. About 6-7 types.
Using the command df.info () you can make sure that the dataframe for the available columns has the datatime64[ns] type for the date and time column and the category type for the column with the types of violations.
I would like to use hexbin plot with marginal distributions from the seaborn library (https://seaborn.pydata.org/examples/hexbin_marginals.html ). However, the simple code available at the link above is not so simple for a variable with categories and time.
import seaborn as sns
sns.set_theme(style="ticks")

sns.jointplot(x=df['incident'], y=['date-time'], kind="hex", color="#4CB391")

The compiler reports TypeError: The x variable is categorical, but one of ['numeric', 'datetime'] is required
I understand that either a numeric variable or a date-time variable is needed for the ordinate axis. Conversion does not solve the problem.
This error can be reproduced using
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd

from datetime import datetime

ndf = pd.DataFrame({'date-time': ['2021-11-15 00:10:00','2021-11-15 00:20:00'], 'incident': ['a','b']})
print(ndf)

sns.set_theme(style="ticks")

sns.jointplot(data=ndf, x='incident', y='date-time', color="#4CB391", hue=ndf['incident'] )

plt.show()

Question. How to get a plot looks like seabron style
Comment: This kind of plot doesn't make much sense for purely categorical data.  If there is some "natural" mapping from categories to numbers, you could try something like `df['incident']=df['incident'].map({'a': 1, 'b': 3, 'c':2,...})`.
Answer: Based on the example cited in the question as the desired graph style, change the data on the x-axis to date/time data, convert it to a date format that can be handled by matplotlib, and place it as a tick on the x-axis. The ticks are placed by converting the time series back to its original format. Since the date and time overlap, the angle of the text is changed. Also, please judge for yourself the points that @JohanC pointed out.
import numpy as np
import seaborn as sns
sns.set_theme(style="ticks")
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas as pd

rs = np.random.RandomState(11)
x = rs.gamma(2, size=1000)
date_rnge = pd.date_range('2021-11-15', '2021-11-16', freq='1min')
y = -.5 * x + rs.normal(size=1000)

g = sns.jointplot(x=mdates.date2num(date_rng[:1000]), y=y, kind="hex", color="#4CB391")
g.ax_joint.set_xticklabels([mdates.num2date(d).strftime('%Y-%m-%d %H:%M:%S') for d in mdates.date2num(date_rng[:1000])])

for tick in g.ax_joint.get_xticklabels():
    tick.set_rotation(45)


ProFTPD AuthOrder inside VirtualHost is being ignored

Question: I am trying to configure proftpd 1.3.5b.
What I would like to achieve is simple: only one VirtualHost, users will log in based on AuthUserFile and not based on /etc/passwd.
The problem is that all the authentication related configuration inside a VirtualHost is being ignored (although the VirtualHost is being loaded successfully).
Here is my config:
<VirtualHost 10.11.12.162>
......
        DefaultRoot             /disk/ftp/
        AuthOrder mod_auth_file.c
        AuthUserFile                    /etc/proftpd/misc/ftp.users
        AuthGroupFile                   /etc/proftpd/misc/ftp.group
....
</VirtualHost>

Users can successfully login based on /etc/passwd and ftp.users is being ignored.
DefaultRoot is also ignored.
If I place everything in proftpd.conf, outside the virtualhost, is working.
According to documentation, AuthOrder & AuthUserFile is supported inside VirtualHost directive:
http://www.proftpd.org/docs/directives/linked/config_ref_AuthUserFile.html
Any idea what is causing this problem?
Best Regards
Comment: What IP address/DNS name are your clients using to connect to your FTP server?
Comment: They are using a hostname, ftp.mydomain.com, that resolves to IP 10.11.12.162
Comment: Hmm.  What happens if you use `SocketBindTight on`?  The behavior you describe usually happens when the client connects to an IP/port different from your ``, _or_ when the default "server config" server is already listening on that IP/port.
Comment: Yes, probably this is the case.  is totally ignored. Even ServerName is displayed from the proftpd.conf instead of the VirtualHost!
Comment: proftpd is behind a NAT. The public IP is resolving to a DNS name and receiving connections from public IPs.  is not working. And ServerAlias is not implemented: fatal: ServerAlias: not yet implemented
Answer: Reviving this necro post to mention that we had the same issue when we tried to do the exact same thing.
Adding AuthPAM off inside the VirtualHost fixed our problem.


How to read GitHub payload in groovy Jenkinsfile?

Question: I have a web hook configured in my GitHub org that triggers a Jenkins pipeline every time a new repo is created. What I am trying to do is get some of the values from the payload which triggers the job and use them in a script within the pipeline.
One such example would be the repo name, for instance the payload looks something like this:
{
"action": "created",
"repository": {
    "name": "my-new-repo"
    [...]
  }
[...]
}

I tried assigning the repository["name"] value to a variable in the Jenkinsfile but that did not seem to work:
pipeline{
  environment {
    REPO_NAME = $.repository.name
  }
[...]
}

Also tried it with quotes and some other ways in formatting but still could not get it to be assigned to the REPO_NAME variable.
Comment: What Plugin did you use to configure the Webhook?
Comment: generic-webhook-trigger plugin
Answer: Here is an example of how to Read different attributes from the Webhook request.
pipeline {
  agent any
  triggers {
    GenericTrigger(
     genericVariables: [
      [key: 'REPO_NAME', value: '$.repository.name', defaultValue: 'null'],
      [key: 'PR_TYPE', value: '$.pullrequest.type', defaultValue: 'null']
     ],
     causeString: 'Triggered By Github',
     token: '12345678',
     tokenCredentialId: '',
     printContributedVariables: true,
     printPostContent: true,
     silentResponse: false
    )
  }
  stages {
    stage('ProcessWebHook') {
      steps {
          script {
            echo "Received a Webhook Request from Guthub."
            echo "RepoName: $REPO_NAME"

          }
      }
    }
  }
}


Create a menu under a menu?

Question: I am wondering if there is a way to have a menu under another menu in Drupal 7. Let's say I have a new menu called Blah and I want it to appear under the main menu item Top.
So I would end up with
<code>Main Menu

|- Top
|---Blah Menu
|------ Blah Menu Item
</code>
Answer: The obvious approach would be to have your main-menu built with sub-links.
If that doesn't work, you could:
edit your template to call the new menu right underneath the first.
or
add the new menu to the same block as your first menu (you may want to define new block areas for this)

Create a menu under a menu?


How to find the minimum value of c?

Question:
In this book, the answer is not clear. What will be the method to find the value of c?
Comment: You're asked to indicate your thinking so far. With no effort at a solution, a post like this will be closed.
Comment: Substitute $k$ into the pmf and compute $P(X\leq x)$; it should take a few seconds in your head to find the first $x$ that satisfies the condition.
Answer: As mentioned in the book, the answer is reached through trial and error.
So, first we take c=1 and calculate P(X<=1):
P(X<=1) = P(X=0) + P(X=1) = 0 + 1/10 = 0.1
Then, we take c=2 and calculate P(X<=2):
P(X<=2) = P(X=0) + P(X=1) + P(X=2) = 0 + 1/10 + 2/10 = 3/10 = 0.3
Then, we take c=3 and calculate P(X<=3):
P(X<=3) = P(X=0) + P(X=1) + P(X=2) + P(X=3) = 0 + 1/10 + 2/10 + 2/10 = 5/10 = 0.5
Then, we take c=4 and calculate P(X<=4):
P(X<=4) = P(X=0) + P(X=1) + P(X=2) + P(X=3) + P(X=4) = 0 + 1/10 + 2/10 + 2/10 +3/10 = 8/10 = 0.8
So, for c=4 we can see that P(X<=4) < 0.5

How to find the minimum value of c?


Elementary integral of exponential

Question: I am keen to find the simplest expression for the following integral:
$$
\int_{-1}^{1}(x^{2}-1)^{n}e^{i\sigma x}dx
$$
where $n$ is a non-negative integer. The best I could come up with involves binomially expanding out the first part and using
$$
\int_{-1}^{1}x^{k-1}e^{i\sigma x}dx=\frac{i^{k}}{\sigma^{k}}(\Gamma(k,i\sigma)-\Gamma(k,-i\sigma))
$$
where $\Gamma$ is the incomplete Gamma function. Please help me find a better way to obtain a nicer expression?
Comment: This appears to be a restricted version of the Fourier transform ${\cal F}_{[-1,1]}(f)(\sigma/2\pi)$ where $f(x)=(x^2-1)^n$. I don't think there's a particularly nice expression for it.
Answer: Note that $e^{i\sigma x}=\cos(\sigma x)+i\sin(\sigma x)$, and therefore, by considering just the even part (the integral is taken over the symmetric interval $[-1,1]$), we find
$$I_n=\int_{-1}^{1}(x^{2}-1)^{n}e^{i\sigma x}dx=\int_{-1}^{1}(x^{2}-1)^{n}\cos(\sigma x)dx.$$
According to $I_n= \int_{-1}^1 (1 − x^2 )^n \cos(ax) \mathrm dx$, for $\sigma\not=0$, $I_n$ satisfies the following recurrence for $n\geq 2$,
$$I_n = -\frac{2n}{\sigma^2}\left((2n-1)I_{n-1}+(2n-2)I_{n-2}\right).$$
I don't think there is a simple closed formula for $I_n$ when $\sigma\not=0$.
On the other hand, when $\sigma=0$, it is easy to see that
$$I_{n}=\int_{-1}^{1}(x^{2}-1)^{n}dx=-\frac{2n}{2n+1}I_{n-1}=2\frac{(-2)^{n} n!}{(2n+1)!!}.$$
Answer: There are several direct solutions for
$$I_n=\int_{-1}^{1}(x^{2}-1)^{n}\,e^{i\sigma x}\,dx$$
The first one is not very pleasant
$$I_n=(-1)^n \sqrt{\pi }\, \Gamma (n+1) \,\, _0\tilde{F}_1\left(;n+\frac{3}{2};-\frac{\sigma^2}{4}\right)$$ where appears the   regularized confluent hypergeometric function.
Fortunately, it also write
$$I_n=(-1)^n \sqrt{\pi }\, \Gamma (n+1)\, \left(\frac{2}{\sigma }\right)^{n+\frac{1}{2}}\,J_{n+\frac{1}{2} }(\sigma )$$ where appears the Bessel function of the first kind.
This even works for non-integer values of $n$ (leading to comlex values).
If $\sigma$ is small, you have nice expansions
$$I_n=(-1)^n \sqrt{\pi }\,\frac{  \Gamma (n+1)}{\Gamma \left(n+\frac{3}{2}\right)}\Bigg[1-\frac{\sigma ^2}{2 (2 n+3)}+\frac{\sigma ^4}{8 (2 n+3) (2 n+5)}-\frac{\sigma ^6}{48
   ((2 n+3) (2 n+5) (2 n+7))}+O\left(\sigma ^8\right) \Bigg]$$

Elementary integral of exponential


404 when serving static files with docker+nginx+django/angularjs

Question: I'm following the configuration given at this repository. I decided to keep my docker configuration and actual code in separate repositories - I'd clone the code repo using the Dockerfile. I'm using a docker-machine (locally, using the Virtualbox driver) and docker-compose setup.
The code repo's directory structure is roughly as follows -:
|-- bower.json
|-- CONTRIBUTORS
|-- defsec
|   |-- defsec
|   |   |-- aws_settings.py
|   |   |-- heroku_settings.py
|   |   |-- __init__.py
|   |   |-- settings.py
|   |   |-- urls.py
|   |   |-- views.py
|   |   `-- wsgi.py
|   |-- manage.py
|   |-- quiz_restful
|   |   |-- __init__.py
|   |   |-- permissions.py
|   |   |-- serializers.py
|   |   |-- services.py
|   |   |-- tests.py
|   |   `-- views.py
|   `-- users
|       |-- __init__.py
|       |-- models.py
|       |-- permissions.py
|       |-- serializers.py
|       `-- views.py
|-- extras
|-- gulpfile.js
|-- package.json
|-- Procfile
|-- README.md
|-- requirements.txt
|-- scripts
|   `-- postInstall.sh
|-- static
|   |-- javascripts
|   |   |-- app.js
|   |   |-- controllers
|   |   |   `-- controllers.js
|   |   |-- directives
|   |   |   `-- directives.js
|   |   `-- services
|   |       `-- services.js
|   |-- partials
|   |   |-- eval.html
|   |   |-- exam.html
|   |   |-- exam-partials
|   |   |   |-- exam-view.html
|   |   |   `-- sidebar.html
|   |   |-- login.html
|   |   `-- register.html
|   `-- stylesheets
|       `-- styles.css
|-- templates
|   |-- index.html
|   |-- javascripts.html
|   |-- navbar.html
|   `-- stylesheets.html

The docker-compose.yml file is almost the same as that of the repository I listed above, with the minor difference that I mounted django on volume .:/root - without which a [8] System error: no file or directory error was being thrown. This was probably because /usr/src/app does not exist before the cloning (for reference, this is the original file). The Dockerfile (for the django service) has the following -:
FROM ubuntu:14.04

ENV DJANGO_CONFIGURATION Docker

# First, we need to get git, and clone our repository
# Additionally, get everything else here too, such as nodejs and npm

RUN apt-get update
RUN apt-get install -y ca-certificates git-core ssh nodejs npm python-pip libpq-dev python-dev
RUN ln -s /usr/bin/nodejs /usr/bin/node

ENV HOME /root

# Add custom ssh keypair - usually Bitbucket deployment keys
ADD ssh/ /root/.ssh/

# Fix permissions
RUN chmod 600 /root/.ssh/*

# Avoid first connection host confirmation
RUN ssh-keyscan bitbucket.org > /root/.ssh/known_hosts

# Clone the repo
WORKDIR /usr/src/app
RUN git clone email@example.com:username/defsec-exam-app.git

# Install requirements
WORKDIR /usr/src/app/defsec-exam-app
RUN pip install -r requirements.txt
RUN npm install -g bower
RUN bower --allow-root install

# Remember to perform migrations on your own, and also create DB when needed.
# S3 Storage
...

# DB Settings
...

WORKDIR /usr/src/app/defsec-exam-app/defsec
CMD ["gunicorn", "defsec.wsgi", "-w", "2", "-b", "0.0.0.0:8000", "--log-level", "-"]

And finally, the nginx.conf to serve the static files is as follows -:
worker_processes 1;

events {

    worker_connections 1024;

}

http {

    server {
        listen 80;
        server_name example.org;

        access_log /dev/stdout;
        error_log /dev/stdout info;

        location /static/ {
            alias /usr/src/app/defsec-exam-app/static;
        }

        location /static/javascripts/ {
          default_type text/javascript;
          alias /usr/src/app/defsec-exam-app/static/javascripts/;
        }

        location /static/stylesheets/ {
          default_type text/css;
          alias /usr/src/app/defsec-exam-app/static/stylesheets/;
        }

    location /static/bower_components/ {
      alias /usr/src/app/defsec-exam-app/static/bower_components/;
    }

        location / {
            proxy_pass http://django:8000;
            proxy_set_header   Host $host;
            proxy_set_header   X-Real-IP $remote_addr;
            proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header   X-Forwarded-Host $server_name;
        }
    }
}

However, I cannot get nginx to serve the static files at all - all of them return a 404. I wondered if the linking between the nginx and django container services (as defined in docker-compose.yml) was incorrect, but it doesn't seem like it. I also inspected the /etc/hosts file in the nginx container, for linking creates hostfile entries.
172.17.0.136    151ca02e891a
127.0.0.1   localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
172.17.0.134    defsecdocker_django_1 eb900ed9600c
172.17.0.135    defsecdocker_nginx_1 eec99206076a
172.17.0.134    django eb900ed9600c defsecdocker_django_1
172.17.0.134    django_1 eb900ed9600c defsecdocker_django_1
172.17.0.135    nginx eec99206076a defsecdocker_nginx_1
172.17.0.135    nginx_1 eec99206076a defsecdocker_nginx_1
172.17.0.116    defsecdocker_postgres_1
172.17.0.134    defsecdocker_django_1
172.17.0.135    defsecdocker_nginx_1.bridge
172.17.0.136    defsecdocker_nginx_run_10.bridge
172.17.0.135    defsecdocker_nginx_1
172.17.0.136    defsecdocker_nginx_run_10
172.17.0.116    defsecdocker_postgres_1.bridge
172.17.0.134    defsecdocker_django_1.bridge

I'm not sure if this is right, as there are only 3 containers but a hell lot of entries in the hosts file, some of which are duplicates. This is reproducible behaviour - I get this exact file each time I build and run the container using docker-compose. The docker-compose logs for nginx confirm the 404s.
Any pointers would be greatly appreciated.
Answer: It would appear that the docker-compose configuration was not correct. The reason nginx threw those 404s was because it had no access to /usr/src/app/defsec-exam-app/static.
Here is the correct docker-compose config -:
# Nginx
nginx:
    build: ./nginx
    volumes_from:
        - django
    links:
        - django
    ports:
        - "80:80"

# This defines a service for the Django app
# Will include the Angular frontend
django:
    build: .
    volumes:
        - .:/root
        - /usr/src/app
    expose:
        - "8000"
    links:
        - postgres

# This defines a service for the Postgres database
postgres:
    image: postgres:latest

volumes_from gets the volumes from the django service. And I have exposed usr/src/app as a volume. This seems to do the trick. I'm open to suggestions, if any!
Additionally, here is the new nginx config -:
worker_processes 1;

events {

    worker_connections 1024;

}

http {

    server {
        listen 80;
        server_name example.org;

        access_log /dev/stdout;
        error_log /dev/stdout info;

        location /static/ {
            alias /usr/src/app/defsec-exam-app/static;
        }

        location /static/javascripts/ {
          default_type text/javascript;
          alias /usr/src/app/defsec-exam-app/static/javascripts/;
        }

        location /static/stylesheets/ {
          default_type text/css;
          alias /usr/src/app/defsec-exam-app/static/stylesheets/;
        }

    location /static/bower_components/ {
      types {
        text/css css;
        text/javascript js;
      }
      alias /usr/src/app/defsec-exam-app/static/bower_components/;
    }

    location /static/partials/ {
      types {
        text/html html;
      }
      alias /usr/src/app/defsec-exam-app/static/partials/;
    }

    location /static/admin/ {
          alias /usr/src/app/defsec-exam-app/static/admin/;
    }

    location /static/admin/css {
      default_type text/css;
      alias /usr/src/app/defsec-exam-app/static/admin/css;
    }

    location /static/admin/js {
      default_type text/javascript;
      alias /usr/src/app/defsec-exam-app/static/admin/js;
    }

    location /static/admin/img {
      types {
        image/png png;
        image/jpeg jpg;
      }
      alias /usr/src/app/defsec-exam-app/static/admin/img;
    }

        location / {
            proxy_pass http://django:8000;
            proxy_set_header   Host $host;
            proxy_set_header   X-Real-IP $remote_addr;
            proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header   X-Forwarded-Host $server_name;
        }
    }
}

Note: I had to add django admin css/js/img to the docker/deployment repository separately, so that django admin works properly. (A simple ADD command in the django Dockerfile does the trick)


how to create more then one thread at a time

Question: Can anyone tell me how to create more then one thread at a time
is there any such ?
like:
pthread_create (thread, attr, start_routine, arg)
should give me more than one thread at a time.
Comment: Just call `pthread_create` as many times as you need threads.
Comment: If accessing a function multiple times is a problem, something is wrong with this function.
Comment: What kind of error do you expect from that? Please give us the whole story, as what you said until now doesn't make much sense.
Comment: Why do you want that?
Comment: I want one or more threads to access one function at a time.so that i get an error
Comment: Hmmm...OK.I should write a testcase where i should create some threads and make those threads to call one function. if more then one thread tries to access that function at a time, it should crash or should create some problem. to create that scenario i want to know to how to make two threads to access same function at a time
Comment: @ deviantfan.yes. I have fixed that problem in function using mutex. but i want to produce the fault through tests
Comment: @user3913114 I don´t understand why anyone really *want* to make such bugs, but: a) Get rid of that mutex again, because it will prevent such bugs (usually a good thing, but in your case...). And with an usual OS, you can´t just say "I wan´t this two threads to access it on the same time, now". You could try to execute this function many times, like 1 million etc., and with a bit of luck some if the accessess will not work correctly. (however, this doesn´t mean they will crash immediately. There are many kinds of potential problems).
Answer: Your actual question seems to be more like "How can I make sure my tests exercise a potential race condition by calling the same function at the exact same time?"
The answer is, you sort of can't.  Imagine your test runs on a single-processor machine.  There's no way for the function to be called twice at the same time (but it could partially execute once then start again in the other thread).
Think about other ways to test for race conditions.  At the more formal end of the spectrum, you can use tools like Spin and Promela to verify such things, but it's a lot more involved than spawning two threads in a unit test.  For more, see here: http://lwn.net/Articles/243851/
A less formal way is to call your function in some way where it will sleep in its middle when the first thread calls it.  Then you're very likely to see execution continue with the second call while the first one is suspended.  But be mindful of wasting time on this approach, because it mostly validates that you've written the test correctly, and may not prove anything much about the thread safety of your code in practice.


Map a collection using Mapstruct and specify method for a single instance?

Question: i have a mapstruct class with the following functions
    abstract CustomApplication convertCustomApplication(ApplicationDTO source);

    abstract RegularApplication convertRegularApplication(ApplicationDTO source);

    @Named("mainConverter")
    public App mainConverter(ApplicationDTO source) {
        return source.isCustom() ? convertCustomApplication(source) : convertRegularApplication(source);
    }

    //@Mapping( qualifiedByName = "mainConverter")
    abstract public List<App> convertApplications(List<ApplicationDTO> applicationList);

Both CustomApplication and RegularApplication extend App, so I have mainConverter that calls the converter according to the isCustom field.
The problem is that when i try to build this i get an ambiguous mapping error, because mainConverter, convertRegularApplication, and convertCustomApplication all map from ApplicationDTO to App (or subclass of App). So convertApplications does not know what to use.
Is there any way i can explicitly tell it to call mainConverter? I wanted something like @Mapping( qualifiedByName = "mainConverter") that I put above convertApplications, (but it doesnt work of course)
Does anyone know how I can do this? Thanks!
Answer: In order to achieve what you are looking for you will need to use IterableMapping#qualifiedByName.
This property is meant to enhance the selection for the list.
e.g.
    abstract CustomApplication convertCustomApplication(ApplicationDTO source);

    abstract RegularApplication convertRegularApplication(ApplicationDTO source);

    @Named("mainConverter")
    public App mainConverter(ApplicationDTO source) {
        return source.isCustom() ? convertCustomApplication(source) : convertRegularApplication(source);
    }

    @IterableMapping(qualifiedByName = "mainConverter")
    abstract public List<App> convertApplications(List<ApplicationDTO> applicationList);

Alternative solution
You are making your mainConverter qualified method. However, it looks like that method already redirects to the more specific method. Therefore I would suggest to qualify the other two methods and remove the qualification from the mainConverter. Then you won't need to do anything for the iterable mapping.
e.g.
    @Named("customApplication")
    abstract CustomApplication convertCustomApplication(ApplicationDTO source);

    @Named("regularApplication")
    abstract RegularApplication convertRegularApplication(ApplicationDTO source);

    public App mainConverter(ApplicationDTO source) {
        return source.isCustom() ? convertCustomApplication(source) : convertRegularApplication(source);
    }

    abstract public List<App> convertApplications(List<ApplicationDTO> applicationList);


Jacobi identity in associative algebra as Lie algebra

Question: In page 2 of Hans Samelson's Notes on Lie Algebras, the text gives an example of Lie algebra $A_L$.

Let $A$ be an algebra over $\mathbb{F}$ (a vector space with an associative multiplication $X\cdot Y$). We make $A$ into a Lie algebra $A_L$ (also called $A$ as Lie algebra) by defining $[X,Y]=X\cdot Y-Y\cdot X$. The Jacobi identity holds; just "multiply out".

Multiplying out the Jacobi identity and using associativity of $\cdot$, we have
$X\cdot Y\cdot Z-X\cdot Z\cdot Y+Y\cdot Z\cdot X-Y\cdot X\cdot Z+Z\cdot X\cdot Y-Z\cdot Y\cdot X=0$.
Assuming only associativity, I can't see why this holds.
Answer: The Jacobi identity will give the following:
$$[[x,y],z]+[[y,z],x]+[[z,x],y]=\\(xy-yx)z-z(xy-yx)+(yz-zy)x-x(yz-zy)+(zx-xz)y-y(zx-xz)$$
See if you can multiply now, and use associativity to show that the above expression vanishes.
Comment: Oh whoops, in $[X[YZ]]$ I just expanded Jacobi on the inner one, but thought the outer one is just multiplication. Thanks!


Most efficient way to find whether matching row exists in MySQL table

Question: I have two MySQL tables:
tableCollections: collection INT INDEX NOT NULL, item VARCHAR INDEX NOT NULL -- Contains items belonging to a collection. About 1,000 items per collection id.
tableData: item VARCHAR INDEX NOT NULL, itemAttr1 VARCHAR, itemAttr2 VARCHAR --
Contains all possible items and their data. About 10,000 items.
I want to select all items from tableData that are contained in a collection.
The three ways I know of doing this are either with a subquery:
SELECT * FROM tableData
WHERE item IN (SELECT item from tableCollections WHERE collection = 3)

Or with a left join:
SELECT * FROM tableData
LEFT JOIN tableCollections USING (item)
WHERE tableCollections.collection = 3 AND tableCollections.item IS NOT NULL

Or with an inner join (via @Phate01):
SELECT * FROM tableData
INNER JOIN tableCollections USING (item)
WHERE tableCollections.collection = 3

Since this query will be executed every few seconds I want to go with the option that is the most efficient. Is anybody aware whether one of these might be better than the other or will they be optimized to the same thing anyway?
Comment: They were equivalent in the cases I tried, but I may have missed some edge cases. Why are you saying they are not equivalent?
Comment: All 3 queries not equivalent to one another. They'll return different results. Have you tried them?
Comment: The 2nd and the 3rd are equivalent if and only if the `tableCollections.item` column has no nulls.  The 1st and the 2nd are not equivalent because they show different number of columns as output.
Comment: It would help if you added the `SHOW CREATE TABLE` output in the question (for both tables).
Comment: The columns are declared as NOT NULL, so they will not contain nulls. The output is also not really relevant, since my question is really about the efficiency of finding the rows in the first place. I agree that the create table statements would have made this clearer, but the real-life case is unfortunately much too complicated for this. Sorry about that!
Answer: I'd try with an INNER JOIN
SELECT * FROM tableData
INNER JOIN tableCollections USING (item)
WHERE tableCollections.collection = 3 AND tableCollections.item IS NOT NULL

As LEFT JOIN takes also the items not in the collection number 3, and then filters the data.
INNER JOIN takes only record that are in both tables, this way you handle less data
Comment: Good point! I will edit that into the first post. I guess MySQL should actually optimize the LEFT JOIN version to the same as this, but I'm not sure if that will work or not.
Comment: Actually you could also drop the `tableCollections.item IS NOT NULL` then, couldn't you?
Comment: If `tableCollections.item` is a `PRIMARY KEY` (as it should be) or anyway if you're sure that no rows have the item set to null then yes 'cause it can't be null
Comment: It's not (since multiple collections can contain the same item) but it is declared as `NOT NULL`.
Comment: You'll have no problem then. Another point that crossed my mind is that if you use `LEFT JOIN` make sure the left table to be the one with less data, cause it puts the whole left table in your resultset
Answer: This one must be faster :-)
SELECT *
FROM tableCollections
LEFT JOIN tableData
USING (item)
WHERE tableCollections.collection = 3 AND tableCollections.item IS NOT NULL

Comment: Hmm, why are you saying it must be faster?
Comment: Because the logic of data you want to get says tableCollection is smaller, and you need only records from both tables but you don't need records that does not exists in tableCollection, that means if you filter with WHERE before LEFT JOIN it will reduce number of records a lot.


Substract two row values in dataframe python

Question: Currently I have a sort of dataframe where I want to substract value from current row from the previous one.
example:
df = pd.Datafame([1,4,3,5,6],columns = ["time")])

left

1

4

3

5

6

I want to iterate over these rows and store it in a list. So the list will get like this [-3,1,-2,-1].
So far I have this
 list = []

    for index, row in df.iterrows():
          list.append(row['time'])

Now the for loop just stores the values in the list when it comes across the row. How can I change it that it substracts the current value from the previous one and stores it in a list?
Your help is appreciated
Answer: df['time'].diff(-1).tolist()[:-1]
>>> [-3.0, 1.0, -2.0, -1.0]

Comment: Okay, thank you! One more question. How can I access the list, because when I look at the list (that I created in the code) it is empty?
Comment: The code, which I shared, produced the list that you need.
Comment: Just one more question. Is it also possible to get the difference in percentage instead of just the difference between the two values. So instead of 3 you store (4-1/4) = 0.75?
Comment: I also made one small mistake. Instead of a list with -3, 1, -2 and -1, I want a list the other way around, so 3,-1,2 and 1
Comment: If you need the data in the opposite order, you can use `df['time'].diff(1).tolist()[1:]`. As for the percentage, you can do it manually: `df['time'].diff(1).tolist()[1:] / df['time'][1:]`
Answer: You can use .shift(-1):
df['time'] = df['left'] - df['left'].shift(-1)
or if you need it as a list:
(df['left'] - df['left'].shift(-1)).tolist()


Why the retrieved result set string doesn't work with the .equals()

Question: I'm retrieving some information from a database and I want to check if the value is null. Although the string retrieved from the database is "null" the equals() returns false.
I tried trim(), just in case there were any spaces in the retrieved string
     String code = product.retrieveCode();
            System.out.println("the code is :"+ code);

            if (code.equals("null")==true){
                // do this
            }
            else{
                //   do that
            }

Please let it be noted that the database doesn't have any data stored.
Comment: You can remove the ==true sine equals retrns a boolean.
Comment: Use a debugger and inspect the *actual* value of `code`. You're the only with access to this information.
Comment: Are you sure it returns the String "null" (as opposed to `null` reference)?
Comment: yes on the retrieveCode method I return rs.getString
Comment: @BenjaminUrquhart true but I need to know if it's true of false
Comment: If it's false it returns false. If it's true it's true. There's no need for a redundant check.
Answer: As pointed out by 'Eran', the value in code is probably a null reference. Do,
if (code == null)
instead of
if (code.equals("null")==true)
This likely occurs because the rs object returns null when you call it's getString() method. ResultSet will return null when the column value is SQL NULL. (Reference)
Comment: Although what I said is true, since I didn't have anything to lose I tried your and Eran's  suggestion and it worked. Still curious why this happens though.
Comment: @Volpym So, I guess you're using ResultSet, if the column value in SQL is null, then `getString` returns null ([docs](https://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html#getString(int))). The `println` internally calls `toString` on the object converting the null value, into a "null" string.
Answer: your logic and syntax is correct.In this case here your database value is probably assigning null value to code and you are checking whether a string of "null" is equal to code. This will give error as it is null reference. Make sure that you are getting a "null" else if its empty just check equals case withe whitespace
Answer: It prints Yes. so I don't think java doing anything wrong
String code = "null";
if (code.equals("null")){
     System.out.println("Yes");
} else{
   //   do that
}

I think it is a null reference. Please do the below code.
if (code==null){
   System.out.println("Yes");
} else{
       //   do that
}

Comment: Looks like you and the others are correct. Trying to figure our why this is the case.
Comment: can you please share the screenshot of debugging code
Comment: there is no need to. Chrisvin pointed me to oracle's docs and I got my answer. Thank you for you time and help


SGDClassifier vs LogisticRegression with sgd solver in scikit-learn library

Question: scikit-learn library has following classifiers which look similar:

Logistic regression classifier has different solvers and one of them
is 'sgd'

http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html#sklearn.linear_model.LogisticRegression

It also has a different classifier 'SGDClassifier' and the loss
parameter can be mentioned as 'log' for logistic regression.

http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.SGDClassifier.html#sklearn.linear_model.SGDClassifier
Are they essentially same or different? If they are different, how different is the implementation between two? And how do you decide which one to use given the problem of logistic regression?
Comment: The LogisticRegression-module has no SGD-algorithm ('newton-cg', 'lbfgs', 'liblinear', 'sag'), but the module SGDClassifier can solve LogisticRegression too. That means you got 5 solvers you can use. There are huge differences between those and some rules to choose are given in the docs (e.g. which one of group 1). SGD is typically used for large-scale problems where it's very efficient. Compared to the others, it might be very dependent on chosen hyperparameters (learning-rate, decay, ...). Bad hyperparameters not only result in slow performance, but also bad results (global-min not reached)
Comment: Thank you. I got confused between 'sag' and 'sgd'. Does 'sag' refer to Stochastic Average Gradient? I thought that is similar to sgd unless Stochastic average gradient is much different than Stochastic average gradient descent.
Comment: @sascha "**SAG**" stands for "**S**tochastic **A**verage **G**radient descent". See http://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
Answer: Logistic Regression in Sklearn doesn't have a 'sgd' solver though. It implements a log regularized logistic regression : it minimizes the log-probability.
SGDClassifier is a generalized linear classifier that will use Stochastic Gradient Descent as a solver. As it is mentionned here http://scikit-learn.org/stable/modules/sgd.html : "Even though SGD has been around in the machine learning community for a long time, it has received a considerable amount of attention just recently in the context of large-scale learning."
It is easy to implement and efficient. For example, this is one of the solvers that is used for Neural Networks.
With SGDClassifier you can use lots of different loss functions (a function to minimize or maximize to find the optimum solution) that allows you to "tune" your model and find the best sgd based linear model for your data. Indeed, some data structures or some problems will need different loss functions.
In your example, the SGD classifier will have the same loss function as the Logistic Regression but a different solver. Depending on your data, you can have different results. You may try to find the best one using cross validation or even try a grid search cross validation to find the best hyper-parameters.
Hope that answers your questions.
Comment: Very nice answer!
Comment: Thanks for making this so clear! I was not relating the "log" in "loss" to logistic regression!
Answer: Basically, SGD is like an umbrella capable to facing different linear functions.
SGD is an approximation algorithm like taking single single points and as the number of point increases it converses more to the optimal solution. Therefore, it is mostly used when the dataset is large.
Logistic Regression uses Gradient descent by default so its slower (if compared on large dataset)
To make SGD perform well for any particular linear function, lets say here logistic Regression we tune the parameters called hyperparameter tuning
Answer: All linear classifiers(SVM, logistic regression, a.o.) can use the sgd: Stochastic Gradient Descent


Is the integral of a modification of a stochastic process equal to the integral of the original process?

Question: For a measurable stochastic process $X_t(\omega): \Omega \times [0,T] \to \mathbb{R}$, $\tilde{X}_{t}(\omega)$ is a modification of $X_t(\omega)$ if $\mathbb{P}(X_t = \tilde{X}_t) = 1$ for all $t \in [0,T]$.
Does this imply that
$$\int_0^t X_s(\omega) ds = \int_0^t \tilde{X}_s(\omega) ds ~~\text{ almost all }\omega, \forall ~t\in[0,T]?
$$
I tried to prove that the set $A = \{ \omega: X_t(\omega) \neq \tilde{X}_t(\omega) \text{ for a subset of } [0,T] \text{ of positive measure} \}$ has measure 0, but I didn't know how to.
I also tried to construct a counterexample, where a modification has a different integral, but I couldn't think of a way to make sure that for a subset of $\Omega$ of positive measure the two processes are different for a subset of $[0,T]$ of positive measure.
Comment: are the processes time continuous?
Comment: In the example where it came up, $\tilde{X}_t$ was a continuous modification of $X_t$, so if you know it for this case it would already be very helpful.
Answer: For the case that the processes $X$ and $\tilde X$ have both right continuous paths a.s., it is true. Because two right continuous modifications are indistinguishable (see Protter page 4). And if $X$ and $\tilde X$ are indistinguishable is clear that $\int_0^tX_sds = \int_0^t \tilde X_sds$ a.s.
Answer: First, using the Hölder inequality (or Lyapunov's), for $\mu:=\lambda\times \mathbb{P}$ with $\lambda$ the Lebesgue measure on the real line,
$$
 \mathbb{E}\left|\int_0^t (X_{s}-\tilde{X}_{s})ds\right|^2\lesssim \mathbb{E}\left(\int_0^t \left|X_{s}-\tilde{X}_{s}\right|^2\right)^{1/2}=\|X-\tilde{X}\|_{L^2(\mu)}.\tag{1}
 $$
Thus,
$$
 \text{LHS}_{(1)}\lesssim\|X-\tilde{X}\|_{L^2(\mu)}=\int_0^t\mathbb{E}|X_s-\tilde{X}_s|^2ds=\int_0^t\int_{\mathbb{R}_{\ge0}}\mathbb{P}\left(|X_s-\tilde{X}_s|^2>\tau\right)d\tau ds=0
 $$
as $\mathbb{P}\left(|X_s-\tilde{X}_s|^2>\tau\right)=0 ~~ \forall s,\tau$ in its range, as $\tilde{X}$ is a version of $X$. I have used a standard result to rewrite an expectation using the cumulative distribution, see Remark 2. Therefore,
$$
 \int_0^t (X_{s}-\tilde{X}_{s})ds=0
 $$
for almost all $\omega$.

GENERALIZATION
We can proceed similarly for the Itô integral and with a general function $\sigma$ satisfying the Lipschitz condition of the existence theorem of SDE ($|\sigma(t,x)-\sigma(t,y)|\leq D|x-y|$). Indeed, as above
$$
 \mathbb{E}\left(\int_0^t\left|\sigma(s, X_{s})-\sigma(s, \tilde{X}_{s})\right|^2ds\right) = 0
 $$
By the Itô isometry,
$$
 \|\int_0^t\left(\sigma(s, X_{s})-\sigma(s, \tilde{X}_{s})\right)dB_s \|_{L^2(\mathbb{P})}= 0
 $$
Therefore,
$$
 \left|\int_0^t\left(\sigma(s, X_{s})-\sigma(s, \tilde{X}_{s})\right)dB_s \right|^2=0
 $$
for almost all $\omega$. So we conclude that, almost surely,
$$
 \int_0^t b(s, {X}_{s}))ds=\int_0^t b(s, \tilde{X}_{s}))ds,\quad \int_0^t\sigma(s, \tilde{X}_{s})dB_s=\int_0^t\sigma(s, {X}_{s})dB_s.
 $$
where $|b(t,x)-b(t,y)|\leq D|x-y|$.
Remark 1. using that $\mathbb{Q}$ is countable,
$$
 \mathbb{P}\left(\omega\in\Omega ~|~\tilde{X}_t(\omega)=X_t(\omega)~~ \forall t\in\mathbb{Q}~\cap[0,T]\right)=1.
 $$
But this is not as strong as indistinguishability, i.e.,
$$
 \mathbb{P}\left(\omega\in\Omega ~|~\tilde{X}_t(\omega)=X_t(\omega)~~ \forall t\in[0,T]\right)=1,
 $$
and it is unclear that the equality of integrals can be proved from here.
For instance, let $\{t_j\}_{j\in\mathcal{J}}=\mathbb{Q}~\cap[0,T]$, taking $\{t_i\}\subset\{t_j\}_{j\in\mathcal{J}}$ for the elementary functions
$$
 \phi_n(t,\omega):=\sum_{i\in \mathcal{I}_n}{\sigma}(t_i, X_{t_i}(\omega))\chi_{[t_i,t_{i+1})}(t)=\sum_{i\in \mathcal{I}_n}{\sigma}(t_i, \tilde{X}_{t_i}(\omega))\chi_{[t_i,t_{i+1})}(t)=\tilde{\phi}_n(t,\omega) \quad \omega\text{-a.a.,}
 $$
is not enough because $\int_0^t\phi_n dB$ might not converge to $\int_0^s\sigma(s, X_s)dB_s$ (in the construction of the Itô integral one needs first to mollify and cutoff to get a continuous and bounded function, see Øksendal, §3.1). And with the equality only in a countable number of $t_i$, the standard integrals might be different too (take $X_s=\chi_\mathbb{Q}$ and $\tilde{X}_s=1$ for all $\omega$).
$\diamond$
Remark 2. From the solution manual of J. Shao "Mathematical Statistics".


What are the shared fundamental components of Baroque and Minimalist music that make them sound similar?

Question: Baroque and minimalist music are two of my favorite genres. In particular, I like the repetitive note sequences with variations. J.-S. Bach's Goldberg Variations and Phillip Glass's Naqoyqatsi are good examples of this.
What similarities do these genres share in a way that might impact how they are performed? Do they have any common foundations in particular aspects of music theory (besides the trivial)?  Are they historically related?
Comment: I proposed another edit to the question, adding other "objective" aspects.  I would like the question to stay open if the edit is accepted (or modified, but still objective and sufficiently broad).
Comment: This question is much improved. Please don't vote to close without reading [the meta thread on this question](http://meta.music.stackexchange.com/questions/23/genre-definition-and-comparison-questions/24#24).
Comment: But this question isn't so much a history question as it is a comparison of genres, but any answer will *involve* history (like Kyle's excellent answer below does). Posting a [thread in meta](http://meta.music.stackexchange.com/q/23/59).
Comment: @neilfein it does, in that these genres are still played by musicians, including myself, and the answer will hopefully help me to understand why I enjoy playing and listening to this type of music, play better by understanding what I am playing, and locate more music that I enjoy.
Comment: By that logic, I could ask any question about any music genre. I would suggest rewriting to explain how this relates directly to performing or practicing music.
Comment: I think there may be a valid answer to this question regarding the underlying musical theory, but I have to agree that as-is the question is subjective (of the bad variety).
Answer: Couple of ideas...
Harmony:
Baroque music was the period when harmonic progression (instead of just counter point) started to become a fundamental part of composition (See Functional Tonality). Dissonance is resolved to consonance throughout a phase.
Minimalism tends to focus more on a stable harmony, but in both case the Harmony tends to be a very exposed feature of the music.
Timbre:
Although Baroque was regarded as heavily ornamented music at the time, I would say both Baroque and Minamlist music tend to have a more uniform and stable sound.
How might this effect how they are played?
If you feel that these characteristics I gave as examples are important attributes, you can try to emphasize these or other attribute when you play.
With the Harmony, having accurate pitch and tone might help you expose the harmonies better. With timbre, you might try to keep that timbre stable until there is an intentional change of contrast in the music.
Identifying the contrast between these two styles also might help you understand the genres better. With Baroque you want to strongly identify the functional tonality so you can feel the flow of the harmony, and that generally will naturally translate to your playing. With the stable harmonic nature of Minimalism, you might want to emphasize that by having stable steady sections that coincide with those harmonies. In orchestral auditions, awareness of the contrast between styles and periods of music can be heard and is a major factor.
Keep in mind, these are very sweeping generalizations, music is full of exceptions.
Comment: thank you for your answer. I think that it is the harmonic progression that I am interested in, but did not have a name for.
Comment: Good answer. This is a subjective question in any situation, but personally I would argue minimalist music shares even more in common with the early Classical period (and its corresponding "back to basics" attitude).
Answer: You are absolutely right in saying that both have functional harmony/resolve dissonances but it is in fact more useful in drawing comparisons to compare both of these styles with everything in between them. For example, the shift over the Classical and Romantic periods tended to shift, harmonically, towards countering listeners' expectations over a very brief scales of time (there are countless examples, take any symphony by Brahms and listen to the rapidly evolving harmony) whereas Baroque and Minimalist compositional practices adhered to quasi-Schenkerian 'structural dissonances' whereby the music very broadly moves its tonal center containing smaller harmonic intricacies. Take, for example, Steve Reich's Music for 18 Musicians, which moves broadly from stacked 5ths chords build over a D, shifting down to C sharp with much 'darker' harmonies above, then back to D, creating a huge paradigmic harmonic arc over the whole work or Terry Riley's 'In C'. Similarly Bach's 5th Brandenburg concerto which, despite containing normal harmonically functional dissonances, moves from D major through relative minors but then a very extended highly chromatic harpsichord cadenza, then back to the major. This broad scale of harmonic change would not be found in Classical/Romantic/trad 20th century music, which might adhere to other things such as sonata form or cleverly manipulated passages of modulation of differing harmonic rhythm.
Secondly, there is much similarity to be found in the textures that are used - Baroque devices such as a ground bass/passacaglia (see Pachelbel's canon/the passacaglias of the French school such as those of Charpentier) has a repetitivity about it that surely has influenced the devices of repetition, modification and imitation of the minimalists. The Baroque saw some incredibly complex polyphony such as any traditional form of the time (Fugue etc, or even larger forms such as the Masses) as well as constant ornamentation. If you listen to Minimalist music, you will notice a preoccupation with texture such as the interweaving lines of yet more Steve Reich (Drumming, Nagoya Marimbas etc), or the elaborate orchestral effects of John Adams' Two Fanfares for Orchestra or Philip Glass's Violin Concerto.
Having performed both styles of music extensively, I can say that there are certainly similarities in the way you play them, especially compared with Romantic music. The trend of authentic Baroque performance fits with that of minimalism - in neither would you use excessive Rubato/vibrato or other aspects of 'over-expression'. In both there seems to be a trend away from over-interpretation of the composers' writing and a general feeling of letting the music flow completely from start to finish with no interruptions - indeed this is one aspect that strongly characterises the two styles in a similar way. In terms of beat, both Baroque and Minimalism seem to be characterised by a constant unchanging pulse (look at the relentless semiquavers of Vivaldi violin concertos or the constant pulse of Adams' 'Short Ride in a Fast Machine'). Also both seem to draw inspiration from dance patterns and forms, look at how Bach's cello suites reflect now-archaic dance forms such as the minuet, sarabande or gigue, and similarly how minimalist pieces such as 'The Chairman Dances' or 'Music for Pieces of Wood' and how they so clearly contain the aspects of pulse and rhythm found in more recent forms of dance music.


How to display a field only if option (x) isn't selected

Question: In one of my content types, I have a Status field (field_status) which is a List(text) field displaying 3 radio button options set to the following key|label values:

0|In Stock
1|Under Deposit
2|Sold

I have a custom twig template file for this content type and was wondering how I would display the value if the option isn't 0 (In Stock). In Stock is pretty much the default option so when the item is sold/under deposit, I want a "Sold/Under Deposit" banner to appear in the upper corner of the picture of the item.
Also, I have a view displaying a list of these content types so how would I only show this value again if the selection isn't "In Stock". I don't have a custom template for the view as I did it all in the UI so I'm hoping there's a way to do this there as well.
I feel like this should be a simple solution but for some reason I'm having issues with it.
I figured it would be something like the following but this doesn't seem to work:
{% if field_status is not ['0'] %}
  {{ field_status }}
{% endif %}

I'm assuming my syntax is wrong. What would be the proper way of doing this?
Answer: Create a file in template folder : node--articles.html.twig
             {% if content.field_gif_image|render is not empty %}

{{ content.field_gif_image }}

             {% elseif content.field_image|render is not empty %}

{{ content.field_image }}

             {% endif %}
             {{ content.body }}
             {{ content.field_more_on }}

Fields defined are just for reference, hope It can give you a clue of how to do this.
Comment: This doesn't help me at all. This just checks to see if a field is empty or not. I need it to check which option was selected and then show something only if option 2 or 3 were selected.
Answer: Ok, so I knew I was overthinking my issue. The way I got this to work for me was the following:
In a pre-process function I created the itemstatus variable with the following code:
function THEME_preprocess_node(&$vars) {
  $vars['itemstatus'] = $vars['content']['field_status'][0]['#markup'];
}

And then just applied it to my twig template like so:
{% if itemstatus != "In Stock" %}

    {{ itemstatus }}

{% endif %}


Customizing the display of properties on a rendered entity

Question: I have a custom entity with a large amount of properties on it.
We want to format these entity properties to look a certain way, without modifying the underlying data in the table.
What is the most idiomatic (the most Drupal) way of doing it?
We're trying to put an Entity Reference of this custom entity on a node and render only a few fields - with a form of preprocessing or something along those lines so that we can control the ultimate output.
I can get the fields to show with this key => value pair in the entity array in hook_entity_info():
'extra fields controller class' => 'EntityDefaultExtraFieldsController',

But it doesn't seem to give me any control over the output.
Alternatively, I can put all of the properties into $entity->content in hook_entity_view() as such:
foreach ($entity as $field_name => $property) {
  if (in_array($field_name, $properties)) {
    $entity->content[$field_name] = array("#markup" => $property . "
");
  }

But this doesn't seem very idiomatic.
This seems like a problem that I can't find a lot of resources on.
Comment: In D8 base fields are first-class citizens, formatters and widgets work like any other field. Not sure about D7.
Comment: I could be way off base here but what about setting a custom view mode in `hook_entity_info_alter`, set that view mode in the Ui and then use theme debugger to get the custom view mode template name? Then theme away per field to your heart's content. You'll probably need to use some custom preprocess functions either to remove field markup or just get the vars via the array path or a combo of both.
Answer:
We're trying to put an Entity Reference of this custom entity on a node and render only a few fields - with a form of preprocessing or something along those lines so that we can control the ultimate output.

Sounds like hook_entity_view is what you want. Use "teaser" or create a new view mode, and attach the reference using the given view mode, then implement your logic to render the properties as you like.
Alternatively / additionally, you could look at Display Suite and DS Extras which will give you more flexibility to expose properties via DS custom fields or in field templates.


Obtaining cellsite gps location on Blackberry Curve 8520

Question: Details of my phone:
<code>  Model:Blackberry Curve 8520
  Version :220.127.116.116
  data services :on
</code>
When I am installing google maps I am able to see the location ,so there is a chance of obtaining the current location using this phone.
I am trying to develop an application which will show the current location of the phone,by using the cell site locations because this phone model does not have an in-built GPS device.
I am using the following code:
<code>   BlackBerryCriteria bc=new BlackBerryCriteria(GPSInfo. GPS_MODE_CELLSITE );
   try {
    LocationProvider lp=LocationProvider.getInstance(bc);
           if(lp !=null)
           {
            Location loc=lp.getLocation(-1);
            add (new EditField(loc.getQualifiedCoordinates().getLatitude()+"\n"+loc.getQualifiedCoordinates().getLongitude(),""));
           }
    else
         {
        add(new EditField("unable to find the location provider", ""));
         }
    } catch (LocationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }}
</code>
I am installing the alx file on the bb phone using desktop manager.
On starting the application it is giving me an Uncaught exception:

NET.RIM.DEVICE.API.SYSTEM.UNSupportedOperationException.
Answer: The device might currently not support GPS_MODE_CELLSITE. Check using
<code> GPSInfo.isGPSModeAvailable(GPS_MODE_CELLSITE)
</code>
and use another mode if neccessary.
It might not support GPS_MODE_CELLSITE because:

There is no valid SIM card in your phone (ok, i assume you have one :)
Check if your device and carrier have available GPS mode you are using (here)
If your carrier is Verizone, check for Verizon GPSSettings signing requirement
Your APN settings are not correct (Options > Device > Advanced Settings > TCP IP)
You don't have a BlackBerry Service Plan (not too sure about that one)


compare multiple algorithms in the same dataset

Question: I want to do a comparison between multiple algorithms when they applied to the same dataset. For example, I have a set of texts in Arabic and another version translated to English. I did a sentiment analysis by using different sentiment tools and by using annotators. So, I want to find a suitable statistical test can help me to illustrate the difference.
Comment: It is not very clear what you are asking for. When you say "I want to find a suitable statistical test can help me to illustrate the difference", what difference do you mean? The difference in the performance of the algorithm, or the difference in the results between the two data sets?
Comment: I want to examine if there is any difference in the result of different algorithms.
Comment: sentiment analysis is not mainstream. Show data, method, and references if you want to get a nibble for an answer.
Comment: Please tell us about the results that are output by the sentiment tools. Are they scores? Are they continuous? Are they categorical?

Also, what type of difference in the scores are you looking for?
Answer: First apply k-fold cross-validation (e.g., k = 10). Afterwards apply a paired T-test.
Have a look on Peter Flach's great book "Machine Learning: The Art and Science of Algorithms that Make Sense of Data". There is also a online-version of if, look up page 529:
https://docs.google.com/file/d/0B8ya4ynGkqSxdXRoVmJFNmJEQTQ/edit
Comment: But my data set is not normally distributed. So, I cannot apply t-test


How do you check what version of Server Message Block client a workstation is using on Windows?

Question: Sometimes over slow connections we switch to an older version of the protocol.  I'd like to be able to check and see which version is being used, I only know how to set the version ala:
sc.exe config lanmanworkstation depend= bowser/mrxsmb10/nsi
sc.exe config mrxsmb20 start= disabled

How does one check the version of the protocol being used without using Powershell?
Comment: Why would you switch to an older version over slow connections?
Comment: @JimB Because it doesn't work if you don't.  The Microsoft KB says to do exactly that.
Comment: Can you post that KB?   Autotuming can cause performance problems but SMB peformance usually rises as the version gets higher.
Comment: @JimB I think it's this one: https://support.microsoft.com/en-us/kb/2696547
Comment: That link tells you how to disable the various protocols but also explain what you lose - IE disabling SMB2 looses the better network performamce,and high latency performance.   In fact that one says (correctly) ONLY do this as a temporary troubleshooting measure.
Comment: @JimB Well I'm not making the decisions, I'm just implementing the solution...
Comment: what was the problem you were doing this to try to fix?  That would be a better question to solve the problem.  If anything reducing the SMB version should make life worse for poor network connectivity.
Comment: The problem was that their connection would disconnect while they had an office document open; and then they would get a message stating that someone else was editing it.  And they would have to contact IT to delete the temp file on the server to free it up again so they could open it again.
Answer: If you have Windows 8.1 or 2012, you can use the PowerShell cmdlet Get-SmbConnection for that.
To interpret the answer (copied and pasted from here):

SMB 1 - Windows 2000
SMB 2 - Windows Server 2008 and WIndows Vista SP1
SMB 2.1 - Windows Server 2008 R2 and Windows 7
SMB 3.0 - Windows Server 2012 and Windows 8

Sample output:
ServerName   ShareName   UserName      Credential                 Dialect   NumOpens
----------   ---------   --------      ----------                 -------   --------
SERVER2      f$          DOMAIN\USER   otherdomain\otheruser...   2.02      1
SERVER1      backups     DOMAIN\USER   DOMAIN.LOCAL\USER          3.02      2
SERVER3      users       DOMAIN\USER   DOMAIN.LOCAL\USER          2.02      1

If you don't, perhaps this related question will help:

ServerFault, How do I find out what version of SMB is enabled on a remote host?
Comment: Get-SmbConnection isn't entirely helpful, as it's listing the current SMB connections and what Dialect (SMB version) they have negotiated between the 2 parties.
It isn't showing the client or servers SMB capabilities.
Comment: Do I have to install that?
Comment: Some of my users are remote it might not be practical...
Comment: It depends on your version of PowerShell, I imagine;  it's built into Windows 8 and above, at least.
Comment: Oh I have Windows 7... :p
Comment: I don't know about 7;  I'd have to look.  It might be built-in there, too.
Comment: Alas.  Windows 8.1 or server 2012.  Sorry.  :(
Comment: I couldn't run the suggested command as admin locally or other wise.  I'm running powershell 3 0 -1 -1
Comment: That's kind of unbelievable.
Answer: You can check the status of the SMB 1/2 services, as seen here:
sc query mrxsmb10
sc query mrxsmb20

 In PowerShell, you will need to use sc.exe instead of sc!
Comment: That is because `sc` in Powershell is an Alias for `Set-Content`. To run this in Powershell, use `sc.exe query [...]`


Organizar mensagem da Thread

Question: boa noite.
Preciso da ajuda de vocês em algo meio simples, estou fazendo uma chat via RMI, a implementação do programa já está funcionando mais o menos como eu quero, mas eu to quebrando a cabeça em um simples print.
Eu preciso organizar a saída para que fique da seguinte maneira:
Chat: digitar mensagem
fulano de tal diz: mensagem digitada
Meu programa uma uma thread para ler as mensagens do servidor, e é justamente essas mensagens que não estou conseguindo organizar.
atualmente as mensagens estão saindo da seguinte forma:
Chat: Digitar Mensagem
Chat: fulano de tal diz: mensagem digitada
Ou seja, eu gostaria de seguir a sequeência
Mensagem
Mesagem
Sei que é meio besta essa dúvida, mas eu realmente não estou conseguindo fazer isso kkkk
segue meu codigo:
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.util.Scanner;

public class ChatCliente{

private static Scanner scanner;

public static void main(String[] args) {
    try {

        ChatIF chat = (ChatIF) Naming.lookup("rmi://localhost:1098/Chat"); //Buscando a Interface no Servidor

        String nome;
        String msg = "";
        scanner = new Scanner(System.in);
        int cont = chat.getmensagens().size();

        //Recebendo o nome do Usuario
        System.out.println("---------------------------------------------");
        System.out.println("       SEJA BEM VINDO AO CHAT                ");
        System.out.println("---------------------------------------------");
        System.out.print("[Chat] Por Favor, Digite seu nome: ");
        nome = scanner.nextLine();

        //Thread responsavel por ler as mensagens do servidor
        Thread thread = new Thread(new Runnable() {
            int cont = chat.getmensagens().size();

            @Override
            public void run() {
                try {
                    while(true){
                        if (chat.getmensagens().size() > cont){

   System.out.println(chat.getmensagens().get(chat.getmensagens().size()-1));
                            cont++;
                        }
                    }
                }catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });

        System.out.println("---------------------------------------------");
        System.out.println("Ola, " + nome + "! Voce agora esta conectado!");
        System.out.println("---------------------------------------------");

        thread.start();

        //Envia as mensagens  para o servidor
        while(true){
            System.out.print("[Chat]"+": ");
            msg = scanner.nextLine();
            chat.setMensagem(nome+" diz"+": "+msg);
        }

    } catch (Exception e) {
        System.out.println("Ocorreu um erro: " + e);
    }
}
}

Answer: O problema é que as duas threads estão imprimindo na mesma console.
Nesse ponto você imprime a string chat sem quebra de linha.
while(true){
    System.out.print("[Chat]"+": "); // Aqui você imprime o "[Chat]:" sem quebra de linhas
    msg = scanner.nextLine();
    chat.setMensagem(nome+" diz"+": "+msg);
}

Nesse outro ponto, você imprime a mensagem na mesma console da mensagem anterior.
System.out.println(chat.getmensagens().get(chat.getmensagens().size()-1));

Por isso você está vendo: "[Chat]: mensagem".
As mensagens das threads estão misturadas. Para que fique organizado você precisa colocar as threads em classes diferentes e criar um main para cada uma. Depois você precisa executar os dois main. Dessa forma você terá duas consoles.

Organizar mensagem da Thread


Todas teclas funcionarem como enter

Question: Estou desenvolvendo um pequeno sistema em PHP onde o usuário apenas passa um crachá e pressiona enter. De alguma forma preciso fazer esse enter ser automático após alguns segundos (o botão já fica no focus após o preenchimento do campo) ou que ao passar o crachá novamente (somente números) o sistema entenda como um "enter". É possível?
Estou tentando adaptar essa função que bloqueou todas letras para esse caso:
function SomenteNumero(e){
   var tecla = (window.event) ? event.keyCode : e.which;

   if((tecla > 47 && tecla < 58))
       return true;
   else{
       if (tecla == 8 || tecla == 0)
           return true;
       else
           return false;
   }
}

Comment: Já tentou fazer algo com JavaScript? Pode postar o que tentou?
Comment: Minha empresa trabalha com cartões também. A sua máquina de leitura não simula um enter automaticamente?
Comment: Estou tentando adaptar essa função que bloqueou todas letras para esse caso: function SomenteNumero(e){
    var tecla=(window.event)?event.keyCode:e.which;
    if((tecla>47 && tecla<58)) return true;
    else{
     if (tecla==8 || tecla==0) return true;
 else  return false;
    }
}
Comment: Não Wallace, essa leitora é uma Nonus Homebank para boleto que adaptamos para leitura de cartão....
Answer: Eu entendi a sua pergunta desta maneira:
Como automatizar a submissão de um formulário após preenchimento automático de um campo?
Monitore os eventos KeyDown e KeyUp, e após alguns segundos de inatividade valide o conteúdo digitado.

    var temporizador;
    var intervalotemporizador = 2000;  //tempo em milissegundos. Neste caso, 2s.
    var $input = $('#campoCodigo');

    //Quando uma tecla for liberada no campoCodigo, iniciar temporizador:
    $input.on('keyup', function () {
      clearTimeout(temporizador);
      temporizador = setTimeout(avaliarConteudoDigitado, intervalotemporizador);
    });

    //Quando uma tecla for pressionada, limpar o temporizador:
    $input.on('keydown', function () {
      clearTimeout(temporizador);
    });

    //quando o usuário finalizar a 'digitação':
    function avaliarConteudoDigitado () {
      //Faça algo aqui - valide o código, mostre comentários, e ao final submeta o formulário:

      //document.getElementById("meuForm").submit();

      var valor = $input.val();

      if (isNaN(valor)) //isNaN: Is Not a Number (verifica se o valor não é numérico)
        $('#mensagem').val('ERRO: Não numérico.');
      else
      if (valor.length != 10)
        $('#mensagem').val('ERRO: Número de caracteres diferente de 10.');
      else
        $('#mensagem').val('OK.');

    }

<input type='text' id='campoCodigo' />

<input type='text' id='mensagem' />

Adaptado de 'Run javascript function when user finishes typing instead of on key up?', SO Original.
Comment: A intenção seria essa mesmo, mas o usuário não terá acesso a teclado, é somente a leitura do cartão que gera uma sequencia de 10 números. Tentei alterar os eventos das teclas, para todos valerem como enter, mas até o momento não consegui.
Comment: @Diego Não é possível fazer essa diferenciação. O browser recebe os caracteres digitados como se fosse um usuário digitando o conteúdo. O que você pode fazer é incorporar a sua validação (apenas caracteres numéricos? comprimento total = 10?) na função `avaliarConteudoDigitado()`.
Answer: Você pode verificar o tamanho do valor do campo, se for o tamanho do número do crachá, envie o formulário, exemplo:

function SomenteNumero(e){
   var tecla = (window.event) ? event.keyCode : e.which;

   if((tecla > 47 && tecla < 58))
       return true;
   else{
       if (tecla == 8 || tecla == 0)
           return true;
       else
           return false;
   }
}

$(document).on('keyup change', '#numero', function(event){
  event.preventDefault();

  var res = SomenteNumero(event);

  var len = this.value.length;

  if (len < 10 && !res) return res;

  if (len == 10){
    $(this).prop('readonly', true);
    $('#teste').submit();
  }

});

$(document).on('submit', '#teste', function(event){
  event.preventDefault();
  alert('Form "enviado", SQN!');
  $('#numero').prop('readonly', false);
});
[readonly]{
background-color: #CCC;
}

<form id="teste">
  <input type="text" name="numero" id="numero">
 </form>

Todas teclas funcionarem como enter


Como da loop em células selecionadas no Excel?

Question: Quando eu clico e arrasto para baixo as células seguintes na devida imagem, na célula "E21" aparece um '3' decorrente do acompanhamento da sequencia de células da "A15" até "A18" como eu faço para dar um loop apenas nas células de "A15" até "A17"? para o resultado sair "aguardando" ??
Comment: o que você quer dizer com *"dar um loop"*?
Comment: Eu quis dizer, a função repetir as células A15 até A17, para o resultado da "aguardando", pois todo vez que eu clico e arrasto esse bendito '3' aparece, referente a célula A18
Comment: bom só vai dar problema ao arrastar para copiar a fórmula se tiver algum problema nas referências. Podo mostrar como está a fórmula na célula "E18"?
Comment: Eu consegui resolver! vou responder minha pergunta. Ficou uma fórmula bem grande
Comment: como a tabela é fixa, ao copiar a fórmula muda as linhas, precisa usar `A$15:A$17`, basta colocar o `$` para que não mude as linhas ao copiar a fórmula
Answer:
Fixando as células correspondentes A15 até A17 e adicionando uma função "Se" na A18 até C18, dizendo que se for diferente das numerações de 1 até 3 e fixando esses valores, chame a célula "incorreto" caso adicione algum numero fora da sequencia de 1,2,3.


How to show that $\sum_{k=0}^{\infty}(k+1)2^{-k}$ converges to 4?

Question: The geometric series $\sum_{k=0}^{\infty}2^{-k}$ converges to 2. Use Theorem 6.3.6 to show that the series $$\sum_{k=0}^{\infty}(k+1)2^{-k}$$ converges to 4.
Theorem 6.3.6 states:
Let $\sum_{k=0}^{\infty}a_k$ and $\sum_{j=0}^{\infty}b_j$ be two absolutely convergent series. Then $$(\sum_{k=0}^{\infty}a_k)(\sum_{j=0}^{\infty}b_j)=\sum_{n=0}^{\infty}\sum_{k=0}^{n}a_kb_{n-k}$$ where the series on the right also converges absolutely. From reading other questions, it looks like this is called the Cauchy product.
It seems like a good first step to assume $2^{-k}$ will be playing the role of $a_k$ here. Then I am looking for something to play the role of $b_j$ such that $\sum_{j=0}^{\infty}b_j$ converges to 2 and such that $k+1$ emerges from the $b_{n-k}$ terms.
I'm thrown off by the inner sum. It seems like something along the lines of $$b_j=\frac{(b+1)!}{b!}$$ could lead to the $k+1$ emerging, but this would make $\sum b_j$ a divergent series.
Is my choice of $a_k$ reasonable? Is there a different way I should be thinking about $b_j$?
This is not a duplicate of How can I evaluate $\sum_{n=0}^\infty(n+1)x^n$? because this problem requires use of a theorem that is not used in the linked question.
Comment: just differentiate the geometric series and plug in a half
Comment: Set $a_k = 2^{-k}$ and $b_k = 2^{-k}$. LHS: $4$,
RHS: $\sum_{n=0}^{\infty}\sum_{k=0}^n 1*2^{-n}= \sum_{n=0}^{\infty}(n+1)*2^{-k}$. Hence the answer is 4
Comment: See https://math.stackexchange.com/questions/30732/how-can-i-evaluate-sum-n-0-inftyn1xn
Comment: It's $ 2\sum\limits_{k=1}^\infty k(\frac12)^k$
Comment: This theorem doesn't seem appropriate because $\sum_{k=0}^\infty (k+1)2^{-k}$ can't really be written in the form $\left( \sum_{k=0}^\infty a_k\right)\left(\sum_{k=0}^\infty b_k\right)$. I would just use differentiation of power series and the knowledge of the limit of the geometric series here.
Comment: @qbert Unfortunately we haven't developed the tools to differentiate series yet in the course. I need to find a justification that non-trivially uses the statement in the theorem (even if simpler methods are available).
Answer: Set $a_k = 2^{-k}$ and $b_k = 2^{-k}$.
LHS: $4$,
RHS: $\sum_{n=0}^{\infty}\sum_{k=0}^n 1*2^{-n}= \sum_{n=0}^{\infty}(n+1)*2^{-n}$. Hence the answer is 4
Comment: well basically it says use the theorem. You can't have $a_k$ or $b_k$ just be $(k+1)$ on its own as this does not sum up. Also, you can't have $a_k = (k+1)2^{-k}$ because you get square terms on the right hand side (oh no!). So I realised that this sum from 0 to n on the right hand side was just an $n+1$ in disguise
Comment: Thanks! Is there a thought process that leads to seeing that this is the answer, or is this more of a 'flash of insight' solution? I understand why this works, but I'm not sure how I would go about seeing it if I didn't already know to try it.
Answer: I think the intention here is to write
$$(n+1)2^{-n} = \sum_{k=0}^n\left(\frac 1{2^k}\cdot \frac 1{2^{n-k}} \right)$$
Then apply the given theorem about the Cauchy product.


Views - Filtering view results by current user profile field

Question: I have been trying to do this last couple of days but no luck.
Every user have a custom field (favorite_car) which is taxonomy and there is different terms ('Audi','Bmw' etc).
I have also content type 'Cars' which had also a custom field (favorite_car).
I need to display only the results, that user have selected.
If user have a custom field selected to 'Bmw', view need to return only nodes which have a favorite_car field set to 'Bmw'.
I think that there is a way to do this in drupal 7. Every kind of help is welcome.
Answer: You can filter contents on their term_reference_field by the field_value of a term_reference_field of the current_user:
So we go:

Create a content_view
Create a relationship with "favorite_car"
Create a relationship with "term from favorite_car"
Create contextual filter user:uid with provide default_value: user_id from logged in user and the relationship favorite_car

This works for me!
Answer: Look at the answer to Add Taxonomy Term automatically based on term from user's account
Replace the references to "state of residence" with "favorite car" and references to "forum postings view" with "car listings view".


Questions that ask too much

Question: Some examples:

Show cart page in a popup on add to cart action
Full Page Cache on CE 1.8 - An FPC Magento Module? Varnish? Both?
Pre-Warming the Magento Enterprise Full Page Cache
Is Magento the right platform for 1M products?

I've been a long time SO user, and questions like these are usually quick to be closed (partially thanks to the cv-ring) and I think they're bad for the site's health.
I don't think questions about broad topics, or require writing an entire module as an answer belong here.  I know we're all here to help people learn Magento, but I believe we should be directing things like this to a forum/reddit/twitter/etc.
Take from the FAQ:

Not all questions work well in our format. Avoid questions that are primarily opinion-based, or that are likely to generate discussion rather than answers.
Don't ask about [...] Questions with too many possible answers or that would require an extremely long answer

I've flagged/vote-closed a few questions out there, but I wanted to bring up a few examples and see what the community thinks.
Answer: Background
In the foundation of this site it was very important for us to attempt to answer all questions and to instill trust that we would support this community, no matter how difficult. Let's face it - Magento is monolithic and can be daunting.
Today we see very few of these types of questions, and if not they are swiftly closed.
But what you're asking is to rewrite history. I will argue not to close questions that have de-facto answers on them, no matter how long the answer may be. I often refer back to them and I hold them in very high regard. Those of us in the early days put in hundreds of hours, and that should mean something.
I realize that not all long-form answers are good, just as not every short answer is good.
Action
So, in that case, I will consider the following:

Mark these types of questions as Community Wiki
Lock these questions so no more answers can be posted
Notify those in the future that longform answers are encouraged, but it's probable that the question itself may be out-of-bounds to begin with

We have to be careful not to be police. I don't want to discourage people from asking hard questions. If they knew the answer to the question or the level of effort involved in the answer, they honestly they wouldn't be here asking.
We're here to help people be better actors by nudging them in the right direction.
Comment: I think the key is that we best serve the Magento SE community by using the tools provided to encourage inclusion (ie community wiki) rather than exclusion (closing questions) and it serves no one to close retroactively if questions have up votes. In a recent SO Podcast Joel & Team mentioned how they felt they had been perhaps a bit too eager to train Mods & reviewers to close topics quickly as OT resulting specifically in too strong of a "policing" mentality making SO less inviting for new users. Steve's got a good point but I we should strive for balance & prefer change vs closure.

Questions that ask too much


Como passar o id da empresa do angular para o php?

Question: Olá
Preciso passar o id da empresa do angular para a api em php. Como faço?
Segue o código:
Angular:
app.controller('UploadCtrl', ['$scope', '$window', 'Upload', function($scope, $window, Upload) {

var formData = new FormData();
var idempresa = localStorage.getItem('idempresa');
// Attach file

$scope.uploadExcel = function(){
  $scope.input.click();
}

$scope.input = document.createElement("INPUT");
$scope.input.setAttribute("type", "file");
$scope.input.addEventListener('change', function(){
  formData.append('file_xls', $scope.input.files[0]);

    $.ajax({
      url: 'http://localhost:8888/sistemas/webApps/fluxo_de_caixa/fluxojoin_2.0/php/importaArquivo.php',
      data: formData,
      type: 'POST',
      contentType: false,
      processData: false,
  });
});

}]);

PHP:
<?php
ini_set('display_errors', true);
error_reporting(E_ALL);

header("Access-Control-Allow-Methods", "POST, PUT, OPTIONS");
header("Access-Control-Allow-Origin", "*.*");
header("Access-Control-Allow-Headers", "Content-Type");

include_once("con.php");

$pdo = conectar();

include_once("PHPExcel/Classes/PHPExcel.php");

$uploadDir = "uploadFile/";

$uploadfile = $uploadDir . $_FILES['file_xls']['name'];

if(move_uploaded_file($_FILES['file_xls']['tmp_name'], $uploadfile)) {
  echo "
";
  echo "Dados pegos com sucesso.";
  echo "

";
}else{
  echo "Não foi possível pegar arquivo";
  echo "

";
}

$pegaDados=$pdo->prepare("SELECT * FROM dadosImportados");
$pegaDados->execute();
$qtd = $pegaDados->rowCount();

if($qtd > 0){ // se tiver dados no banco, apaga tudo
  $qryZera=$pdo->prepare("DELETE FROM dadosImportados");
  $qryZera->execute();
}

$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objPHPExcel = $objReader->load($uploadfile);

$sheet = $objPHPExcel->getActiveSheet();

foreach ($sheet->rangeToArray($sheet->calculateWorksheetDataDimension()) as
$row) {
  echo $row[0]." ".$row[1]." ".$row[2]." ".$row[3]."
";
  $qryInsert=$pdo->prepare("INSERT INTO dadosImportados
  VALUES(NULL,'$id_empresa','$row[0]','$row[1]','$row[2]','$row[3]')");
  $qryInsert->execute;
}

?>

Answer: Você pode passar o id direto na URL:
url: 'http://localhost:8888/sistemas/webApps/fluxo_de_caixa/fluxojoin_2.0/php/importaArquivo.php?idempresa='+idempresa,

E recuperar no PHP com $_GET:
$_GET['idempresa'];

Comment: Mas estou passando enviado a requisição por POST.
Comment: @GustavoSevero Sim, o form será enviado por POST normalmente. Colocando o id da empresa na url como falei, não altera nada, apenas você irá pegá-lo com GET no PHP.
Answer: Adicione a variável idempresa no seu formData:
$scope.input = document.createElement("INPUT");
$scope.input.setAttribute("type", "file");
$scope.input.addEventListener('change', function(){
  formData.append('file_xls', $scope.input.files[0]);
  formData.append('idempresa', idempresa);

    $.ajax({
      url: 'http://localhost:8888/sistemas/webApps/fluxo_de_caixa/fluxojoin_2.0/php/importaArquivo.php',
      data: formData,
      type: 'POST',
      contentType: false,
      processData: false,
  });
});

E no PHP você recupera esse valor através da variável $_POST:
<?
    $idempresa = $_POST["idempresa"];
    echo "Id da empresa: ".$idempresa;
?>


HTML Body align as center

Question: I have tried all the possibilities but surely somewhere I am mistaking. I am creating a bootstrap website (http://design.logohour.com) site seems ok as well as aligned well in center, but when I am trying to change the screen size lesser than 850px or more less, all the content goes to the left.
I know there is something wrong with CSS but unable to find out since I want all my content in the center without overflow-x ... need an expert opinion.
Comment: Hmmm... looks centered for me all the way down to 300px. Nothing went left aligned for me when I checked. What device/browser are you using?
Comment: Google chrome I have cleared cache but still its bad at my end
Comment: Ok this is funny .. I have spent almost an hour and finally when I checked on mozilla its showing fine .... so why Chrome showing such alignement
Comment: Cache on the server? All i know is I am using Chrome and it is fine.
Comment: Seems to be working fine on Chrome for me as well.  I'm voting to close as a problem that can no longer be reproduced,
Answer: Everything looks fine on my end!
Your cache is probably outdated. Try these things to see if it solves:
1) Assuming you're using Google Chrome, open an incognito window and view the site.
Why? Incognito mode will allow you to view your site without using cache
2) Refresh your cache using the web inspector.
If you open up the web inspector (Right click and click "Inspect") you unlock a magical way to clear your cache. With the web inspector open, right click the reload button and empty the cache.

Good luck solving the issue!

HTML Body align as center


MSAL - No Tokens Available when Using IneractionType.Redirect

Question: In our application, we authenticate users using AAD, but we authorize users using our own User and Role tables in our local SQL database.
With the old ADAL library, we were able to return users to our callback url, then from there we would grab the JWT token from the ADAL service, and send that token to our server.  The server would then validate the token, decode it and grab the email address.  We then used our SQL tables to return another JWT that contained the user's identity and all of their roles.
With MSAL, this still works if you use InteractionType.Popup. The response Observable from the loginPopup() method carries the AuthentiationResult, which has an idToken property and an accessToken property.  You can easily grab the one you need and you're off to the races.
However, with InteractionType.Redirect we don't get the AuthenticationResult.
I have injected the msalService instance into the our callbackURL's component (called AuthCallbackComponent).  I looked everywhere within the msalService for the tokens, but couldn't find them.  I even looked in sessionStorage, where I've configured MSAL to cache the token.  They are actually in there (under a couple of really funky keys), but not until later.  Whether I use ngOnInit, ngAfterViewInit or ngAftercontentInit, the tokens are not there yet.   It does work if I set a timeout of 1-2 seconds, but...no. You can never really rely on timeout delays being long enough for all of your users all the time.
We desire to use the Redirect workflow rather than the popup workflow, so it really would be ideal if we can just get the idToken from the MSAL instance.
I found this post here: Retrieve token using msal, which offers some possible solutions, but the suggestions aren't helpful.  It talks about a custom MSAL Interceptor, but that seems wrong.  That's typically the HTTP interceptor that adds your token to the headers of your service calls.  It also says you can subscribe to the callback and "do something with the returned token", but assuming they mean the callback of the msalService.loginRedirect() method, well that is just wrong.  It doesn't return anything at all.
Remember, that in the old ADAL library, this worked.  Also it still works with InteractionType.Popup (which we can't use).  I expect those tokens must be in the MSAL instance somewhere, or else there's a method we can override, a callback we can provide, etc.
Thanks for reading this longer post.
Answer: Buried deep within the 10K pages of Microsoft documntation on MSAL, I found this event reference:
https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-angular/docs/v2-docs/events.md#the-inprogress-observable
So I used their example code to come up with my solution, which was to inject the msalBroadcastService into my AuthCallbackComponent.  There I subscribe to its msalSubject$, and when a LOGIN_SUCCESS event happens, I can get the accessToken and idToken from the event's payload.  Here is some code:

<code>  ngOnInit(): void {
    this.msalBroadcastService.msalSubject$.pipe(filter((msg: EventMessage) => msg.eventType === EventType.LOGIN_SUCCESS)).subscribe(msg => {
      const idToken = (msg.payload as any).idToken;

      // now I can call my service method, passing in the idToken
  }</code>