Dealing with "cheap" opponents

Question: I recently joined a competitive basketball city league, and I've been dealing with some "cheap" stuff on the court - pulling on my jersey, pulling on my arms before a rebound (I'm taller than average), etc. The refs aren't calling this; I assume they aren't seeing it.
I haven't played much competitive basketball. I would like to know if it is something I should always expect. It seems "below the belt". Also, how do I overcome this sort of stuff. I'm getting a little frustrated, I want to be more effective, and I'm not getting much coaching.
Comment: Perhaps. I suppose others would know better than me. In any case, I've updated my post to include that tag. Thanks!
Comment: Welcome. I added the `sports-psychology` tag as some of this is mental...and it seems that their "cheap" actions are working as it is frustrating you. Not saying whether the officiating is clean or not, but they are doing a good job in flustering you.
Comment: @mastermind_ed I looked for a "sportsmanship" tag, but couldn't find one. Would you consider creating one?
Comment: Does [`etiquette`](https://sports.stackexchange.com/questions/tagged/etiquette) suffice?
Answer: Competitive sports will be like this.  Learning to deal with cheap shots will just be another skill to pick up.
Opponents pull cheap shots for two reasons:  to create actual game play advantage and rattle you.  In the sports I've played cheap shots meant to rattle the opposing player are often legal even if they are cheap.  Referees are not there to make sure we play like ladies and gentlemen.
Here are the three tricks I picked up from captains, referees, psychologists, and sports articles that have helped me the most.
Cue phrase:  Pick something to repeat like a mantra when you encounter unsportsmanlike play.  Pick something that is useful to your sport to refocus your energy away from the other player and back to the game.  Mine is "Get to the front."
Poker face:  If your opponent can see that he is annoying you with antics, he will continue them.  He will continue them even if your only response is acknowledgement.  I de-personalize opposing players.  They are just there, like the ball or boundaries.  Let nothing show on your face.
Prepare:  Think about what you will do when someone engages in cheap play.  We prepare for different things that happen in play and this is just one more thing to prepare for.  And then practice makes permanent.  If there is something in particular that really irks you, you can have teammates do the same thing in warm up and practice so you can work out how you want to respond.
I found the following articles helpful:

http://www.stack.com/a/sports-anger-management
http://devzone.positivecoach.org/resource/video/how-handle-opponents-unsportsmanlike-behavior
Comment: This is actually the thing that irritates me the most too and I do two things.  I wear really tight jerseys and I hack away when I feel hands.  I hack until I hear my number in association with a ref whistle and then I know I've pushed a smidge too hard for next time.  Your play has to match what you are encountering even if you would prefer more sportsmanlike play.  If something becomes egregious then it's time for a captain to request a review.
Comment: +1 Great, experienced answer. I am reminded of [this example](http://stream1.gifsoup.com/view3/3656319/kobe-abd-matt-barnes-o.gif) when you state, "Let nothing show on your face."
Comment: @Coach-D One example doesn't imply a generalization...Kobe didn't react by the ball being pumped in his face in that instance, that's all I was pointing out. That said, I can appreciate what you are saying about Bird and Jordan especially as they primarily played in a different era than Kobe.
Comment: Thanks. I figured I'd have accept it as part of the game, but besides emotionally, I'm not sure how to prepare to counter. I'm frustrated not because of fairness, but because I can't overcome. If I breakaway, and they are holding on my jersey, how hard can I hack their hand? What do I do about retaliation? (I'm also a little frustrated that I'm so out of shape. Previously, I probably could have simply played more physically)
Comment: @mastermind_ed - not sure Kobe is the best example of keeping cool.  When he played against top defenders he jacked up a lot of shots from 20 feet with the guy right in his face.  I would have pointed to more Bird or Jordan on this front.  Bird dealt with cheap guys in more of a happy way - and rose his play against top defenders.  Jordan was great at focusing his anger and really looked like some possessed maniac when playing against Detroit for example - but still under control.
Comment: @mastermind_ed - he did react because - #1 what the hell is Kobe doing pressing the in-bounds passer.  #2 He played terrible against Barnes jacking up dumb hero shots all game.
Comment: @Coach-D Where did he flinch? "Let nothing show on your face" was the point I was referring to, not "Kobe reacted by his poor decision making throughout the course of the game." Barnes was hacking Kobe that game and Kobe was hacking back, so one was using those tactics against the other.
Comment: @ᴍᴀsᴛᴇʀᴍɪɴᴅ_ᴇᴅ i got the point.
Comment: Also, I watched a documentary on the 1980s pistons and bill laimbeer. It was really eye-opening into the psychology of "cheap" play.
Answer: You have a good text book answer that you already accepted.
I will simply give you my take as a big - 6'3" 200lb point guard - that takes a ton of abuse especially when playing in lower income areas - top city leagues.
You are going to get pulled, scratched, elbowed, pushed, whatever.  By just "taking" these actions you are allowing the referee to just ignore them.  It is really easy for a referee to ignore the little things when there is no resistance.  Also if you are playing against these type of players they will only do these actions more if you let them.
Also I have found that most referees at lower intramural levels call fouls based on the reaction.  So if you get bumped mid air and fall over foul.  If you are much bigger than the other guy and he bounces off you, no foul.  Obviously this is blatantly wrong.  However you are not going to make the referee "better" in one go.
Examples:

Guy pulls your shirt.  Grab your shirt and pull it back.  If you don't have the ball this is a given.  Or you can grab his back.  And if you grab it, grab it.  Don't tug it but give it a hefty grab.  You could certainly use this tactic to slow him down and dart the other way.
Pushes you in the back.  This usually happens when you box out well.  So instead of pushing your butt back, chomp back with your heels and go after his toes.  This isn't to disable the player, it is to give them something to think about.  I can tell you I instinctively do this once I feel two hands on my lower back during a rebound.
Lazily keeps hand on your back at all times or when you have ball away from basket - to manipulate your body (and possibly tug jersey when you take off).  This is illegal.  Refs hardly ever call this on a smaller player.  Chop their arm right at their wrist with your off forearm as you swing around.
Pushes your body as you shot.  To me this is one of the cardinal sins of intramural/pickup basketball.  Guys give you a little shove and you don't move much because you are bigger - but your damn shot is always slightly off.  The good news is for a person to do this they have to be playing your pretty close.  I handle this while shooting.  I keep two hands on the shot until the last possible second and push through towards the man.  If they are going in to push my stomach they are going to get a face full of ball or elbow.  The key is to start your shooting motion while cracking the other player on the chin.

The examples above are just examples.  How extreme you get with them is dependent on how cheap the player is playing and the crowd you are playing with.  Rules I live by (and the first we were taught at referee school):

always assume negative intent by the player.  If a player does something "wrong" it isn't an accident - in fact there are hardly ever accidents on the court, even the "accidents" have degrees of intent.  They have a mind and body just like you and you are not to be treated inferior because you have more of a conscience.  If someone is so dumb that they truly don't realize what they are doing then you will only be able to rationalize through them with action.
always assume positive intent by referee.  Most of the time the referee isn't calling things because they don't know better or they feel that it would interfere with the flow of the game.  If a player has their hands on your back and it stops a spin move you should chop their arms away (any good basketball coach will teach you this).  If the referee calls a foul on you don't overreact.  Simply have a small conversation, "Sir, he had two hands on my back and pushed me.  I know I fouled him but his hands were on my back for 5 seconds without a call."  Sometimes the only way to educate a poor ref is to get fouls called on yourself - this is a long-term approach and obviously should not be played with a minute left in a game down 1.
whenever you play against a cheap player - make sure you are guarding the cheap player on the other end.  It is a common ploy for a cheap player to hack the crap out of you and make sure you are not guarding them.
more than anything else - use the cheap player as motivation.  Play harder and more aggressive the cheaper they act.  This is a skill to bring your game up a notch AND stay under control.  Play harder, not violent.  Run the other player around on offense a bit.  Bump into them.
all of the advice I gave you in the examples involves skill.  The cheap player is skilled at playing cheap without getting a call against them.  If you are truly skilled you can jamb your arm through his face while putting up a shot, knock him over, and draw the foul - all legally of course :).  Everything takes practice and skill.  I play in leagues in the winter that are about DIII quality of play that are crystal clean.  Guys say sorry after fouling and so forth.  I play in a couple of summer leagues that after a game it looks like I was attacked by a lion.  It might take me a game or two or three to get my groove back in the retaliation department.  It is a defined skill (you are getting outskilled there right now).

The key to everything I am saying is use the "cheap" players tactics against them.  Just like in judo every offensive move has a counter.  Your opponent by doing these tactics is taking themselves away from playing sound D or rebounding right.  You must learn to use those things to your advantage.  If you have to step down your game to "take care of a player" then you aren't good enough to handle these things properly - yet.  And I say yet because I would expect if you haven't played organized ball you will have a few missteps/fouls/issues when trying to "legally retaliate".  You have to take care of yourself on the court and doing nothing will just lead to you not like playing the beautiful game.
Answer: 1)  It's not that cheap.  Pulling jersey, being grabby, etc. are all "in-between" type of plays.  It's physical play that isn't necessarily a foul.  Remember, basketball IS a physical sport.  Not every time players come in physical contact with each other it's a foul.
2)  Suck it up, no excuses.  The fact that it's frustrating you means you aren't being mentally tough enough.  Whining to everyone on the court will be the worst course of action.  Be grabby back, be physical back, use your body to shield their aggression or be timely with your movement to work against them.
3)  Never count on the refs to bail you out, you're going to have to use your own savviness, scrappiness, skill, and toughness.  That's a given.  But if your opponent is clearly going over the top and fouling you every play, just tell the ref to keep an eye on it.  If it's a pickup game with no refs, call a foul if it's OVERT physical contact, or be super physical back.
4)  Retaliate.  Be physical back, when they put their arm on you, slap it!
5)  If you're taller than average, you need to use that inherent advantage.  Taller than average + FEROCIOUS is a great combo.  Your mental approach on the court should be like someone with Napoleon-syndrome with everything to prove.  Like a small chihuahua.  Tall guy with the heart of a chihuahua?  That will be effective.  I can't tell you how many tall guys I've played vs who underachieved because they were too frail.  If they just knew how to use their frame and be MEAN on the court, they would be amazing.  Keep playing 'cause you'll learn the ropes by constantly competing.

Basketball isn't an easy sport.  It takes a great mixture of physical and mental toughness, finesse, athleticism, skill, and heart.  Enjoy!

Dealing with "cheap" opponents


psql: fatal role "root" does not exist

Question: I have gone through many SO question answer my problem was not solved..
This is the method I tried:
user@user-Latitude-XT3:~$ sudo su postgres
No passwd entry for user 'postgres'
user@user-Latitude-XT3:~$

and many others.
I keep on getting fatal error user does not exist
any working solution?
please Note before marking duplicate, tried all similar but wasn't solved yet.
Answer: This is how I normally login to postgres:
sudo -i
sudo -i -u postgres
psql

Edit:
if you are using Debian
su postgres
psql

Answer: Here how i fixed,

vi /etc/postgresql/9.3/main/pg_hba.conf

local   all             postgres                                peer
here change peer to trust

restart, sudo service postgresql restart

now try, psql -U postgres
Comment: after step 4 I get: `psql: FATAL:  Peer authentication failed for user "postgres"`
Answer: If you don't specify the user, psql will try to login with the current system logged in user. Try to add the user option (-U) to the psql command:
psql -U <existing role with permission>

psql: fatal role "root" does not exist


Sort cell array base on the 2D value

Question: I have a 3X3 cell array and each element store a (x,y) point.
The point are generate by random number from [0,1].
What I want to do is sort the cell array so that it looks like following
ex: 9 points
each circle is one 2D point
index:(1,1) in the left top corner and (3,3) to the right bottom corner as the usual array index

that is to ensure the topological order.
How do I do it?
Thank in advance.
for the example
pairs = [4 9 2 6 5 1 7 8 3; 9 6 2 1 3 8 7 4 5] (row 1 = x-values, row 2 = y-values))

what I want to do is put them in the cell array so that they can be connected by read lines like the image's topology.
Comment: Could you explain how you have arranged the numbers more specifically? You question is unclear to me.
Answer: The number of permutations is factorial(9), which is not terribly large. So a brute-froce approach is feasible: test all permutations for your desired conditions, and pick the first that is valid.
In the following I'm using a 2x3x3 array, instead of a 3x3 cell array containing length-2 vectors, because it's much easier that way.
N = 3;
data = rand(2,N,N);
permutations = perms(1:N^2); %// generate all permutations
for k = 1:numel(permutations)
    dx = reshape(data(1,permutations(k,:)),N,N); %// permuted x data
    dy = reshape(data(2,permutations(k,:)),N,N); %// permuted y data
    if all(all(diff(dy,[],1)<0)) && all(all(diff(dx,[],2)>0)) %// solution found
        disp(dx) %// display solution: x values
        disp(dy) %// y values
        break %// we only want one solution
    end
end

Note that for some choices of data there may not be a solution.

Sort cell array base on the 2D value


What are the common methodology can be used to find the parameter of the fixed and random effect in a nonlinear mixed effect model?

Question: Recently, I am doing some research about nonlinear mixed effect model. However, most of the time, they will just straight away use the R language nlme package and fit the model into it to get the result. Therefore, I am wonder what is the algorithm or methodology behind it..... I couldn't find any book or journal article which specifically explain the method to solve a nonlinear mixed effect model. Any recommended book or study material for solving nlme?
Answer: This paper has a lot of the details you're probably after (section 3 in particular):
https://arxiv.org/pdf/1406.5823.pdf
Although it's for lme4 rather than nlme. I'm not sure what the differences are under the hood.


How to change the nginx process user of the official docker image nginx?

Question: I'm using Docker Hub's official nginx image:
https://hub.docker.com/_/nginx/
The user of nginx (as defined in /etc/nginx/nginx.conf) is nginx. Is there a way to make nginx run as www-data without having to extend the docker image? The reason for this is, I have a shared volume, that is used by multiple containers - php-fpm that I'm running as www-data and nginx. The owner of the files/directories in the shared volume is www-data:www-data and nginx has trouble accessing that - errors similar to *1 stat() "/app/frontend/web/" failed (13: Permission denied)
I have a docker-compose.yml and run all my containers, including the nginx one with docker-compose up.
  ...
  nginx:
    image: nginx:latest
    ports:
      - "80:80"
    volumes:
      - ./:/app
      - ./vhost.conf:/etc/nginx/conf.d/vhost.conf
    links:
      - fpm

  ...

Comment: I think the better way is to create your own Dockerfile, that way it is reproducible. You can login to the container and change the user and restart the container, but that might be a maintenance issue in the future.
Answer: FYI

It is problem of php-fpm image
It is not about usernames, it is about www-data user ID

What to do
Fix your php-fpm container and don't break good nginx container.
Solutions

Here is mine post with solution for docker-compose (nginx +
php-fpm(alpine)): https://stackoverflow.com/a/36130772/1032085
Here is mine post with solution for php-fpm(debian) container:
https://stackoverflow.com/a/36642679/1032085
Solution for Official php-fpm image. Create Dockerfile:
FROM php:5.6-fpm
RUN usermod -u 1000 www-data

Comment: Why 1000??? Nginx user in nginx container is NOT `1000` so does not have permissions to read the files created by `php-fpm`
Comment: For the `php:rc-fpm-alpine` Alpine linux images, `usermod` does not exist as Alpine uses busybox. Here is the equivalent:

`RUN deluser www-data && adduser -DH -h /home/www-data -s /sbin/nologin -u 1000 www-data` –
Hopefully helpful for those using alpine.
Comment: After hours of searching helped a lot! I recommend others having same problem as I did (permissions in combination of Docker - nginx - php-fpm) to pay attention here.
Answer: I know the OP asked for a solution that doesn't extend the nginx image, but I've landed here without that constraint. So I've made this Dockerfile to run nginx as www-data:www-data (33:33) :
FROM nginx:1.17

# Customization of the nginx user and group ids in the image. It's 101:101 in
# the base image. Here we use 33 which is the user id and group id for www-data
# on Ubuntu, Debian, etc.
ARG nginx_uid=33
ARG nginx_gid=33

# The worker processes in the nginx image run as the user nginx with group
# nginx. This is where we override their respective uid and guid to something
# else that lines up better with file permissions.
# The -o switch allows reusing an existing user id
RUN usermod -u $nginx_uid -o nginx && groupmod -g $nginx_gid -o nginx

It accepts a uid and gid on the command line during image build. To make an nginx image that runs as your current user id and group id for example:
docker build --build-arg nginx_uid=$(id -u) nginx_uid=$(id -g) .

The nginx user and group ids are currently hardcoded to 101:101 in the image.
Comment: If running alpine nginx add shadow before trying to run usermod. Change usermod line above to: RUN apk add shadow && usermod -u $nginx_uid -o nginx && groupmod -g $nginx_gid -o nginx
Answer: Another option is to grab the source from https://github.com/nginxinc/docker-nginx and change the docker file to support build args Ex: of changing the stable Dockerfile of buser release (https://github.com/nginxinc/docker-nginx/blob/master/stable/buster/Dockerfile). to have the nginx user/group uid/gid set as build args
FROM debian:buster-slim

LABEL maintainer="NGINX Docker Maintainers <email@example.com>"

ENV NGINX_VERSION   1.18.0
ENV NJS_VERSION     0.4.3
ENV PKG_RELEASE     1~buster

#Change NGNIX guid/uid#
ARG nginx_guid=101
ARG nginx_uid=101

RUN set -x \
# create nginx user/group first, to be consistent throughout docker variants
    && addgroup --system --gid $nginx_guid nginx \
    && adduser --system --disabled-login --ingroup nginx --no-create-home --home /nonexistent --gecos "nginx user" --shell /bin/false --uid $nginx_uid nginx \

This way is safer than just doing usermod since if something is done in other places like
chown nginx:nginx  it will use the GUID/UID set


Does the link function in a GLM influence the plot of residuals?

Question: Could an inappropriate link function contribute to non-uniform residuals in a GLM, or could that only be caused by an inappropriate error structure?
Comment: Hi there, could you elaborate further on what you mean by "non-uniform" residuals?
Comment: It's unusual for the choice of link function to matter much, when fitting GLMs - this is effectively what the Li-Duan theorem says.
Answer: A brief answer is yes an inappropriate link function can lead to residuals appearing "non-random".   however it can also be due to a predictor which needs to be transformed.  I am assuming that you are refering to a plot of residuals against the linear predictor.
One way to check that it isn't t a predictor is to create pseudo "partial residuals".  These are done by $u_{ij}=\hat{g}(y_{i})-x_{i}^T\hat{\beta}+x_{ij}\hat{\beta}_{j}$ where i indexes observations and j indexes variables.  The "hat" on the link function refers to the first order taylor series of g commonly refered to as the working response in a irls algorithm.  you plot $u_{ij}$ against $x_{ij}$ (ie one plot per covariate) and it should look like a straight line.  If this passes then i would consider changing the link function.  Of course this is only feasible when you only have a small number of variables.
Note that there are no hard and fast rules for using diagnostics - this is one approach of many.


Windows Server 2008R2 not scavenging stale DNS records

Question: We have Domain Controllers where our internal DNS runs on.
2 Windows 2008R2 and 2 Windows 2012R2.
Our stale records are no longer removed for some time now, even when running the DnsCmd commands manually or through the GUI.
It seems to happen since we set dynamic updates to secure.
It happens for all AD-integrated zones and normal zones including reverse lookup zones.
Things I've tried:
https://social.technet.microsoft.com/Forums/windowsserver/en-US/02563ce5-d026-4519-83e1-0222ed72cf2f/dns-server-not-flushing-stale-records?forum=winserverPN
https://community.spiceworks.com/topic/254198-old-dns-records-not-being-scavenged
https://support.microsoft.com/en-us/kb/2791165
Answer: For the zone in question run the following command:
dnscmd /zoneinfo foobar.com

You will get the result like this:
Zone query result:
Zone info:
            ptr                   = 0000000000327C90
            zone name             = foobar.com
~snip~

            zone DN = DC=fopobar.com,cn=MicrosoftDNS,DC=DomainDnsZones,DC=foobar,DC=com          Scavenge Servers
~snip~
           Server[0] => af=2, salen=16, [sub=0, flag=00000000] p=13568, addr=192.168.1.1

Here you notice the IP address 192.168.1.1
This is the IP address of the only server which has the permission to scavenge the zone. Most likely this could be a server which is no longer existing - this happens a lot in Domains with a funktion level of 2008. If this is not the IP address of the server which on which you have configured Scavenging, you need to change that.
To change the Scavenging server for a zone, run the command:
dnscmd /zoneresetscavengeservers foobar.com <IP of the correct DNS Server>

And a few moments later, your DNS is working with Scavenging again.
Comment: Looks like it wasn't set on the server Properties ... _facepalm_. Have set it now and will evaluate.
Comment: Ok it is working. I've added multiple servers as "ScavengerServer".
Answer: Have you made any changes to the expiry interval?
Did you set DHCP option 81?
Maybe this guide can be helpfull:
http://blogs.msmvps.com/acefekay/2009/08/20/dhcp-dynamic-dns-updates-scavenging-static-entries-amp-timestamps-and-the-dnsproxyupdate-group/


Is a SSI-style cluster possible with Windows Server 2012?

Question: I use an application that does CPU intensive multithreaded optimization which is currently run on a hyper-threaded Quad Core machine that it just pegs at 95-100% utilization across all cores for hours. I am planning on running it on a 32 vCPU EC2 instance, but even then it could probably benefit from additional processing power.
My question is in regards to creating a cluster or similar to run this type of program on. This is a 3rd party 64bit Windows application that wasn't necessarily designed for distributed computing, and I am having a hard time figuring out if it is even possible to cluster Windows Server 2012 for this purpose.
From what I can tell I need something similar SSI (single system image) cluster that would allow the application to run like it is just a single powerful computer.
In a Windows environment is something like this or similar possible?
Answer: No, not possible. SSI is not supported outside of the hypervisors doing it. If you get one and use it then you can run windows on it, but windows by itself has no SSI capabilities.
Comment: So what your saying is in theory I could create an SSI and then run Windows on top of such a system, but other wise there is no other good way of going about this on a Windows system?
Comment: Exactly. No SSI support IN windows - running it as client does not require OS support. That said... this is the reason I rewrote our inhouse main software to be inhouse / not purchased... missing grid-capabilities.
Comment: In theory from a technical stand point how hard is it to make a multithreaded program cluster computing capable?
Comment: Depends totally. In my case we did a total rework. We also moved from "program controlled" to database controlled so that in case of a restart the work continues where it was last recorded in the database. Was worth it for us - this is our core business application and we are now maybe 1000 times faster than before and scalable. But generally it is a VERY Large undertaking.


CKEditor is adding inline style to resize my textarea on node add/edit form

Question: No matter how many rows I define the textarea to be in the content type configuration, I get a huge editor taking up almost the whole browser window in the node add/edit page. I tracked this down to CKEditor, which is hiding the actual textarea and adding an inline height to the table cell it uses to display the iframe containing the actual field. (Argh.)
Please share any advice on how to make it stop or override it? Since it's inline, I'm not hopeful about using normal CSS.
Answer: It turns out this is a documented problem in CKEditor. There are some workarounds posted at https://www.drupal.org/node/1154730 but I'd also be intersted in hearing any other ideas.


Check that a curve is a geodesic.

Question: Suppose $M$ is a two-dimensional manifold. Let $\sigma:M \rightarrow M$ be an isometry such that $\sigma^2=1$. Suppose that the fixed point set $\gamma=\{x \in M| \sigma(x)=x\}$ is a connected one-dimensional submanifold of $M$. The question asks to show that $\gamma$ is the image of a geodesic.
Answer: Let $N=\{x\in M:\sigma(x)=x\}$ and fix $p\in N$.
Exercise 1: Prove that either $1$ or $-1$ is an eigenvalue of $d\sigma_p:T_p(M)\to T_p(M)$.
Exercise 2: Prove that if $v\in T_p(M)$ is an eigenvector of $d\sigma_p:T_p(M)\to T_p(M)$ of sufficiently small norm, then the unique geodesic $\gamma:I\to M$ for some open interval $I\subseteq \mathbb{R}$ such that $\gamma(0)=p$ and $\gamma'(0)=v$ has image contained in $N$. (Hint: isometries of Riemannian manifolds take geodesics to geodesics.)
I hope this helps!

Check that a curve is a geodesic.


Pause media recorder programmatically. Camera.apk from samsung galaxy has `this.mMediaRecorder.pause();` does not work in my code

Question: Now, i have made a library to concatenate 2 videos, using the mp4parser library.
And with this i can pause and resume recording a video (after it records the second video, it appends it to the first one).
Now, my boss told me to do a wrapper, and use this for the phones that do not have hardware support for pausing a video. For phones that have that (Samsung Galaxy S2 and Samsung Galaxy S1 can pause a video recording , with their camera application), i need to do this with no libraries, so it would be fast.
How can I implement this native, if as seen on the media recorder state diagram, http://developer.android.com/reference/android/media/MediaRecorder.html , there is no pause state?
I have decompiled the Camera.apk app from an Samsung Galaxe Ace, and the code has in the CamcorderEngine.class a method like this:
public void doPauseVideoRecordingSync()
{
Log.v("CamcorderEngine", "doPauseVideoRecordingSync");
if (this.mMediaRecorder == null)
{
  Log.e("CamcorderEngine", "MediaRecorder is not initialized.");
  return;
}
if (!this.mMediaRecorderRecording)
{
  Log.e("CamcorderEngine", "Recording is not started yet.");
  return;
}
try
{
  this.mMediaRecorder.pause();
  enableAlertSound();
  return;
}
catch (RuntimeException localRuntimeException)
{
  Log.e("CamcorderEngine", "Could not pause media recorder. ", localRuntimeException);
  enableAlertSound();
}

}
If I try this.mMediaRecorder.pause(); in my code, it does not work, how is this possible, they use the same import (android.media.MediaRecorder). Have they rewritten the whole code at a system level?
Is it possible to take the input stream of the second video (while recording it), and directly append this data to my first video?
for my concatenate method, i use 2 parameters (the 2 videos, which both are FileInputStream), is it possible to take the InputStream from the recording function and pass it as the second parameter?
Answer:
If I try this.mMediaRecorder.pause();

The MediaRecorder class does not have a pause() function, so this is obvious that there is a custom MediaRecorder class on this specific device. This is not something unusual, as the only thing required from the OEMs is to pass the "android compatability tests" on the device; there is no restriction on adding functionality.

Is it possible to take the input stream of the second video (while
  recording it), and directly append this data to my first video?

I am not sure if you can do this, because the video stream is encoded data (codec header, key frames, and so on), and just combining 2 streams into 1 file will not produce a valid video file in my opinion.
Basically what you can do:

get raw data images from camera preview surface (see Camera.setPreviewCallback())
use a android.media.MediaCodec to encode the video
and then use an OutputFilStream to write to the file.

This will give you the flexability you want, as in this case you in you app decide which frames get into encoder, and which do not.
However, it maybe an overkill for your specific project, as well as some performance issues may rise.
PS. Oh, an by the way, try taking a look at the MediaMuxer - maybe it can help you too. developer.android.com/reference/android/media/MediaMuxer.html


Linebreak in  tag for any text

Question: I have long text. For example:

"GATEWAY_INTERFACE: CGI/1.1
SERVER_PROTOCOL: HTTP/1.1
REQUEST_METHOD: POST
QUERY_STRING:
REQUEST_URI: /
SCRIPT_NAME:
"

When displayed, it all merges into a single row in the cell, without hyphenation where there is \n
I need that when displayed inside the  tag, the lines are transferred without any additional tags.
Is possible?
Comment: Please don't make more work for other people by vandalizing your posts. By posting on the Stack Exchange network, you've granted a non-revocable right, under the [CC BY-SA 4.0 license](//creativecommons.org/licenses/by-sa/4.0/), for Stack Exchange to distribute that content (i.e. regardless of your future choices). By Stack Exchange policy, the non-vandalized version of the post is the one which is distributed. Thus, any vandalism will be reverted. If you want to know more about deleting a post please see: [How does deleting work?](//meta.stackexchange.com/q/5221)
Comment: why not simply use `` as linebreak? Otherwise word-wrap but then it break at a specific width not necessarly at every single list item (which as such is not tabular data anyways).
Comment: @tacoshy Is long way. I can  simple modificate css, and backend modification is not transparent here.
Answer: If you cannot insert
 tag inside the HTML, you can use white-space: pre-line on td.

td{
  white-space: pre-line;
}

      "GATEWAY_INTERFACE: CGI/1.1
      SERVER_PROTOCOL: HTTP/1.1
      REQUEST_METHOD: POST
      QUERY_STRING:
      REQUEST_URI: /
      SCRIPT_NAME: "

Edit: Source
Comment: @connexo I'll keep that in mind. The reason I answered it instead of commenting is that I tried it with **only** `td` and it was not working, and the Source that I linked does not have anything related to `td` so I just thought I'd answer it.
Comment: No no, try it with only `td` without the `` structure and it's not working. (I'm sure I'm missing something here)
Comment: @gormih Consider a different tone. Explain how your question differs from the one marked as a duplicate. From what I can see, https://stackoverflow.com/a/21577945/3744304 exactly answers the question.
Comment: @DebsmitaPaul No worries, there was nothing wrong with your tone. I just had some minor disagreements with gormih's behaviour.
Comment: `td` is no different from any other element with regard to this problem.
Comment: @conexo Answer essentially to the person to whom you asked the question and received the answer. (@DebshmitaPaul)
Comment: I'm sorry if anything in my last comment sounded harsh, it was completely unintentional. I tried to explain why i posted this, not to prove it is unique or has any extra useful information, but to say that it is me that didn't understand why it wasn't working with td alone. @connexo you have enlightenment me on a certain mistake to not answer duplicate questions, which I thought was ok to do, and it is not.

Linebreak in  tag for any text


Reduce a list of custom objects in java

Question: I have two custom classes called OrthogonalPoint and PolarPoint.
public class OrthogonalPoint extends AbstractPoint<OrthogonalPoint> {
    private double x;
    private double y;

    // constructor, getters, ...
}

public class PolarPoint extends AbstractPoint<PolarPoint> {
    private double rho;
    private double theta;

    // constructor, getters, ...
}

Both extend an abstract class AbstractPoint.
public abstract class AbstractPoint<PointType extends AbstractPoint<PointType>> {

    public abstract double getX();

    public abstract double getY();

    public final double distance(PointType other) {
        // calculate distance between current point and other point
    }
}

Next, I have a class Route.
public class Route<T extends AbstractPoint<T>> {

    private final List<T> points = new ArrayList<>();

    public void appendPoint(T point) {
        this.points.add(point);
    }

    public double routeDistance() {
        // calculate total distance
    }
}

A route is an ordered number of points whose length is defined as the sum of the distances of the points in the sequence. So, if a route consists of three points (p1, p2, and p3) the distance of the route is p1.distance(p2) + p2.distance(p3).
In the routeDistance function, I want to calculate this distance. I have tried something like
public double routeDistance() {
    return this.points.stream().reduce(0d, (point, point2) -> point.distance(point2));
}

But the body part of the lambda function is underlined red:
Bad return type in lambda expression: double cannot be converted to T

What would be the correct way to calculate the distance? I would like to use the reduce, but any solution is appreciated.
Comment: An orthogonal point is defined by 2 numbers (x and y); to find the point, start at the origin (not, usually, part of the definition of the point itself), and go 'x' distance on the x axis and 'y' distance on the y axis. A polar point is defined by 2 numbers (r and d); to find the point, start at the origin, and then go 'd' distance at an angle of r. In other words, __PolarPoint has absolutely no business having an x and y value here__. AbstractPoint should not have `.getX()` and `.getY()`, or if it should, PolarPoint's .getX() method will need to do quite a bit of math.
Comment: @rzwitserloot Thank you for the comment, I made a simple copy-paste mistake. PolarPoint has class variables rho and theta (instead of x and y). ```.getX``` and ```.getY``` do quite a bit of math as you said. For example, ```.getX``` returns ```this.rho * Math.cos(this.theta)```
Answer: Your problem is that you use reduce in the wrong way. Reduce doesn't get two elements from your stream but the current accumulator and the current element and combine them to get the new accumulator. Here is a good tutorial on reduce: https://www.baeldung.com/java-stream-reduce
The easiest way here is to not use stream. As you need to keep the order of each two points, just use a regular for loop with i between 0 and n-1 to loop over all sub routes and sum the lengths.
Comment: I was endeed following the baeldung tutorial, unfortunately it doesn't have a useful example for me. I need to pass the next point in the list as a parameter to the current one. Maybe there is no way to solve this with streams, I will use the good old for-loop for now.
Answer: You can't reduce a Point to a Double. If you need to use an ArrayList then you can mapToDouble and then sum() (a special case of a reduction):
points.stream().skip(1).mapToDouble(point ->
        points.get(points.indexOf(point) - 1).distance(point)).sum();

or
points.stream().limit(points.size() - 1).mapToDouble(point ->
        point.distance(points.get(points.indexOf(point) + 1))).sum();

With ÌntStream you can do:
IntStream.range(1, points.size()).mapToDouble(i ->
        points.get(i - 1).distance(points.get(i))).sum();

or
IntStream.range(0, points.size() - 1).mapToDouble(i ->
        points.get(i).distance(points.get(i + 1))).sum();

Comment: All your examples work wonderfully! I will go with the first one :)

Reduce a list of custom objects in java


A question about the choice and interpretation of the jumping distribution in Metropolis-Hastings algorithm

Question: In order to implement the MH algorithm you need a proposal density or jumping distribution $q(⋅|⋅)$, from which it is easy to sample. If you want to sample from a distribution $f(⋅)$, the MH algorithm can be implemented as follows:

Pick a initial random state $x_0$.
Generate a candidate $x^*$ from $q(⋅|x_0)$.
Calculate the ratio $\alpha=\frac{f(x^*)}{f(x_0)} \frac{q(x_0|x^*)}{q(x^*|x_0)}$.
Accept $x^*$ as a realisation of f with probability min(1,α).
Take $x^*$ as the new initial state and continue sampling until you get the desired sample size.

$q$ is often symmetrical so $\frac{q(x^*|x_0)}{q(x_0|x^*)}=1$
I have two questions :

Does $q$ describe the Birth-or-Death move that is often associated with Metropolis Hastings algorithm? When would you want to take $q$ non symmetrical? A colleague of mine wants to implement MH for sampling from a complex distribution (Y is a sample from X with a distribution $f$), and said he would impose different probabilities of picking $u$ in $X-Y$ to make the chain converge quicker (with Y the sample at a time and $\{Y-{v}\}\cup{\{u\}}$ the sample retained the next time if the ratio is big enough at step 3). Is it standard?
The context in which I personally use MH algorithm is for Bayesian model averaging. In this context, I have some models $M_i$ with an a priori probability $\pi$, some data D and an a posteriori probability I want to sample from. So the ratio of the 3th step of the algorithm becomes $\frac{f(D|M_i)\pi(M_i)}{f(D|M_j) \pi(M_j)}$ (Bayes formula). Do you agree that $q$ in this case is still about the modification of $M_i$ between two iterations and the Bayesian context doesn't change anything about it? Shouldn't my colleague adopt a Bayesian approach and choose a a priori distribution on the observations to favour those he wants to select more often rather than changing the jumping distribution?

Sorry for the naive questions, I want to be sure I understood the algorithm.
EDIT : some of you say there is no link between MH and Birth-death moves, but here is what is explained in the vignette of the BMS package I use :
"In addition to enumerating all models, BMS implements two MCMC samplers that differ in the way they propose candidate models:

Birth-death sampler (bd): This is the standard model sampler used in most BMA routines. One of the K potential covariates is randomly chosen; if the chosen covariate forms already part of the current model Mi, then the candidate model Mj will have the same set of covariates as Mi but for the chosen variable ('dropping' a variable). If the chosen covariate is not contained in Mi, then the candidate model will contain all the variables from Mi plus the chosen covariate ('adding' a variable).
Reversible-jump sampler (rev.jump): Adapted to BMA by Madigan and York (1995) this sampler either draws a candidate by the birth-death method with 50% probability. In the other case (chosen with 50% probability) a 'swap' is proposed, i.e. the candidate model Mj randomly drops one covariate with respect to Mi and randomly adds one chosen at random from the potential covariates that were not included in model Mi.
Enumeration (enum): Up to fourteen covariates, complete enumeration of all models is the default option: This means that instead of an approximation by means of the aforementioned MCMC sampling schemes all possible models are evaluated. As enumeration becomes quite time-consuming or infeasible for many variables, the default option is mcmc="bd" in case of K > 14, though enumeration can still be invoked with the command mcmc="enumerate"."

I just want to know if there is a link between the sampling option and $q$.
Comment: I'll come back to this question later, but you should really look at the original paper.  It explains everything from scratch pretty well.
Comment: As pointed out by Neil G. in his answer, those are different issues: if you want to penalise non-sparse models, your prior $\pi$ should reflect this. The choice of $q$ is important in exploring the space of models faster and focussing on those with high posterior probability. A major change in $\pi$ should induce a major change in $q$ to keep the efficiency high.
Comment: @Xi'an, yes I get that, but what is the link with q ?
Comment: In both Birth-and-death and for the more general reversible jump sampler, you have to pick a proposal $q$ that is most often non-symmetric because there usually are more ways to kill one term than to add one term.
Comment: Ok but q is exactly what defines the sampler, right ?
Comment: thanks !! That was just the point I wasn't sure about and kept asking, perfect, thank you !
Comment: @Xi'an my final question would be : is it better to choose a $q$ that favours smaller models (in my model selection problem) or choose a prior on models ? $q$ seems to be the crucial point for efficiency in high dimensionnal distribution if I understand well all the comments in this page
Comment: @Xi'an about your last comment, as you can see in the documentation of the BMS package I copied, a change in $\pi$ doesn't impact at all the choice of $q$, I know that in my context the choice of $\pi$ is important to coerce the algorithm to visit more often smaller models, I was asking about my colleague use case's that I described in question 1.
Comment: @Xi'an thanks for your editing but my question is not about bayesian context, much about the interpretation and choice of $q$ in different contexts (bayesian is one of them), plus it is not about feature selection (which is a consequence of the approach but off topic regarding the question I asked), more about model selection... And reversible-jump seems to be a particular case.
Answer: As signalled by bdeonovic, there seems to be some confusion in your understanding of Metropolis-Hastings algorithms. What you describe is the standard version of the algorithm where both target $f$ and proposal $q(\cdot|x)$ are densities against the same dominating measure (e.g., the Lebesgue measure). In this framework, the proposal $q(\cdot|x)$ can be absolutely anything and be chosen in terms of the target $f$ [and of the observations in a Bayesian setting] and of its mixing performances. For instance, when $q(\cdot|x)$ is a random walk, the scale of the random walk can be selected for the acceptance rate to stay around 0.234. But non-symmetric versions are also available like the Metropolis-adjusted Langevin (MALA) algorithm which is asymmetric and aims at bringing the chain towards the mode(s) of the target $f$.
You seem to be interested in model choice, where the measure issues are much more complicated because the target is defined on a space of varying dimension, with the measure being a direct sum of measures. thus requiring the move to be equally measurable against this sum. Green (1995) managed to formalise this requirement into a valid framework and produced the reversible jump Metropolis-Hastings algorithm, which works by pairs of models and spaces and proposals. While the implementation can be brought down to a reasonable level of difficulty, the presentation of the algorithm does not fit in a forum answer. I thus suggest you read the reference by Green (1995) or a book like my book with George Casella (2004, Chap. 11).
As for your question #2, if you can compare directly the models via the marginal likelihoods $p(D|M_i)$, there is no need for reversible jump as you are working on a finite or countably discrete space of model indices. Any proposal exploring this space produces a valid Markov chain on the model indices but in cases you can compute directly those probabilities $p(D|M_i)\pi(M_i)$ there is even no need for MCMC since all you have to do is select the highest value or average across models. If you cannot list (and compare) all models, you need a proposal $q$ that considers enough model indices at once to guarantee irreducibility of the resulting Markov chain: since $q$ can be asymmetric, it should appear in the ratio.
Comment: I don't understand your last paragraph, in my context MCMC is used to avoid testing all the models since the dimension of the space may be very high, right ?
Comment: I edited my question to clarify
Comment: Do you mean the number of models can be very high?
Comment: yes, for k regressors, you can have 2^k models
Answer:
$q$ is the proposal distribution.  I've only ever seen symmetric $q$, but it's okay to make it asymmetrical since you're dividing the ratio out in $\alpha$.  It's normal to choose $q$ so that the chain converges more quickly.  If $q$ is too wide, then you have a lot of rejected points, and if it's too narrow, it takes a long time to explore the high probability areas.
$q$ has nothing to do with your $\pi$ or $f$ or $M$.  The $f$ in step 3 is your Bayesian posterior (likelihood times prior).  Changing $q$ should not affect your sampled distribution (if it does, that's a bad $q$, and you would have to pick a weird $q$ for that to happen.)
Comment: I don't think the standard Metropolis-Hastings algorithm has anything similar to the concept of birth-death moves. This sounds like Reverse-Jump Markov Chain Monte Carlo (RJMCMC)
Comment: Ok, so far I am reassured by your answer : so does q describe the Birth-or-Death move that is often associated with metropolis hastings algorithm?
Comment: I edited my question to clarify
Answer: I would add to other answers that $q$ can be chosen as asymmetric when the support of the prior for a given parameter is restricted. For example, if $p(\theta<0)=0$ then it could be interesting to choose a proposal avoiding negative $\theta$  e.g. using $q(.|x)$ as a gaussian density with location parameter $x$ truncated on $R^+$. In such a case $q(x_1|x_2) \ne q(x_2|x_1)$. This can easily noticed by considering that in a truncated normal density, the value of the location parameter appears in the normalisation constant of the density (and is thus different in $q(.|x_2)$ and $q(.|x_1)$).


Can't preselect time zone in hook_form_alter

Question: I'm writing a custom installation profile/distribution and I want to pre-populate some fields in the 'Configure Site' form (/core/install.php).
I have managed to prefill/preselect other fields like (Site name, Site email address and Default country) but cannot preselect the Default time zone field. This is the code I am using:
function mydistribution_form_install_configure_form_alter(&$form, FormStateInterface $form_state) {
  $form['site_information']['site_name']['#default_value'] = 'Dummy Site Name';
  $form['site_information']['site_mail']['#default_value'] = 'firstname.lastname@example.com';

  $form['regional_settings']['site_default_country']['#default_value'] = 'DE';
  $form['regional_settings']['date_default_timezone']['#default_value'] = 'Europe/Berlin';
}

As you can see in the screenshot, I manage to change the Default country successfully, but not the Default time zone.
The "strange" thing though is that when I inspect the code, I can see that the correct timezone has been selected but the form displays London.

I'm based in the UK so I guess this is how London gets selected.
Does anyone know how to get this fixed? Thank you in advance!
Answer: Drupal adds some JS to detect the timezone (through core/misc/timezone.js). This is interfering with your code, but can be removed easily:
unset($form['regional_settings']['date_default_timezone']['#attributes']);

This removes the timezone-detect class from the <select>, stopping it from being processed by the JS.
Comment: Thank you so much Clive! That resolved my issue.


Customizing UIAlertController in iOS8

Question: As in iOS8 UIAlertView is deprecated.we should use UIAlertController.
I want to customize it like font color, font family of message label of alertcontrller's view, also change background color of ok button.i don't know the right way to do that.
Please Help!!
Any help will be appreciable!!
Comment: s you can customize the uialert u need to loop in the subviews and change as per your requirement … and pls show your your and ask don't ask blankly how ...
Comment: yah Thanks! but is'n there any better soltion than looping?
Comment: or else you subclass the control or just go for custom view
Comment: Try My Code For UIAlertController in ios8
Answer: I think, you have been perform task with them. But I think it's useful for someone.
Below code is working perfectly with my requirements. Please do changes according to your requirements.
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil
                                                                         message:nil
                                                                  preferredStyle:UIAlertControllerStyleActionSheet];

UIAlertAction *setCoverPhoto = [UIAlertAction
                                actionWithTitle:@"First Button"
                                style:UIAlertActionStyleDefault
                                handler:^(UIAlertAction *action){

                                    NSLog(@"First Button");

                                }];
[alertController addAction:setCoverPhoto];

UIAlertAction *deleteImageAct = [UIAlertAction
                                 actionWithTitle:@"Second Button"
                                 style:UIAlertActionStyleDefault
                                 handler:^(UIAlertAction *action) {

                                     NSLog(@"Second Button");

                                 }];
[alertController addAction:deleteImageAct];

UIAlertAction *setImageASNotif = [UIAlertAction
                                  actionWithTitle:@"Third Button"
                                  style:UIAlertActionStyleDefault
                                  handler:^(UIAlertAction *action) {

                                      NSLog(@"Third Button");

                                  }];
[alertController addAction:setImageASNotif];

alertController.view.tintColor = [UIColor whiteColor];

UIView *subView = alertController.view.subviews.firstObject;
UIView *alertContentView = subView.subviews.firstObject;
[alertContentView setBackgroundColor:[UIColor darkGrayColor]];

alertContentView.layer.cornerRadius = 5;

[self presentViewController:alertController animated:YES completion:nil];

Answer: Pretty darn good tutorial over at Matt Thompson's site:
http://nshipster.com/uialertcontroller/
Also, how to configure the alert on the iOS Developer Library:
https://developer.apple.com/Library/ios/documentation/UIKit/Reference/UIAlertController_class/index.html
Comment: Thanks @Steve Rosenberg.but can u give me link for Objective-C too.
Comment: http://pivotallabs.com/uialertcontroller-ios-8/  of course the apple site is in Obj C and Swift
Comment: this will not change the background color of OK button
Comment: tintcolor discussed here:  http://stackoverflow.com/questions/25795065/ios-8-uiactivityviewcontroller-and-uialertcontroller-button-text-color-uses-wind
Comment: @ CarouselMin is there any way to change the background color of ok button?
Comment: This does not answer the OP's question of how to configure the appearance of the alert view.
Comment: Down voted for two reasons: 1. This is essentially a link only answer. There is no good information in the answer without those links. 2. Neither of these links provide information on *customising* the controller as per the question: `I want to customize it like font color, font family`

Customizing UIAlertController in iOS8


How to hide the grid lines from Yaxis and draw only one line from specific Yaxis points?

Question: I am creating a view using the Charts module. I am using the (interactive) Google Charts API as the charting engine.
Is it possible to hide other gridlines and only display one grid line from a specific y axis point?
Just like in this image:
Comment: You could do this with chart_definition_alter function. See the question and answer about **charts module settings per chart** (with views integration): http://drupal.stackexchange.com/questions/137737/charts-module-settings-per-chart-with-views-integration
Answer: Refer to HowTos about vertical axis, located within the Community documentation of the Charts module. Here is the relevant part of it:

Refer to #2356053-2: Automatically adjusted value range for vertical axis, which explains how to automatically adjust the minimum and maximum of the Y-axis to fit the available data. Specifying a "Max" and "Min" value is optional. Specifying a minimum of 0 is recommended in the event that numbers will always be positive, while for the maximum value the recommendation is (usually) to just leave it empty.
To experiment with this in your own site, use the column chart with the number of nodes for each content type (located in charts/examples/views ):

If you do not specify a maximum there, you get a close to perfect chart, no?
If however you only have a few nodes (like a dozen or so) but use a huge maximum (like 240 ...), the chart looks not so nice, right?
Comment: Any feedback on this?


OLS: $E[\epsilon_{it}^T\epsilon_{it}] \not= 0$ in 1st equation biases standard errors in 2nd equation?

Question: Suppose ${X_{it}},{Y_{it}}$ are time series with $X_{it}\sim N(0.1,1)$, ($\sigma^2(Y_{it}) = 1$ and $mean(Y_{it})$ is similar to that for $X_{it}$, but changes when the dummy = 1). and $t \in \{1,2,...,200\}$, $i \in \{1,2,...,N\}$. In a real world setting this will be periodic stock market returns over $N$ firms (but you can ignore this). There is a dummy, $D_t$ that's equal to unity over $t \in \{150,151,...,200\}$ and equal to zero otherwise. The time series model to be estimated with OLS $\forall i$ is:
$(1) Y_{it} = \alpha_i + \beta_i X_{it} + \gamma_i D_{t} + \epsilon_{it}$
This model generally adheres to the Gauss-Markov assumptions for each $i$. However, we have $E[\epsilon_{it}^T \epsilon_{jt}] \not= 0$ for all $i$ and $j$.
The next step is to construct a vector of gammas using the $N$ estimates of model $(1)$. Call this vector $\bf{\hat{\gamma}}$. We then use this in the cross-sectional model:
$(2) \hat{\gamma}_i = a + b Z_i + u_i$
where $Z_i$ is some cross-sectional variable that doesn't cause any violations in OLS assumptions and is relevant for explaining $\hat{\gamma}_i$.

The claim in the applied econometrics literature is that $E[\epsilon_{it}^T \epsilon_{jt}] \not= 0$ in model $(1)$ leads to (i) No problem for the OLS coefficient estimates in $(2)$, but (ii) Biased standard errors in $(2)$.

Can someone please post ideas about why this is the case?
I don't understand what $\epsilon_{it}^T$ is in the expression $E[\epsilon_{it}^T \epsilon_{jt}] \not= 0$. Of course $\epsilon_{it}$ is a scalar and you can't transpose a scalar. This is seen HERE, where they apply this methodology.
Comment: You say that you don't understand why variance estimates are biased in eq 2  and then you say that we can ignore your $\gamma$ estimate which happens to be equation 2 ? I think I understand what do you mean and could give an speculative answer to that but it will be better for you to precise your question.
Comment: In your setup $Y_{it}$ cannot be stationary, since its mean depends on $t$.
Comment: There are three versions of the expectation (one in the title, another in the body, and a third in the comments). All of them incorporate a mysterious transpose even though in all the cases only scalars are present. Do you mind editing your post to clarify?
Comment: @mpiktas Correct observation, $Y_{it}$ has different mean after $t=150$ (given $\gamma_i \not= 0$). Thanks.
Comment: Some good answers have been delivered -- I would just add that this needs to be estimated as a random coefficients model (aka multilevel model for sociologists and psychologists, aka mixed model for biostatisticians). If economists do not know this, and estimate it with a two-step procedure, that's just too bad for them (and I am still waiting for Fama-Macbeth standard errors to die, which apparently they just don't want to do).
Answer: In order to be sure you need to go into the details, this implies comparing the true variance covariance matrix with the one you get in the second ols stage.
The true one:
This can be obtained by replacing eq.2 into eq.1, pooled OLS follows, and from it, the true $\hat a , \hat b$ variance covariance matrix:
$Y_{it} = \alpha_i + \beta_i X_{it} + aD_t + bD_tZ_{i} +D_t u_{i} + \epsilon_{it}$
Using matrix notation to split the  equation in $\gamma$ parameters and others leads to:
$Y = X\theta + Z\gamma + \varepsilon$
where we are interested in $V(\hat \gamma)$ , $\gamma=[a \; b] $, Z is a two column vector $Z=[D_t \; D_tZ_i]_{[i=1,..,N;t=1,...,T]}$ ( a similar structure defines X but this is not of interest) and where $V(\varepsilon) =\Sigma$ has a full structure of between firms covariances that's why it's not diagonal ($\sigma^2I_{NT}$)
like in the GAUSS-MARKOV assumptions. By Frish-Waugh we can express $\gamma$ ols as :
$\hat \gamma = (Z'M_{X}Z)^{-1}Z'M_{X}Y$ where $M_X= I-X(X'X)^{-1}X' $
which implies the following true variance:
$V(\hat \gamma) = H\Sigma H'$ where $H = (Z'M_{X}Z)^{-1}Z'M_{X}$
The other one
Under the assumption of non correlated firms (and time periods but this is not the issue), $\Sigma$ has a simplier diagonal structure $\Delta$. This means that $\Delta$ triangular terms are 0. Under an even simpler specification,( the one that is estimated by default by econometric and statistical software for OLS) $\Sigma$ follows GAUSS-Markov assumptions meaning that even the diagonal terms are equal thus $\Sigma$ is downgraded to $\sigma^2I$
This implies that not considering between firms correlation would lead to $V(\hat\gamma) $as:
$V(\hat \gamma) = H\Delta H'$ or $V(\hat \gamma) = H\sigma^2I H' \equiv \sigma^2(Z'M_xZ)^{-1}$
which, as it can be seen, are not equal to the true one.
Comment: I think the notation is innacurate, he uses scalars where vectors are needed to refer to the fact that between firms covariances are not zero so his notation implies $\epsilon_{it} = [\epsilon_{it}]_{i=1,...,N}$ is a N rows vector. Another interpretation is that he is refering to $ij$ element of $\epsilon_{.t}^T\epsilon_{.t}$. In both cases he means the same thing, but as it's not a quantitative journal ambiguities in math notation happen...
Comment: With different words.. I'm basiclly giving the same answer @mpiktas gave
Comment: (1) Really fantastic. (2) Seems like you've ignored $D_i u_i$ when you expressed the model in matrix form? This shouldn't change anything you've done though. (3) Would you know why Portfolio OLS gives correct SEs? (See the 1986 paper I linked). Don't bother with answer (3) if you wouldn't enjoy figuring that problem out.
Comment: (2) I didn't put all the definitions in order to let some for intuition and to avoid kronecker products... this way the demo goes "faster".  But you may deduce that the new random term is $\varepsilon_{it} = D_tu_i + \epsilon_{it}$, this means that if firms were correlated by $u_i$ then this causes the new random term $\varepsilon_{it}$ to be correlated on its firms dimension as well. (3) didn't hear about a portfolio OLS, but i guess it's a just another name to something that already exists in standard econometrics to del with full Var matrices, like WLS, or Robust OLS, etc.
Comment: (3) a good estimate implies a good $\Sigma$ estimate , the portfolio OLS somehow is estimating the full structure $\Sigma$ and not only variances without covariances: $\Delta$ or a single variance: $\sigma^2$
Comment: Can't redit my previous comment but in fact, between firm correlation comes not only from $u_i$ but from $\epsilon_{it}$ as well.
Comment: Do you know why Forbes (2004) says $E[\epsilon_{it}^T\epsilon_{jt}] \not= 0$. What's the transpose of a a scalar mean?
Comment: if fact $\epsilon_{.t}$ must a row vector with N elements... so the product  $\epsilon_{.t}^T \epsilon_{.t}$ is the matrix of between firms crossproducts
Answer: I am putting up another answer with more details.
In standard linear regression model (in matrix form):
$$Y=X\beta+\varepsilon$$
the OLS estimate is the following
$$\hat\beta=(X^TX)^{-1}X^TY.$$
Its variance then is
$$Var(\hat\beta)=(X^TX)^{-1}X^TVar(Y)X(X^TX)^{-1}.$$
The usual assumption for regression is that
$$Var(Y)=\sigma^2I,$$
where $I$ is the identity matrix. Then
$$Var(\hat\beta)=\sigma^2(X^TX)^{-1}.$$
Now in your case you have two models:
$$Y_{i}=M_i\delta_i+\epsilon_i$$
and
$$\Gamma=Lc+u,$$
where

$Y_i^T=(Y_{i1},...,Y_{iT})$,
$M_i=[1,X_i,D]$, with $X_i^T=(X_{i1},...,X_{iT})$, $D^T=(D_1,...,D_T)$
$\delta_i^T=(\alpha_i,\beta_i,\gamma_i)$
$\epsilon_i^T=(\epsilon_{i1},...,\epsilon_{iT})$
$\Gamma^T=(\gamma_1,...,\gamma_n)$
$L=[1,Z]$, with $Z^T=(Z_1,...,Z_n)$
$c^T=(a,b)$
$u^T=(u_1,...,u_N)$.

Note that you state second model for the estimates of $\gamma$, which is not usual, hence I restate it in usual form, for the "true" $\gamma$.
Let us write down the covariance matrix for OLS estimates of coefficients $c$:
$$Var(\hat{c})=(L^TL)^{-1}L^TVar(\Gamma)L(L^TL)^{-1}$$
The problem is that we do not observe $\Gamma$. We observe the estimates $\hat\Gamma$. $\hat\gamma_i$ is part of vector
$$\hat\delta_i=\delta_i+(M_i^TM_i)^{-1}M_i^T\epsilon_i.$$
Assume that $\delta_i$ are random and independent with $\epsilon_i$ and $M_i$. This surely holds for $\gamma_i$ so we do not lose anything if we extend this for other elements of $\delta_i$.
Let us stack all $\hat\delta_i$ on top of each other:
$$\hat\delta^T=[\delta_1^T,...,\delta_N^T]$$
and explore the variance of $\hat\delta$:
$$Var(\hat\delta)=\begin{bmatrix}
Var(\hat\delta_1) & cov(\hat\delta_1,\hat\delta_2) & \dots & cov(\hat\delta_1,\hat\delta_N)\\
\dots & \dots & \dots & \dots\\
cov(\hat\delta_n,\hat\delta_1) & cov(\hat\delta_n,\delta_2) & \dots & Var(\hat\delta_N)
\end{bmatrix}$$
Assume that $Var(\epsilon_i)=\sigma^2_\epsilon I$ and that $E\epsilon_i\epsilon_j^T=0$.
For $i\neq j$ we have
\begin{align}
cov(\hat\delta_i,\hat\delta_j)&=cov(\delta_i,\delta_j)+cov((M_i^TM_i)^{-1}M_i^T\epsilon_i,(M_j^TM_j)^{-1}M_j^T\epsilon_j)\\
&=(M_i^TM_i)^{-1}M_i^TE(\epsilon_i\epsilon_j^T)M_j(M_j^TM_j)^{-1}\\
&=0
\end{align}
For diagonal elements we have
$$
Var(\hat\delta_i)=Var(\delta_i)+\sigma_\epsilon^2(M_i^TM_i)^{-1}
$$
Let us turn back to variance of $\hat c$. Since we substitute $\hat\Gamma$ instead of $\Gamma$ the variance is the following
$$Var(\hat{c})=(L^TL)^{-1}L^TVar(\hat\Gamma)L(L^TL)^{-1},$$
We can extract $Var(\hat\Gamma)$ from $Var(\hat\delta)$ by selecting appropriate elements:
$$Var(\hat\Gamma)=Var(\Gamma)+diag(g_1,...,g_n)$$
where $g_i$ is the element of $\sigma_\epsilon^2(M_i^TM_i)^{-1}$ corresponding to the $Var(\hat\gamma_i)$. Each $g_i$ is different from $g_j$ since they correspond to different $X_{it}$ and $X_{jt}$ which are not assumed to be equal.
So we get the surprising result, that algebraically even if we assume all the necessary properties, the resulting covariance matrix at least algebraically will not be equal to usual OLS covariance matrix, since for that we need that $Var(\hat\Gamma)$ is constant times identity matrix which it is clearly not.
All the formulas above were derived assuming that $X_{ij}$ are constant, so they are conditional on $X_{ij}$. This means that we actually calculated $Var(\hat\Gamma|X)$. By putting additional assumptions on $X_{ij}$, I think it would be possible to show that unconditional variance is OK.
The independence assumption placed on $\epsilon_i$ can also be relaxed to uncorrelatedness.
It would also be possible to use simulation study to see how covariance matrix differ if we use $\hat\Gamma$ instead of $\Gamma$.
Answer: I think the problem lies in definition of the second model. I think it is assumed that
$$\gamma_i=a+bZ_i+u_i$$
with the usual assumption that
$$cov(\gamma_i,\gamma_j|Z_1,...,Z_N)=0,$$
i.e. that the $\gamma_i$ are not correlated if we control for $Z_i$. Now when you substitute $\hat{\gamma}$ instead of $\gamma$, you need to check whether the assumption holds, i.e. if
$$cov(\hat{\gamma_i},\hat{\gamma}_j|Z_i)=0.$$
Now
$$\hat{\gamma}_i=\gamma_i+L(\epsilon_{it}),$$
where $L$ is some linear function. It is safe to assume that $\epsilon_{it}$ is independent of $Z_i$, but if $E\epsilon_{it}\epsilon_{jt}\neq0$, the necessary assumption does not hold.
Since the uncorrelatedness assumption is central to calculation of usual OLS statistics, this gives the reason why the standard errors are biased.
This was a rough outline, but I think the idea should work if you'd get into nitty gritty details of OLS machinery.


Group Policy to ensure psexec, remote WMI, and remote registry works

Question: I have been searching the Internet for the past week for the answer to my question, but couldn't find any conclusive answer, so I ask here.
Based on your experience and/or knowledge, what policies could/should be enforced through Group Policy to ensure that all computers in the domain are manageable remotely using the triumvirate of psexec, remote WMI, and remote registry?
Background of my question: when I audited the computers in the domain, I would encounter computers that are not psexec-able, or remote WMI queryable, or remote regedit-able, or a combination of the three. This forced me to every time devise workarounds, a job that took away too much valuable time. So, rather than wasting time again and again, I'd rather enforce uniformity via a domain-wide GPO.
PS: The targets of operation are Windows XP SP3 and Windows 7 Professional/Enterprise.
Comment: Really depends on what specific settings are blocking those remote tools... and, FYI, it's the case often enough that something not working properly and that's what prevents access using these tools, rather than a cofiguration or setting that needs changed.
Comment: For psexec you will normally also need to set an exception in your antivirus software. It works in a way that AV software should be blocking for the general case.
Comment: @John since the antivirus is set and configured centrally (SEP), and everyone is using the same, I don't think that's the reason
Answer: Mmmm...  thoughts:
PSExec - just requires the remote PC to be contactable via RPC and SMB.  Plus, you need the appropriate rights at the other end to remotely interact with the Service Control Manager (this could be forced via Group Policy Preferences).  So, assuming the PC is operational...: If the PC is on the domain, then the Windows Firewall should let you in, unless you've tweaked the domain-connected firewall settings.  Anti-virus products might see PSExec as a "Potentially unwanted Program".  So, possibly some registry settings here to ensure it's allowed to execute.
WMI - Again, needs RPC to be functioning.  You might want to force the WMI services to be running via GPOs.  One snag with WMI is when a 3rd party product fecks up the WMI repository.  Seen this so many times.  Only fix is a manual recompile.
Remote Registry - Again, RPC and privs.  Plus, you could force the service to be running via GPOs.
Comment: Thanks for the breakdown! On Monday, I'll check up on the problematic computers to ensure that WMI is healthy. In the meantime, I'm going to force RpcSs to run via GPO. I'll post another comment on my findings.


How to convert Array[String] into spark Dataframe to save CSV file format?

Question: Code that I'm using to parse the CSV
val ListOfNames = List("Ramesh","Suresh","Ganesh") //Dynamical will add list of names
val Seperator = ListOfNames.map(x => x.split(",")  //mkString(",")

sc.parallelize(Array(seperator)).toDF().csv("path")

Getting output :
"Ramesh,Suresh,Ganesh" // Hence entire list into a single column in CSV

Expected output:
Ramesh, Suresh, Ganesh // each name into a single column in CSV

output should be in a row and each string should be in each column with comma separated.
If I try to change anything, it is saying CSV Data sources do not support array of string data type.
How to solve this?
Answer: If you are looking to convert your list of size n to a spark dataframe which holds n number of rows with only one column then the solution will look like below:
import sparkSession.sqlContext.implicits._

val listOfNames = List("Ramesh","Suresh","Ganesh")

val df = listOfNames.toDF("names")
df.show(false)

output:
+------+
|names |
+------+
|Ramesh|
|Suresh|
|Ganesh|
+------+

Comment: how to make row wise not column and each name should be in each column not Array[String]


PHP - obtaining sub-array in a single expression

Question: Is there a way to get, in a single expression, a sub-array from an array, giving specific keys from the original array?
By example:
$a = array('a' => 1, 'b' => 2, 'c' = 4, 'd' => 'clorch')
$b = doesthisfunctionexist($a, 'a', 'c')
//$b containing array('a' => 1, 'c' => 4)

I know I can code that function, but I'm asking if such a similar native function exists.
Comment: Do you mean `array_key_exists()`? For example: `true === array_key_exists('a', ['a' => 1]);`. It only works for one key at a time though. http://ie2.php.net/array_key_exists
Comment: array_key_exists is not what I expect. from the name one can infer the return value is boolean. from the doc one can confirm it. see what does $b contain in the third expression - that's what I'm looking for.
Answer: $a = array(
  "a" => 1,
  "b" => 2,
  "c" => 4,
  "d" => "clorch",
);
$b = array_intersect_key($a, array_flip(array('a', 'c')));

Comment: I was thinking about this alternative. Seems it's the only one I could figure using native functions (perhaps replacing array_flip with array_fill, but the idea was the same).
Answer: I am not aware of such a function but, you can do the following:
function array_pick($picks, $array)
    {
     $temp = array();
        foreach($array as $key => $value)
        {
            if(in_array($key, $picks))
            {
                $temp[$key] = $value;
            }
        }
     return $temp;
    }

try it like so:
 $a = array('a' => 1, 'b' => 2, 'c' =>4, 'd' => 'clorch');
    $b = array('b','c');
    $z = array_pick($b,$a);
    var_dump($z);

output:
array(2) {
  ["b"]=>
  int(2)
  ["c"]=>
  int(4)
}

Answer: $a = array('a' => 1, 'b' => 2, 'c' => 4, 'd' => 'clorch');
$b = array_intersect_key($a, array_flip(array('a', 'c')));


How To Create Two Column Page in HTML5 through Notepad++

Question: Trying to make a two column page so I can have two columns of information. I cannot get it to work though. I have a large table that takes up half the page and is pushed to the left, but I cannot get the other part to go on the right! It just goes underneath. Please if you know how tell me. I have to do this for a school project! Here is my code:

 .body {
 font-family: "Bookman Old Style";
 background:url('https://i.gifer.com/7sav.gif');
 color: white;
 }

 .table {
 background-color: #B6B6B6;
 font-size: 17px;
 border-color: white;
 }

 .header {
 }

 .rowone {
 float: left;
    width: 50%;
 }

 .rowtwo:after {
 content: "";
 display: table;
 clear: both;
 float: right;
 }
<!DOCTYPE html>

    <title>My Typical Day</title>

My Typical Day

By: Taylor Sloan

 Hour
    Class
 Teacher
 Image

 1
 Spanish 2.5
 Córdoba

 2
 Wood Technologies I
 Cortez

 3
 Honors Geometry
 Alexander

 4
 Honors Biology
 Martens

    5
 Honors English Language Arts
 McCrossen

 6
 Physical Education
 Lowe

 7
 Web Design
 Foster

My Top Three Favorite Books and Why

The Dragon Inside Series

Email Me!

Can anyone tell me what to do to fix it and attach a working version? I'm also doing this in Notepad++, not sure if that makes a difference.
Answer: You just need to make sure that your element tags are closed in the correct places, CENTER, DIV and TABLE tags all needed to be closed correctly.
Also, the CENTER tag is now deprecated and it is recommended that you use CSS to center your elements, like text-align: center

body {
  font-family: "Bookman Old Style";
  background: url('https://i.gifer.com/7sav.gif');
  color: white;
}

.table {
  background-color: #B6B6B6;
  font-size: 17px;
  border-color: white;
}

.header {}

.rowone {
  float: left;
  width: 50%;
}

.rowtwo:after {
  content: "";
  display: table;
  clear: both;
  float: right;
}

My Typical Day

By: Taylor Sloan

        Hour
        Class
        Teacher
        Image

        1
        Spanish 2.5
        Córdoba

        2
        Wood Technologies I
        Cortez

        3
        Honors Geometry
        Alexander

        4
        Honors Biology
        Martens

        5
        Honors English Language Arts
        McCrossen

        6
        Physical Education
        Lowe

        7
        Web Design
        Foster

My Top Three Favorite Books and Why

The Dragon Inside Series

Email Me!

Comment: You **really** should mention that `center` is obsolete and provide an alternative: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/center
Answer: Div elements will display as "block" elements by default, which only allows one per line. The next block level element will appear below it.
Add this CSS rule to .rowone and .rowtwo: display: inline; or display: inline-block;
Edit: MichaelvE's answer is correct. Floating block level divs will allow two blocks to appear on the same line, much like an inline element. I missed the open tags when skimming over the code.


Another Counterpoint Dissonance Handling Question... Species Counterpoint

Question: I am harmonizing a Mozart soprano melody with a musical friend.  Now, I could scour the internet for a week trying to figure this out, but I figured I would instead ask the music.stackexchange Gods first to greater effect.
I am having trouble wrapping my brain around counterpoint dissonance handling, specifically in the correct designation of "strong" and "weak" beats.

This is where I am so far with the harmonization.  In second species counterpoint, you have two half notes per measure, and the second half note can hold a dissonance.  Now, this piece is in 4/4, but if the chord changes are occurring twice per measure, beat 3 there could theoretically hold a dissonance?  Measure 2 changes chords twice like this.  (Note that there is no dissonance in this measure but I'm bringing it up to compare it with measure 4.)
In the 4th measure, you have chord changes that are occurring on the 3rd and 4th beat.  Please notice that I do indeed have a dissonance on beat 3 and this is where I'm lost...
Now, if this is 3rd species, where there are 4 beats in a measure, the 3rd beat is strong(ish) and not fitting for a dissonance.
So measure 4's dissonance on beat 3 is correct in 2nd species, but wrong in 3rd?
Can individual measures be treated as quadruple meter and some in duple depending on the chord changes?
Can someone provide me some insight?
Thanks!
EDIT:
Thanks to Heather S. and some reading I've been doing, I think I've come up with my own answer to this problem.
Now, what I didn't realize before and what I realize now is that there are two aspects to this whole "strong beat/weak beat" issue.
1. Strength/weakness as related to the meter of the piece/measure.
Ex: 4/4: First and 3rd beats are strong.  2/4: First beat is strong etc.
2. Strength/weakness as related to note(s) against a note in different ratios.
Ex: 2 notes against 1: first note is strong, 4 notes against 1: first and 3rd notes are strong etc.
This has helped me to understand the issue, because I wasn't able to separate the two aspects previously.
Now, I also believe I have the answer to best applying these ideas...
In Alfred Mann's intro in his translation of Fux's Gradus Ad Parnassum, he basically spells out one of the main goals of counterpoint: balance.
So, whatever you choose to do in terms of applying dissonance in meter and note-against-note situations, your main goal is creating balance in your music.
Thanks for all who helped.!
Edit for Michael:
Michael thank you again for your responses!
Please take this image for example:

I have altered some things in the first few measures to better help explain my point.
For starters, I know a first inversion tonic chord is poorly placed so early, but I only did it for the sake of allowing a passing 6/4 V chord.
Now, looking at the bass voice: if we pretend there is an invisible cantus firmus present in measure 2 as tonic note C, then we can see how a 2:1 dissonance on "beat 3" works - it is a dissonance that resolves in the same direction by step.  It also justifies common theory about proper placement of dissonant chords like the passing 6/4.  Notice I put beat 3 in quotes a moment ago: If this was duple meter, then this would be beat 2; I feel the chord change here makes this segment act like duple meter justifying 2nd species 2:1.
Now, applying this "invisible whole note cantus" over measures justifies what many theorists say about dissonant chords over the bass (ex: passing 6/4 on weak beat.)  The voices show respect the bass, and the bass shows respect to the the invisible cantus.
However, with that logic, we are already in some sort of contradiction here: Because beat 3's bass note places the melody in error with species 2 - a 4th above the bass that does not resolve by step.  It leaping down to the D correctly makes a proper leap to a consonance in regard to the prevailing chord, but, if looking at the bass voice, we see a dissonance being leapt away from.
Perhaps this is a better example:

Here the 4th above the bass never resolves down - it is instead the movement of the bass that provides the resolution - calling into question where/what the true cantus is.
It seems as though two schools of thought are meeting in this thread.
And...
Do you see how all of this is making my brain leak out my ears??  :)
Comment: What piece/movement is the Mozart melody from?
Comment: I honestly don't know, my friend forwarded it from a music workbook.
Answer: Species 2 counterpoint is 2:1. The note values will change, but the ratio is always 2:1. Two quarters to a half note, 2 eighth notes to a quarter note, two half notes to a whole note, etc.
What counts as a weak or strong beat (or portion of beat) depends on what note values you are using. If you are in a measure of 4/4 and one voice has half notes, the other voice will use quarter notes. The strong beats will then be beats 1 and 3, and the weak beats will be 2 and 4. In an eighth note to quarter note situation, the first half of the beat is strong, and the second half of the beat is weak. In two half notes to a whole note situation, the first half note is strong, the second half note is weak.
Species 2 counterpoint can use a mix of these note values within the same piece, but the idea is that one voices is moving at a proportion of two against the other voice's one. The upper voice might move faster in one place, but the lower voice might move faster in another place. The idea is to use the same principles of handling the dissonance in each setting.
Comment: Thank you heather. You have helped me arrive at what I feel is my answer. I actually added some text to my original question detailing the answer I've come up with. Again thank you for your time and detailed explanations.
Comment: Thank you for your thoughtful answer. I do understand what you're saying about the two-to-one ratio in second species. However, I'm still a bit lost. For example, how does species Counterpoint relate to chord changes? How do I know which species of CounterPoint to use at all in given situations? I know that Bach and Mozart study from fux gradus, but it's still difficult for me to get the whole picture at how species Counterpoint is used in composition.
Comment: Also, if I may, as you seem knowledgeable of this topic, can you reference also the above measures? Can Counterpoint be applied to this example?
Comment: @WilliamEgert, counterpoint is essentially about the independence of the voices and the thoughtful use of dissonance. Principles of counterpoint can *always* be used (and if writing something atonal, even a "negative" counterpoint can be used as if changing the rules of consonance and dissonance to their opposites, like a negative of a photograph.) A fully formed piece of music (as opposed to an exercise) will use a variety of counterpoint species, depending on what is going on in the music. Some measures/sections of measures will be 1:1, some 2:1, some 3:1 and so on.
Comment: Chords are often secondary thought when dealing with counterpoint. The consonances brought about by the various intervals used will form their own chords. If you are considering specific chords, that will limit the options of notes that can be used to find the appropriate intervals according to the species counterpoint you are using. Now, of course, rules are broken all the time. But the masters *know* when and why they break the "rules" and use dissonances or "improper" parallel movement judiciously for a specific sound or effect. I recommend looking at some two-part Bach minuets.
Comment: Thank you for your excellent and thoughtful responses.  I have one last question:  I had someone comment on a previous exercise I posted stating to the effect that I was "leaving the chord with non-chord tones on the strong part of the beat and returning to it on the weak part of the beat."  This brought on a great deal of confusion in me as to what the true weak parts of the beat even are.  For example, If my quarter note is split into smaller denominations, the true "weak" parts of the beat are different depending on which "species" I am applying to that situation?  I'm thinking 2:1 vs 4:1.
Comment: For example: a quarter note divided in 4 into 16th notes.  Sub-beat 3 of 4 here is strong in 3rd species but weak in 2nd.
Comment: @WilliamEgert, the differences in the relative strength or weakness of a part of a beat  (2:1 vs 4:1) are why there are differences in how dissonances can be handled in those different species.  At this point I am not sure how much I can help in this setting. Counterpoint is often studied with a teacher. I recommend that since you can go over specific details directly with someone.
Comment: @WilliamEgert It sound like Heather's post gave you the answer you were looking for. Please "accept" the answer (by clicking the check mark at the left) to make this clear. Also, the best way to say thanks for any helpful answer is to upvote that answer using the up arrow to the right of that post. (Note, this is also helpful to the site as a whole so that your question isn't periodically "bumped", because the system thinks you're still waiting for an answer.)
Answer: I think part of what Heather explained is you don't need to think about the meter, but instead the subdivisions of the two voices. In your example you are essentially dealing with 2:1 and 4:1 rhythms between the parts which are 2nd and 3rd species in Fux.
But there are two things I think you want to consider.
At m. 4, beat 3...

...you have a dissonant fourth above the bass. In terms of species beat 3 is 2:1 - 2nd species - and that first note of the two should be either a consonance or a ligature (a suspension.)
But the other thing I think you should consider is the problem of using a Mozart melody for species counterpoint exercises.
It may sound obvious, but species counterpoint is polyphonic whereas most Mozart's melodies (at least the one in the example) are homophonic. The treatment of dissonance is not exactly the same for both. On the whole I would say the homophonic style gets a lot of its sensibilities regarding dissonance handling from counterpoint, but adds a lot of things not found in species counterpoint.
I don't know the source of this melody. I tired to find it in the piano sonatas, but didn't find it there. The following is based on what I think the original is like.
The Mozart melody uses a short 2 bar phrase which is repeated then varied at the end...

...the varied end is in the green box.
If the original works like I suspect, the G5 of the varied ending (boxed in orange) is an appoggiatura above the F5 of the first iteration of the phrase. That means two things: in the homophonic style that G5 should be a non-chord tone to be heard as an appoggiatura, and the dissonance is unprepared.
I imagine the original is harmonized mm. 2-5 like | I viio6 | I6 | I IV6 | V6... |
It seems m.4, beat 3 shouldn't be a V chord, or else the G5 becomes a chord tone and won't sound like an appoggiatura.
I really hope my suspicion about the original is correct. I'm going out on a limb guessing what it actually is.
Back to the species counterpoint. We can no see two problems that come up using a homophonic melody like this for species counterpoint.

The melody repeats a phrase which is not ideal for a cantus firmus.
(If my suspicion about the original is correct) the appoggiatura is an unprepared dissonance which isn't supposed to happen in species counterpoint.

Of course you can do whatever you like with combining different styles. But if you want to work through traditional species counterpoint, I think you want to choose from existing cantus firmi. It will probably be easier to follow Fux's lessons when you work with the kind of material Fux had in mind.
Comment: Hi Michael!  Thank you for your response.  I'm still trying to figure out if there is any sense to be made out of all this or I am doing mental gymnastics trying to make it work.  The only cantus firmus that is really used in practice is the fugue, and typically the fugue subject is much more than whole notes or half notes.

In regard to m.4 beat 3 of the Mozart example.  You say this is 2:1.  This confuses me because....It could also be considered 4:1 because of the soprano's rhythm.  Also, what do you make of it when there are more voices involved in movement?
Comment: If you look at music theory sites and how they advise you on dissonant chords like the passing 6/4, they advise that you put them on a weak beat, which looks at the meter itself to determine the true "weak beat."  But as you, Heather S. and possibly Fux are saying is that you are only looking at the note against note relationships.  I can definitely dig it as there is much sense to be made in it, his goal was just keeping balance in the music, and balance and symmetry makes for good art!  (In my mind.)
Comment: Again pointing at measure 4, beat 3 in the Mozart example.  The soprano may be 2:1 against the quarter notes in that beat, but the bottom voices (bass and tenor) are 2:1 with the half note in the alto!  It all gets confusing really fast...
Comment: Is it that we are only look at the notes above the bass when making these determinations?  I suppose that would make things simpler....
Comment: Perhaps, and I know I'm making of ton of comments here, that you combine meter and note-against-note aspects when making determinations as to where dissonances should fit?
Comment: Or, looked at in yet another way, perhaps you can look at meter because you can pretend there is this invisible, whole note cantus firmus present in each measure.  In which case you really could use meter as a good determination of beat strength, as least as it relates to movement of the bass voice.
Comment: Michael please see your post I have added some text...
Comment: "Cantus firmus" is just a method, using an existing melody to build a composition. Bach's chorale preludes use chorale tunes as the cantus firmus. It isn't just about fugue. "passing 6/4 ...on the weak beat..." again that is _homophonic_ style. Incidentally, homophonic non-chord tones can be either accented or un-accented.  Anyway, just take the c.f. from Fux and other published species counterpoint books and gradually step through the lessons... then set it all aside and study the homophonic style of Mozart, Haydn, Handel, Bach, etc.
Comment: Thanks Michael, I am waiting on approval for some edits of your post where I've posted images.
Comment: You should put that edit in your question. Just put it under the original text.
Comment: Ok!  Hold up...I'll do that now.
Comment: Ok, all done, feel free to have a look.
Comment: @WilliamEgert, the old textbook author, Prout, came to mind last night. You might take a look at http://ks.imslp.net/files/imglnks/usimg/5/56/IMSLP504788-PMLP817980-Prout-additionalExercisesToCounterpoint.pdf one of his books that is almost entirely example cantus firmi for exercises. A companion to his book _Counterpoint_. You might like his approach as it combines species counterpoint with homophonic aspects like Roman numeral analysis.
Comment: https://imslp.org/wiki/Counterpoint_(Prout%2C_Ebenezer)
Comment: I just started reading Counterpoint: strict and free.  You're right, it is right up my alley as he is starting out by explaining the distinction between counterpoint and harmony.  Thanks for the recommendation!


problema com a data

Question: no meu aplicativo quando faço um pedido de venda, devesse informar a data do pedido e a data de emissão, a data do pedido eu pego automaticamente, já a data de emissão deve ser preenchida manualmente.
Depois dos inserts, eu exporto o banco do AVD e abro no SQLite experts e nenhuma data aprece, todas aparecem como "1899-12-30"

Codigos:
botao Insert do pedido:
Button confirma = (Button) findViewById(R.id.btnConfirmar);
    confirma.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            final BancoController crud = new BancoController(getBaseContext());

            EditText data = (EditText) findViewById(R.id.edtData);
            EditText emissao = (EditText) findViewById(R.id.edtEmissao);
            EditText obs = (EditText) findViewById(R.id.edtObs);

            String dataString = data.getText().toString();
            String emissaoString = emissao.getText().toString();
            String obsString = obs.getText().toString();
            String resultadoPe;
            String resultadoPp = null;

            Spinner spClientes = (Spinner) findViewById(R.id.spCliente);
            Spinner spCarteira = (Spinner) findViewById(R.id.spCarteira);
            Spinner spPagamentos = (Spinner) findViewById(R.id.spPagamento);

            SQLiteCursor dadosClientes = (SQLiteCursor) spClientes.getAdapter().getItem(
                    spClientes.getSelectedItemPosition());

            SQLiteCursor dadosCarteira = (SQLiteCursor) spCarteira.getAdapter().getItem(
                    spCarteira.getSelectedItemPosition());

            SQLiteCursor dadosPagamentos = (SQLiteCursor) spPagamentos.getAdapter().getItem(
                    spPagamentos.getSelectedItemPosition());

            String idCliente = String.valueOf(dadosClientes.getInt(0));
            String idCarteira = String.valueOf(dadosCarteira.getInt(0));
            String idPagamento = String.valueOf(dadosPagamentos.getInt(0));

            crud.op = 2;

            resultadoPe = crud.insereDados(null, null, null, null, null, null, null, null,
                    null, null, null, null, idCliente, idPagamento, idCarteira, dataString,
                    emissaoString, obsString, null, null, null, null, null);

            Toast.makeText(getApplication(), resultadoPe, Toast.LENGTH_LONG).show();

Inseredados do pedido:
public String insereDados
        (String nome, String apelido, String cpf, String rg, String endereco, String bairro,
         String municipio, String uf, String cep, String email, String fone, String cla,
         String par, String car, String cpag, String data, String emissao, String obs, String ped,
         String pro, String quantidade, String unitario, String item /**String lpPcodigo,
         String lpDescri, String lpQtd, String lpPreco*/){

    long resultadoC = -1;
    long resultadoPe = -1;
    long resultadoPr = -1;
    //long resultadoLp = -1;
    db = banco.getWritableDatabase();

    switch (op){
        case 1://Insere cliente:
            ContentValues cvc;
            cvc = new ContentValues();

            cvc.put(CriaBanco.getParNome(), nome);
            cvc.put(CriaBanco.getParApelido(), apelido);
            cvc.put(CriaBanco.getParCpf(), cpf);
            cvc.put(CriaBanco.getParRg(), rg);
            cvc.put(CriaBanco.getParEndereco(), endereco);
            cvc.put(CriaBanco.getParBairro(), bairro);
            cvc.put(CriaBanco.getParMunicipio(), municipio);
            cvc.put(CriaBanco.getParUf(), uf);
            cvc.put(CriaBanco.getParCep(), cep);
            cvc.put(CriaBanco.getParEmail(), email);
            cvc.put(CriaBanco.getParFone(), fone);

            resultadoC = db.insert(CriaBanco.getParTabela(), null, cvc);
            break;

        case 2://Insere Pedido
            ContentValues cvpe;
            cvpe = new ContentValues();

            cvpe.put(CriaBanco.getClaId(), cla);
            cvpe.put(CriaBanco.getPparId(), par);
            cvpe.put(CriaBanco.getCarId(), car);
            cvpe.put(CriaBanco.getCpagId(), cpag);
            cvpe.put(CriaBanco.getPedData(), data);
            cvpe.put(CriaBanco.getPedEmissao(), emissao);
            cvpe.put(CriaBanco.getPedObs(), obs);

            resultadoPe = db.insert(CriaBanco.getPedTabela(), null, cvpe);
            break;

        case 3: // Insere Pedido Produto

            ContentValues cvpr;
            cvpr = new ContentValues();

            cvpr.put(CriaBanco.getPppedId(), ped);
            cvpr.put(CriaBanco.getPpproId(), pro);
            cvpr.put(CriaBanco.getPproQnt(), quantidade);
            cvpr.put(CriaBanco.getPproUnit(), unitario);
            cvpr.put(CriaBanco.getPproItem(), item);

            resultadoPr = db.insert(CriaBanco.getPprodTabela(), null, cvpr);
            break;

    }
    db.close();

    if (resultadoC != -1){
        return "Cliente inserido com sucesso!";
    }else if(resultadoPe != -1 || resultadoPr != -1){
        return "Pedido realizado com sucesso!";
    }/**else if(resultadoLp != -1) {
        return "Produto adicionado a lista com sucesso!";
    }*/else{
        return "Erro ao inserir registro (cliente/pedido)!";
    }
}

uso Date edittext tanto na data do pedido quanto na data de emissão.
outra pergunta, tem como modificar formatação da data?
por exemplo, aparece assim automaticamente:

aparece 13 de maio de 2016, não tem como modificar e aparecer como 13/05/2016?
e tem como modificar com o codigo para na hora de inserir a data modifique as "/" por "-"?
obrigado desde ja
---EDIT---
como eu pego a data automaticamente:
final String currentDataTimeString = DateFormat.getDateInstance().format(new Date());

Answer: tente da seguinte maneira:
String str = new SimpleDateFormat("dd/"+"MM"+"/yyyy").format(new Date());

Comment: deu certo, mas ainda continua salvando errado a data no banco, eu acho que é por causa das barras...

problema com a data