text:
Q: Using Ansible, how can I install PythonBrew system-wide? I'm trying to create a playbook with Ansible (v 1.3.3) to install Pythonbrew system-wide on a Debian server following the instructions in the Pythonbrew readme file.
I am able to get Pythonbrew installed but I cannot install the specific version of Python that I want with it. I suspect the issue has to do with the shell environment Ansible is running under.
Here's my playbook script:
- name: Install and configure PythonBrew
  hosts: dev
  user: root
  vars_files:
    - vars.yml
  gather_facts: false

  tasks:
    - name: Install PythonBrew Debian packages
      apt: pkg=${item} state=installed update-cache=yes
      with_items: ${pythonbrew_packages}

    - name: Install PythonBrew system-wide
      shell: curl -kL http://xrl.us/pythonbrewinstall | bash creates=/usr/local/pythonbrew executable=/bin/bash

    - name: Update bashrc for PythonBrew
      lineinfile:
        dest=~/.bashrc
        regexp='^'
        line='[[ -s $HOME/.pythonbrew/etc/bashrc ]] && source $HOME/.pythonbrew/etc/bashrc'
        state=present
        create=True

    - name: Install python binary
      shell: pythonbrew install -v ${python_version} executable=/bin/bash

When I run this playbook, it fails with the following output

failed: [devserver] => {"changed": true, "cmd": "pythonbrew
  install -v 2.7.3 ", "delta": "0:00:00.016639", "end": "2013-10-11
  15:21:40.989677", "rc": 127, "start": "2013-10-11 15:21:40.973038"}
  stderr: /bin/bash: pythonbrew: command not found

I've been tweaking things for the last hour or so to no avail. Does anybody have any suggestions for fixing this?

A: By peeking at the PythonBrew install script, I was able to figure this out. (And just in time for the deprecation of PythonBrew!)
Here's the playbook that installs PythonBrew without manual intervention. This may be of interest to anyone trying to script PythonBrew to install automatically.
vars.yml
#
# Python/PythonBrew Settings
# TODO: replace old-style Ansible ${vars} with jinja-style {{ vars }}
#
project_name: MY_PROJECT

python:
  version: 2.7.3

pythonbrew:
  root: /usr/local/pythonbrew
  bashrc_path: $HOME/.pythonbrew/etc/bashrc

  packages:
    - curl
    - zlib1g-dev
    - libsqlite3-dev
    - libssl-dev
    - libxml2
    - libxml2-dev
    - libxslt1-dev
    - libmysqlclient-dev
    - libbz2-dev

pythonbrew.yml
---

#
# Install and Configure PythonBrew
#
- name: Install and configure PythonBrew
  hosts: MY_HOST
  user: root
  vars_files:
    - vars.yml
  gather_facts: false

  tasks:
    - name: Install PythonBrew Debian packages
      apt: pkg=${item} state=installed update-cache=yes
      with_items: ${pythonbrew.packages}

    - name: Install PythonBrew system-wide
      shell: curl -kL http://xrl.us/pythonbrewinstall | bash
        executable=/bin/bash
        creates=${pythonbrew.root}

    - name: Update bashrc for PythonBrew
      lineinfile:
        dest=/root/.bashrc
        regexp='^'
        line='[[ -s ${pythonbrew.bashrc_path} ]] && source ${pythonbrew.bashrc_path}'
        state=present
        create=True

    # This step allows install to continue without new shell. Pulled from:
    # https://github.com/utahta/pythonbrew/blob/master/pythonbrew/installer/pythonbrewinstaller.py#L91
    - name: Install python binary
      shell: export PYTHONBREW_ROOT=${pythonbrew.root}; source ${pythonbrew.root}/etc/bashrc; pythonbrew install ${python.version}
        executable=/bin/bash

    - name: Switch to python version
      shell: export PYTHONBREW_ROOT=${pythonbrew.root}; source ${pythonbrew.root}/etc/bashrc; pythonbrew switch ${python.version}
        executable=/bin/bash


text:
Q: How to setup HAProxy to drop connection on matching query string key value? I have installed HAProxy 1.5.18 on a Centos 7.
In the /etc/haproxy/haproxy.cfg I have following line:
frontend free_api
        bind *:80
        stats uri /haproxy?stats
        mode http
        option forwardfor
        acl key1 urlp(key) 12345
        acl key2 urlp(key) 6789

        http-request deny if key1
        http-request deny if key2

       # use_backend api if api
 default_backend api

Right now the URL access gets denied for query string key with a matching value of 12345 or 6789. HAProxy returns a 403 Forbidden status code back.
What I am looking is to simply drop the connection so nothing is returned back to user? How to do that in HAProxy?
Thanks.

A: use haproxy v1.6 and higher, and directive silent-drop
http-request silent-drop if key1

"silent-drop" : this stops the evaluation of the rules and makes the
      client-facing connection suddenly disappear using a system-dependent way
      that tries to prevent the client from being notified. The effect it then
      that the client still sees an established connection while there's none
      on HAProxy. The purpose is to achieve a comparable effect to "tarpit"
      except that it doesn't use any local resource at all on the machine
      running HAProxy. It can resist much higher loads than "tarpit", and slow
      down stronger attackers. It is important to understand the impact of using
      this mechanism. All stateful equipment placed between the client and
      HAProxy (firewalls, proxies, load balancers) will also keep the
      established connection for a long time and may suffer from this action.
      On modern Linux systems running with enough privileges, the TCP_REPAIR
      socket option is used to block the emission of a TCP reset. On other
      systems, the socket's TTL is reduced to 1 so that the TCP reset doesn't
      pass the first router, though it's still delivered to local networks. Do
      not use it unless you fully understand how it works.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Aspell dictionaries missing when installed into nix-shell When I install the Aspell package with the Aspell dictionary for English into my global env using Nix on Mac OSX:
$ nix-env -iA nixpkgs.aspell nixpkgs.aspellDicts.en

Then Aspell behaves as I would expect:
$ aspell dump dicts

en
en-variant_0
...

However if I install the packages into a nix-shell then the Dictionary does not appear to be correctly installed:
$ nix-shell -p aspell aspellDicts.en --pure

$ aspell dump dicts
# nothing printed

$ echo 'word lister to check' | aspell --list
Error: No word lists can be found for the language "en_US".

Each of the following variations produce the same problem behaviour:

*

*Installing into a nix-shell that is not pure,

*Putting the nix expression into a default.nix file and just running nix-shell.

*Installing other Aspell dictionaries

Can anyone advise how to get this working?

A: The aspell binary is wrapped by NixPkgs, to provide the installation paths through ASPELL_CONF environment variable, if not already specified. (For details, cat -v result/bin/aspell)
You can either specify ASPELL_CONF manually, or use the NIX_PROFILES environment variable. For example:
$ nix-build -E 'with import <nixpkgs> {};
     buildEnv { name = "aspell-env"; paths = [aspell aspellDicts.en]; }'

$ NIX_PROFILES=./result ./result/bin/aspell dump dicts
en
en-variant_0
[...]
en_US-wo_accents

However, if you want to build a self-contained aspell install with dictionaries, you can use aspellWithDicts:
nix-build -E 'with import <nixpkgs> {}; aspellWithDicts (d: [d.en])'

This will hardcode the ASPELL_CONF, so you don't need to think of those environment variables again.


text:
Q: Are there rules or trends for -ty vs -ness in general? Could "thoroughty" have been a word if thoroughness hadn't been there? In a recent SE answer I've written:

I think that other answerers can address this with more historical thoroughty than I, so I'll defer to their expertise, but it sounds like the LRO frozen orbit is likely the best representative example of what's been achieved to date.

I'd hoped that it would turn out to be a word, and it's possible that others have in the past as well
Google Ngram viewer shows usage of the word surfacing around the beginning of the nineteenth century and reaching a minuscule crescendo around the beginning of the twentieth century before dropping into the noise soon after.
though comments suggest this represents the rate of typographical errors.
To me it seems that while thoroughty had the chance to exist in the English language, somehow thoroughness always had the upper hand and finally won.
Question: Are there any grammatical or historical reasons why thoroughty could not have functioned just as well as thoroughness? Is there a general trend or rule when -ty and -ness are both possible, or has it been essentially random? Are there any cases where they coexist?
The English Lessons Brighton article How to use suffixes to create nouns from adjectives and verbs lists -ness and -ity but not -ty (except in comments) but I don't see any discussion as to how these selections arose.
I'm thinking of uses such as

*

*proceed with all due thoroughty/thoroughness

*they demonstrated exemplary thoroughty/thoroughness

A:
Are there any grammatical or historical reasons why thoroughty could not have functioned just as well as thoroughness?

There is no reason that I know of that makes it so that -ty necessarily could not have functioned to form a noun thoroughty with the same meaning as the actually existing existing thoroughness. I only mean this in the very weak sense that there is no reason any word, like "thorough" itself, necessarily has the form that it does. Large portions of languages are arbitrary, and could function just as well if they were different from how they actually are.

Is there a general trend or rule when -ty and -ness are both possible, or has it been essentially random?

It is not random: the distribution shows the effects of their historical origins. The ending -ness, a native English suffix, is found attached to a wide range of adjectives, and can easily be attached to create new nouns. The ending -ty, a borrowed element, was often already attached to words at the time they entered English.
Some -ty nouns are built on stems that don't even exist as bare adjectives in English, as with beauty, celerity, integrity.
New -ty nouns mostly tend to be formed on adjectives that have a Latinate ending such as -able, -al, -ous, -ose, -ic, -ive.

Are there any cases where they coexist?

Yes. However, many -ness words have only minor usage compared to their synonymous -ty counterparts. For example, stableness and realness both exist, but are much less common than stability and reality. Some pairs of -ty and -ness nouns have distinct meanings for certain specific senses.


text:
Q: Find the potential of a conservative force/ Line integrals $$ \vec{F} = -k(x-y)^2\hat{x} + k(x-y)^2\hat{y} + Kz\hat{z}$$

*

*Find the potential of $\vec{F}$.

*A particle moves in straight lines from $(0,0,0)$ to$(D,D,0)$ then to $(D,D,D)$. Calculate the work done by $\vec{F}$ using the line integral.

In order to find the potential energy I used the method outlined in this video, Vector Field Potential, however that method is for Vector Fields and I need to find the potential energy of a conservative force. It appears to only be the difference of a minus sign after you have calcualted the entire thing, is that correct?
I am completely unsure of the line integral in this case, and could use a general background of 3D line integrals.


text:
Q: hough transform in a limited frame height of a video This is my code:
int main() {
    VideoCapture cap;
    cap.open("D:/01.avi");
    if (!cap.isOpened()) {
        cout << "Video cannot be opened" << endl;
        system("pause");
        return -1;
    }
    VideoWriter cap_output("D:/01_ouput.avi",
        cap.get(CV_CAP_PROP_FOURCC),
        cap.get(CV_CAP_PROP_FPS),
        Size(cap.get(CV_CAP_PROP_FRAME_WIDTH),
            cap.get(CV_CAP_PROP_FRAME_HEIGHT)));
    if (!cap_output.isOpened()) {
        cout << "Output video cannot be opened" << endl;
        return -1;
    }
    Mat frame, canny_frame, frame_ouput;
    while (true) {
        if (!cap.read(frame))
            break;

        Canny(frame, canny_frame, 50, 200, 3);
        cvtColor(canny_frame, frame_ouput, CV_GRAY2BGR);
        vector<Vec4i> lines;
        HoughLinesP(canny_frame, lines, 1, CV_PI / 180, 100, 100, 10);
        for (size_t i = 0; i < lines.size(); i++) {
            Vec4i l = lines[i];
            line(frame, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 3, 8);
        }
        imshow("ahoho", frame);
        //cap_output.write(frame_ouput);
        if (waitKey(30) >= 0) {
            break;
        }
    }

    cap.release();
    cap_output.release();

    return 0;
}

I want to detect the lines in only 1/2 height of the frame of the video (to avoid different objects). How can I do it?


text:
Q: Firebase app Background or killed notfication I'm programming a Firebase app for sending a notification when my app has a values(number)in red. I tried to send a message when the app is running in the background or is killed, but my program doesn't work and I don't know how to call the onMessageReceived() method.
Station1.java
public class Station1 extends AppCompatActivity implements getData.ReturnValue {

private MyFirebaseMessagingService FBMessagingService = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
      //widget id
  }

        if (mpxInt < mpxIntMin || mpxInt > mpxIntMax) {
            Mpx.setText(valeurs.getMpx());//affiche la valeur mpx dans le textView
            Mpx.setTextColor(Color.parseColor("#DF0101"));//red
            FBMessagingService.onMessageReceived(RemoteMessage);//?
        } else {
            Mpx.setText(valeurs.getMpx());
        }

}

MyFirebaseMessagingService.java
 public class MyFirebaseMessagingService extends FirebaseMessagingService {

    public void onMessageReceived(RemoteMessage remoteMessage) {
    Map<String, String> data = remoteMessage.getData();

    //you can get your text message here.
    String text= data.get("text");

    Intent i =new Intent(this,Station1.class);
    i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    PendingIntent pendingIntent = PendingIntent.getActivity(this,0,i,PendingIntent.FLAG_ONE_SHOT);

    NotificationCompat.Builder notificationBuilder=new
    NotificationCompat.Builder(this);
    notificationBuilder.setContentTitle("FCM NOTIFICATION");
    notificationBuilder.setContentText(remoteMessage.getNotification().getBody());

    notificationBuilder.setAutoCancel(true);
    notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
    notificationBuilder.setContentIntent(pendingIntent);
    NotificationManager notidicationManager= (NotificationManager)

    getSystemService(Context.NOTIFICATION_SERVICE);
    notidicationManager.notify(0,notificationBuilder.build());

    }
}


text:
Q: CRM Application for Ubuntu I am looking for CRM application to manage an IT workshop running Ubuntu. I have a medium size workshop and I am looking for a CRM application I can use to manage jobs, appointments and track work being done by my staff. Does anyone know of an application that will do this?

A: Try sugar crm it is open source and has a free community edition:
http://www.sugarcrm.com/crm/download

A: Check out http://dolibarr.com Hope it helps
Online Demo https://www.dolibarr.org/onlinedemo.php
Github https://github.com/Dolibarr/dolibarr
About
Dolibarr ERP CRM is a modern software package to manage your company or foundation activity (contacts, suppliers, invoices, orders, stocks, agenda, accounting, ...).It's opensource software (wrote with PHP language) designed for small and medium companies, foundation and freelances. You can freely install, use and distribute it as a standalone a…


text:
Q: Оператор as в C# Объясните пожалуйста оператор as в c#. Учил C++ и с него перешёл на C# для изучения Unity. Насколько я понимаю, то оператор as можно понимать как явное приведение типов.

A: Оператор as возвращает значение типа второго операнда, если преобразование типов возможно, или null, если невозможно. Этим он отличается от каста (MyClass)obj, который выбрасывает исключение, когда преобразование типов невозможно.

A: Например,
var m = someObj as MyClass;

Идентично:
MyClass m;
try
{
    m = (MyClass)someObj;
}
catch (InvalidCastException ex)
{
    m = null;
}

или же:
MyClass m;
if(someObj is MyClass)
{
    m = (MyClass)someObj;
}
else
{
    m = null;
}

Возможно, есть какие-то внутренние различия реализации, и, скорее всего, она ближе ко второму варианту, но суть думаю можно понять.


text:
Q: Is there a loadash function to compare two arrays and return true only if all values from arr2 is present in arr1? I have to compare two arrays and return true if only the array 1 contains all values of array 2. What is the suitable loadash function for this?
let arr1 = [1, 2, 3, 4]
let arr2 = [1, 2]
let arr3 = [1, 5]

comparing arr1 with arr2 should return true
comparing arr1 with arr3 should return false

A: Just for completeness, you could take a Set and compare with Set#has.

let arr1 = [1, 2, 3, 4],
    arr2 = [1, 2],
    arr3 = [1, 5],
    base = new Set(arr1);

console.log(arr2.every(Set.prototype.has, base));
console.log(arr3.every(Set.prototype.has, base));

A: You can just use every:

let arr1 = [1, 2, 3, 4];
let arr2 = [1, 2];
let arr3 = [1, 5];

const allElements = (a1, a2) => a2.every(e => a1.includes(e));
console.log(allElements(arr1, arr2));
console.log(allElements(arr1, arr3));

A: There is no need for loadash here just use native JavaScript Array#every method with Array#includes method

function compareArray(arr1, arr2) {
  return arr2.every(v => arr1.includes(v))
}

let arr1 = [1, 2, 3, 4]
let arr2 = [1, 2]
let arr3 = [1, 5]

console.log(compareArray(arr1, arr2))
console.log(compareArray(arr1, arr3))

A: let arr1 = [1, 2, 3, 4]
let arr2 = [1, 2]

for(let x of arr2) {
    _.includes(arr1, x) || true;
}

A: You can use _.difference

let arr1 = [1, 2, 3, 4]
let arr2 = [1, 2]
let arr3 = [1, 5]

console.log(_.difference(arr2,arr1).length === 0)
console.log(_.difference(arr3,arr1).length === 0)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

A: You can use _.difference in such way:
let arr1 = [1, 2, 3, 4]
let arr2 = [1, 2]

const b = _.difference(arr2, arr1).length === 0


text:
Q: Tray icon simply not showing in java I've been trying all day to get my tray icon added, but it doesnt work. I have the icon file stored within the netbeans src/myproject/
I have tried a gazillion different paths, even direct ones to my files, but none seem to work. I'm pretty sure something in my code doesnt work, I simply can't see it.
public void createSystemTrayIcon() {

if (SystemTray.isSupported()) {
    SystemTray tray = SystemTray.getSystemTray();
    Image img = Toolkit.getDefaultToolkit().getImage("smallicon.ico");

    PopupMenu popup = new PopupMenu();

    final MenuItem menuExit = new MenuItem("Quit");

    MouseListener mouseListener =
        new MouseListener() {
        public void mouseClicked(MouseEvent e) {
            show();
        }

        public void mouseEntered(MouseEvent e) {
        }

        public void mouseExited(MouseEvent e) {
        }

        public void mousePressed(MouseEvent e) {
        }

        public void mouseReleased(MouseEvent e) {
        }
    };

    ActionListener exitListener =
        new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Runtime r = Runtime.getRuntime();
            System.out.println("Exiting...");
            r.exit(0);
        }
    };

    menuExit.addActionListener(exitListener);
    popup.add(menuExit);

    final TrayIcon trayIcon = new TrayIcon(img, "ESOLeaderboards", popup);

    ActionListener actionListener =
        new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                trayIcon.displayMessage("ESOLeaderboards ","version: EU 1.0",
                        TrayIcon.MessageType.INFO);
        }
    };

    trayIcon.setImageAutoSize(true);
    trayIcon.addActionListener(actionListener);
    trayIcon.addMouseListener(mouseListener);

    try {
        tray.add(trayIcon);
    } catch (AWTException e) {
        System.err.println("TrayIcon could not be added.");
    }

} else {
    //  System Tray is not supported
}

}

A: Toolkit.getDefaultToolkit().getImage("smallicon.ico"); supports only JPG, PNG and GIF images.
It doesn't support ico images. Use another image.

A: In windows 10, I've been able to view a 16 pixels PNG in the tray this way:
final URL resource = getClass().getResource("icon16.png");
final TrayIcon trayIcon = new TrayIcon(Toolkit.getDefaultToolkit().getImage(resource), "Application v0.1 tooltip");

It's "expected" that other OSes would down-scale a big icon, but I haven't tested it.

A: The standard method of embedding images (and any other non-class resources) is to just put them in a package in the project, e.g. if you project is using com.myproject.myapp, then create a package (just a folder, really) images (under myapp) and put you image files there.
Access to those images (resources) is gained by using the ClassLoader methods getResource(name) and/or getResourceAsStream(name). For simplicity to get the right ClassLoader instance many prefer to also create a class (e.g. "Images") in that same package and define static constants there to access the resources by name (as simple as Images.CONSTANT_NAME). Project structure may look like this:
com.myproject.myapp
    images
        Images.class
        MyImage1.png

In the images class, constants can be defined either for the resource handle or the resources themselves:
public final static URL MY_IMAGE_1 = Images.class.getResource("MyImage1.png");

(The URL could then be passed to Toolkit). If an eager load of everything is desired/feasible the loaded images themselves:
public final static Image MY_IMAGE_1 = loadImage("MyImage1.png");

private static Image loadImage(String name) {
    URL url = Images.class.getClassLoader().getResource(name);
    Image img = Toolkit.getDefaultToolkit().getImage(url);
    // possible hack to force pre-loading of (toolkit) image in next line
    // new ImageIcon(img);
    return img;
}

Obviously I omitted all error handling from the examples, loading methods should include detailed error handling and reporting (logging/System.out and/or throwing appropiate exceptions) when something goes wrong.
These approaches will work in IDE as well as after creating a jar file for the program.


text:
Q: How to use JButton in JTable? I've been trying to put a clickable button in a JTable, and I'm not doing great.
Im using the ButtonColumn class to do so, but the actions are ignored - the buttons are showing but nothing is happening on click.
/**
 *  The ButtonColumn class provides a renderer and an editor that looks like a
 *  JButton. The renderer and editor will then be used for a specified column
 *  in the table. The TableModel will contain the String to be displayed on
 *  the button.
 *
 *  The button can be invoked by a mouse click or by pressing the space bar
 *  when the cell has focus. Optionally a mnemonic can be set to invoke the
 *  button. When the button is invoked the provided Action is invoked. The
 *  source of the Action will be the table. The action command will contain
 *  the model row number of the button that was clicked.
 *
 */
public class ButtonColumn extends AbstractCellEditor
    implements TableCellRenderer, TableCellEditor, ActionListener, MouseListener{
    /**
     *
     */
    private static final long serialVersionUID = -6737467999355167233L;
    private JTable table;
    private Action action;
    private int mnemonic;
    private Border originalBorder;
    private Border focusBorder;

    private JButton renderButton;
    private JButton editButton;
    private Object editorValue;
    private boolean isButtonColumnEditor;

    /**
     *  Create the ButtonColumn to be used as a renderer and editor. The
     *  renderer and editor will automatically be installed on the TableColumn
     *  of the specified column.
     *
     *  @param table the table containing the button renderer/editor
     *  @param action the Action to be invoked when the button is invoked
     *  @param column the column to which the button renderer/editor is added
     */
    public ButtonColumn(JTable table, Action action, int column)
    {
        this.table = table;
        this.action = action;

        renderButton = new JButton();
        editButton = new JButton();
        editButton.setFocusPainted( false );
        editButton.addActionListener( this );
        originalBorder = editButton.getBorder();
        setFocusBorder( new LineBorder(Color.BLUE) );

        TableColumnModel columnModel = table.getColumnModel();
        columnModel.getColumn(column).setCellRenderer( this );
        columnModel.getColumn(column).setCellEditor( this );
        table.addMouseListener( this );
    }

    /**
     *  Get foreground color of the button when the cell has focus
     *
     *  @return the foreground color
     */
    public Border getFocusBorder()
    {
        return focusBorder;
    }

    /**
     *  The foreground color of the button when the cell has focus
     *
     *  @param focusBorder the foreground color
     */
    public void setFocusBorder(Border focusBorder)
    {
        this.focusBorder = focusBorder;
        editButton.setBorder( focusBorder );
    }

    public int getMnemonic()
    {
        return mnemonic;
    }

    /**
     *  The mnemonic to activate the button when the cell has focus
     *
     *  @param mnemonic the mnemonic
     */
    public void setMnemonic(int mnemonic)
    {
        this.mnemonic = mnemonic;
        renderButton.setMnemonic(mnemonic);
        editButton.setMnemonic(mnemonic);
    }

    @Override
    public Component getTableCellEditorComponent(
        JTable table, Object value, boolean isSelected, int row, int column)
    {
        if (value == null)
        {
            editButton.setText( "" );
            editButton.setIcon( null );
        }
        else if (value instanceof Icon)
        {
            editButton.setText( "" );
            editButton.setIcon( (Icon)value );
        }
        else
        {
            editButton.setText( value.toString() );
            editButton.setIcon( null );
        }

        this.editorValue = value;
        return editButton;
    }

    @Override
    public Object getCellEditorValue()
    {
        return editorValue;
    }

//
//  Implement TableCellRenderer interface
//
    @Override
    public Component getTableCellRendererComponent(
        JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
    {
        if (isSelected)
        {
            renderButton.setForeground(table.getSelectionForeground());
            renderButton.setBackground(table.getSelectionBackground());
        }
        else
        {
            renderButton.setForeground(table.getForeground());
            renderButton.setBackground(UIManager.getColor("Button.background"));
        }

        if (hasFocus)
        {
            renderButton.setBorder( focusBorder );
        }
        else
        {
            renderButton.setBorder( originalBorder );
        }

//          renderButton.setText( (value == null) ? "" : value.toString() );
            if (value == null)
            {
                renderButton.setText( "" );
                renderButton.setIcon( null );
            }
            else if (value instanceof Icon)
            {
                renderButton.setText( "" );
                renderButton.setIcon( (Icon)value );
            }
            else
            {
                renderButton.setText( value.toString() );
                renderButton.setIcon( null );
            }

            return renderButton;
        }

    //
    //  Implement ActionListener interface
    //
        /*
         *  The button has been pressed. Stop editing and invoke the custom Action
         */
        @Override
        public void actionPerformed(ActionEvent e)
        {
            int row = table.convertRowIndexToModel( table.getEditingRow() );
            fireEditingStopped();

            //  Invoke the Action

            ActionEvent event = new ActionEvent(
                table,
                ActionEvent.ACTION_PERFORMED,
                "" + row);
            action.actionPerformed(event);
        }

    //
    //  Implement MouseListener interface
    //
        /*
         *  When the mouse is pressed the editor is invoked. If you then then drag
         *  the mouse to another cell before releasing it, the editor is still
         *  active. Make sure editing is stopped when the mouse is released.
         */
        @Override
        public void mousePressed(MouseEvent e)
        {
            if (table.isEditing()
            &&  table.getCellEditor() == this)
                isButtonColumnEditor = true;
        }

        @Override
        public void mouseReleased(MouseEvent e)
        {
            if (isButtonColumnEditor
            &&  table.isEditing())
                table.getCellEditor().stopCellEditing();

            isButtonColumnEditor = false;
        }

        @Override
        public void mouseClicked(MouseEvent e) {}
        @Override
        public void mouseEntered(MouseEvent e) {}
        @Override
        public void mouseExited(MouseEvent e) {}
    }

My code of actually doing so:
ButtonColumn deleteColumn = new ButtonColumn(eventTable, new AbstractAction(){
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("It works!!!!");
        }
 }, 3);

That never seems to be printed. I could really use some help. Thanks in advance!
EDIT: I've also tried this code and it also doesn't seem to work.
eventTable.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                JTable target = (JTable)e.getSource();
                int row = target.getSelectedRow();
                int column = target.getSelectedColumn();
                System.out.println("Event table was clicked in row "+row+", column "+column);
            }
        });

A: Have a look at TableCellRenderer explained.
And the interface TableCellRenderer.

A: My guess is that the column is not editable which means the editor is never invoked so the Action is never invoked.
If this doesn't help then post a proper SSCCE demonstrating the problem.


text:
Q: angularjs, how to bind data after redirection to another page? I am calling my controller function from page1, as well as redirecting to page2 with ng-click method. The code is getting executed and data. Here is my method in controller class.
<a href="FlightSearch/Search/SearchResult" class="btn_search" ng-click="SearchFlight()">SEARCH </a>

    $scope.SearchFlight = function () {
    var AirAvailabilityRQ =
    {
        OriginLocation: $scope.DepartureCity.LocationCode,
        DestinationLocation: $scope.DestinationCity.LocationCode,
        DepartureDateTime: $scope.travel_date,
        ConversationId: "",
        MessageId: "",
        AirLineCode: [],
        PreferencesCabin: "E",
        MaxStopsQuantity: "0",
        IsIgnoreCodeShareFlight: true,
        Token: "",
        TenantId: "",
        Type: ""
    };

    SearchResultService.getSearchresult(AirAvailabilityRQ, function (response) {
        console.log(response);
        angular.forEach(response, function (value, key) {
            if (value.JourneyType == "Forward") {
                $scope.ForwardFlightList = value.AirFlightDetails;
            }
            else {
                $scope.ReturnFlightList = value.AirFlightDetails;
            }
        });
    })
}

the code for service:
searchResult.factory("SearchResultService", function ($http) {
return {
    getSearchresult: function (data,callback) {
        return $http.post("/FlightSearch/Search/BeginSearch",data).success(callback);
    }
}
});

My method hits the MVC controller thru SearchResultService. I am getting data in .CS code, but I am not getting data in my angularJS controller althouth data is returned. When I use  console.log(response), I get nothing. Not even null, in browser console.
When the same page (page2) is executed on standalone basis, I can get data in angularJS the function, and I am able to bind it to the page.
So what is the mistake?


text:
Q: ModuleNotFoundError: No module named 'numpy.testing.decorators' I really need some help, as I have gone through all the posts and nothing has worked. I get this error when importing gensim and not numpy (numpy is before and works fine). All I want to do is import gensim and numpy to then run my analysis.
Here is the full error message:
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-2-3f0b98039a34> in <module>()
      1 # pip install --user numpy==1.16.4
      2
----> 3 import gensim
      4 #import numpy
      5

~/.local/lib64/python3.6/site-packages/gensim/__init__.py in <module>()
      9 import logging
     10
---> 11 from gensim import parsing, corpora, matutils, interfaces, models, similarities, utils  # noqa:F401
     12
     13

~/.local/lib64/python3.6/site-packages/gensim/corpora/__init__.py in <module>()
      4
      5 # bring corpus classes directly into package namespace, to save some typing
----> 6 from .indexedcorpus import IndexedCorpus  # noqa:F401 must appear before the other classes
      7
      8 from .mmcorpus import MmCorpus  # noqa:F401

~/.local/lib64/python3.6/site-packages/gensim/corpora/indexedcorpus.py in <module>()
     12 import numpy
     13
---> 14 from gensim import interfaces, utils
     15
     16 logger = logging.getLogger(__name__)

~/.local/lib64/python3.6/site-packages/gensim/interfaces.py in <module>()
     17 import logging
     18
---> 19 from gensim import utils, matutils
     20
     21

~/.local/lib64/python3.6/site-packages/gensim/matutils.py in <module>()
     17 import numpy as np
     18 import scipy.sparse
---> 19 from scipy.stats import entropy
     20 import scipy.linalg
     21 from scipy.linalg.lapack import get_lapack_funcs

/cluster/apps/python/3.6.4_cpu/lib64/python3.6/site-packages/scipy/stats/__init__.py in <module>()
    343 from .stats import *
    344 from .distributions import *
--> 345 from .morestats import *
    346 from ._binned_statistic import *
    347 from .kde import gaussian_kde

/cluster/apps/python/3.6.4_cpu/lib64/python3.6/site-packages/scipy/stats/morestats.py in <module>()
     10                    sqrt, ceil, floor, array, compress,
     11                    pi, exp, ravel, count_nonzero, sin, cos, arctan2, hypot)
---> 12 from numpy.testing.decorators import setastest
     13
     14 from scipy._lib.six import string_types

ModuleNotFoundError: No module named 'numpy.testing.decorators'

What I have tried:
I have tried using the latest version of numpy, and also forcing it to the version 1.16.4 "pip install --user numpy==1.16.4". I have also tried uninstalling and reinstalling both gensim and numpy, but its not working. I am using Python 3.6 and on a cluster. I don't really understand why numpy has no problem being imported, but that this is a problem of gensim.
Can anyone kindly help me out with this?
Thanks a lot!
Best,
Sandra


text:
Q: Knex Raw Select Postgresql with variable Can I use a variable in a knex query? And what is wrong with db.raw(select usr_vote.vote where usr_vote.user.id = ${loggedInUserId})? Everything else works fine.
In the db.raw that is nowt working, I'm trying to use a variable (loggedInUserId) to get the logged-in users' vote history for the Question (they can upvote / downvote so the value is either -1 or 1 or null). Thanks in advance for any help!
There are 4 tables that look like:
askify_users

*

*id

*user_name

askify_questions

*

*id

*title

*body

*tags

*date_created

*user_id (FK references askify_users.id)

askify_answers

*

*id

*answer

*question_id (FK references askify_question.id)

*user_id (FK references askify_users.id)

askify_question_votes

*

*List item

*question_id (FK references askify_questions.id)

*user_id (FK references askify_users.id)

*vote (-1 or 1)

*PRIMARY KEY (question_id, user_id)

getAllQuestions(db, loggedInUserId) {
    return db
      .from('askify_questions AS q')
      .select(
        'q.id AS question_id',
        'q.title AS question_title',
        'q.body AS question_body',
        'q.date_created AS date_created',
        'q.tags',
        db.raw(
          `count(DISTINCT ans) AS number_of_answers`
        ),
        db.raw(
          `SUM(DISTINCT usr_vote.vote) AS sum_of_votes`
        ),
        db.raw(
          `select usr_vote.vote where usr_vote.user_id = ${loggedInUserId}`
        ),
        db.raw(
          `json_strip_nulls(
            json_build_object(
              'user_id', usr.id,
              'user_name', usr.user_name,
              'full_name', usr.full_name,
              'date_created', usr.date_created
            )
          ) AS "user"`
        )
      )
      .leftJoin(
        'askify_answers AS ans',
        'q.id',
        'ans.question_id'
      )
      .leftJoin(
        'askify_users AS usr',
        'q.user_id',
        'usr.id'
      )
      .leftJoin(
        'askify_question_vote AS usr_vote',
        'q.id',
        'usr_vote.question_id'
      )
      .groupBy('q.id', 'usr.id')
  },

The query should look as follows. Everything except for 'user_vote_history' is working.

  serializeQuestion(question) {
    const { user } = question
    return {
      id: question.question_id,
      question_title: xss(question.question_title),
      question_body: xss(question.question_body),
      date_created: new Date(question.date_created),
      number_of_answers: Number(question.number_of_answers) || 0,
      user_vote_history: question.user_vote_history,
      sum_of_votes: Number(question.sum_of_votes),
      tags: xss(question.tags),
      user: {
        user_id: user.user_id,
        user_name: user.user_name,
        full_name: user.full_name,
        user_vote: user.user_vote,
        date_created: new Date(user.date_created)
      },
    }
  },

A: I note that @felixmosh is correct here regarding bound values, but just to elaborate: the key here is when the string substitution takes place. If you do this:
db.raw(`SELECT vote WHERE user_id = ${loggedInUserId}`)

the substitution takes place in JavaScript, as soon as the JS interpreter reaches this line. The database engine has nothing to do with whatever is in loggedInUserId and neither does Knex: you're essentially bypassing all the built-in protections.
Slightly better is:
db.raw("SELECT vote WHERE user_id = ?", loggedInUserId)

This allows Knex to escape the string in loggedInUserId. If you prefer, you can use a named binding:
db.raw("SELECT vote WHERE user_id = :loggedInUserId", { loggedInUserId })

However, all of this mucking about with bindings is easily avoided by using the facility Knex already provides for subqueries: just put the subquery in a function.
db
  .from("askify_questions AS q")
  .select(
    "q.id AS question_id",
    qb => qb.select("usr_vote.vote").where({ user_id: loggedInUserId })
  )
  .leftJoin(
    "askify_question_vote AS usr_vote",
    "q.id",
    "usr_vote.question_id"
  );

The qb parameter stands for "query builder", and is passed by Knex to your function. It behaves very much like your db object.
This generates SQL akin to:
SELECT
  "q"."id" AS "question_id",
  (
    SELECT "usr_vote"."user_id" WHERE "user_id" = ?
  )
  FROM "askify_questions AS q"
  LEFT JOIN "askify_question_vote" AS "usr_vote"
    ON "q"."id" = "usr_vote"."question_id"


text:
Q: Office 365 Connector does not show up in Jenkins I have installed the Office 365 connector:

And it doesn't show any tab as "Office 365 Connector" despite many times reinstall and restart:

Jenkins v 2.263.2
What did I do wrong here?

A: The UI does not support multibranch pipelines, but must be called by the script.
Vis a vi, you must create a jenkinsfile and manually call the webhookURL within the pipeline.
https://issues.jenkins.io/browse/JENKINS-39745


text:
Q: OpenVINO - Image classification I tried to use OpenVINO Inference Engine to accelerate my DL inference. It works with one image. But I want to create a batch of two images and then do a inference.
This is my code:
InferenceEngine::Core core;
InferenceEngine::CNNNetwork network = core.ReadNetwork("path/to/model.xml");

InferenceEngine::InputInfo::Ptr input_info = network.getInputsInfo().begin()->second;
std::string input_name = network.getInputsInfo().begin()->first;

InferenceEngine::DataPtr output_info = network.getOutputsInfo().begin()->second;
std::string output_name = network.getOutputsInfo().begin()->first;

InferenceEngine::ExecutableNetwork executableNetwork = core.LoadNetwork(network, "CPU");

InferenceEngine::InferRequest inferRequest = executableNetwork.CreateInferRequest();

std::string input_image_01 = "path/to/image_01.png";
cv::Mat image_01 = cv::imread(input_image_01 );
InferenceEngine::Blob::Ptr imgBlob_01 = wrapMat2Blob(image_01);

std::string input_image_02 = "path/to/image_02.png";
cv::Mat image_02 = cv::imread(input_image_02 );
InferenceEngine::Blob::Ptr imgBlob_02 = wrapMat2Blob(image_02);

InferenceEngine::BlobMap imgBlobMap;
std::pair<std::string, InferenceEngine::Blob::Ptr> pair01(input_image_01, imgBlob_01);
imgBlobMap.insert(pair01);
std::pair<std::string, InferenceEngine::Blob::Ptr> pair02(input_image_02, imgBlob_02);
imgBlobMap.insert(pair02);
inferRequest.SetInput(imgBlobMap);

inferRequest.StartAsync();
inferRequest.Wait(InferenceEngine::IInferRequest::WaitMode::RESULT_READY);

InferenceEngine::Blob::Ptr output = inferRequest.GetBlob(output_name);
std::vector<unsigned> class_results;
ClassificationResult cls(output, {"x", "y"}, 2, 3);
class_results = cls.getResults();

Unfortunately, I received the following error message from the command
inferRequest.SetInput(imgBlobMap);

[NOT_FOUND] Failed to find input or output with name: 'path/to/image_02.png'
C:\j\workspace\private-ci\ie\build-windows-vs2019@2\b\repos\openvino\inference-engine\src\plugin_api\cpp_interfaces/impl/ie_infer_request_internal.hpp:303
C:\Program Files (x86)\Intel\openvino_2021.3.394\inference_engine\include\details/ie_exception_conversion.hpp:66
How can I create a batch of more than image, do a inference and get the information for classification class and confidence? Is the confidence and class located in the received variable of GetBlob()? Should I need the call of ClassificationResult cls(output, {"x", "y"}, 2, 3);?

A: I'd recommend you to review Using Shape Inference article from OpenVINO online documentation to be aware of the limitations of using batches. It also refers to Open Model Zoo smart_classroom_demo, where dynamic batching is used in processing multiple previously detected faces. Basically, when you have batch enabled in the model, the memory buffer of your input blob will be allocated to have a room for all batch of images, and your responsibility is to fill data in input blob for each image in batch from your data. You may take a look at function CnnDLSDKBase::InferBatch, of smart_classroom_demo, which is located at file smart_classroom_demo/cpp/src/cnn.cpp, line 51. As you can see, in the loop over num_imgs an auxiliary function matU8ToBlob fills the input blob with data for current_batch_size of images, then set batch size for infer request and run inference.
for (size_t batch_i = 0; batch_i < num_imgs; batch_i += batch_size) {
    const size_t current_batch_size = std::min(batch_size, num_imgs - batch_i);
    for (size_t b = 0; b < current_batch_size; b++) {
        matU8ToBlob<uint8_t>(frames[batch_i + b], input, b);
    }

    if (config_.max_batch_size != 1)
        infer_request_.SetBatch(current_batch_size);
    infer_request_.Infer();

A: there is a similar sample using the batch inputs as input into model within the OpenVINO. You can refer to below link.
https://github.com/openvinotoolkit/openvino/blob/ae2913d3b5970ce0d3112cc880d03be1708f13eb/inference-engine/samples/hello_nv12_input_classification/main.cpp#L236


text:
Q: File permission with Class File i would like to ask , because in some scenario, some class.php are not being run. even if it is in full permission,
sample.
i have a linux pc. and every time i create class.php file. i modified it like :
sudo chmod -Rf 777 file.class.php

then after that. it works on my localhost.
BUT when i transfer the file using FileZilla to other server its not running.
even if it has Full Permission 777 in File Zilla.
Can anyone explain whats the reason behind this ?
coz i cant explain to my superior why its that running but in my localhost/Pc its running.
and they have the same File and codes inside it.
please help me..
thank you very much.

A: It's possible that your server automatically modifies the permissions of the file when you upload it even when you have it set to something in filezilla.  I know that Windows with NTFS can sometimes strip permissions off of a file depending on how you copy/move the file.  This might be what is happening with your linux computer.


text:
Q: Footer always at very bottom (move with content, but min at bottom) I'm trying to set up a website with header, body and footer. I want the footer to be at the very bottom of the page but move it relative to the content. Here is what I got so far
html:

css:
* {
    padding: 0;
    margin: 0;
}
html {
    overflow-y: scroll;
}
html, body {
    height: 100%;
    width: 100%;
}
#header {
    height: 60px;
    position: fixed;
    top: 10px;
    left: 0;
    right: 0;
}
#body {
    min-height:74.3%;
    width:100%;

    padding-top   : 10%;
    padding-bottom: 40px;
}

#footer {
    height: 40px;
    position: relative;
    z-index: 1;
}

On my resolution (Retina) everything is working fine, but when testing on lower resolutions the footer appears above the page bottom if the content of

 is not enough to fill the whole page.
Any suggestions how to fix this?
Thanks in advance!

A: What you're looking for is a sticky footer,
the quickest approach is to wrap all your content except footer and set a margin-bottom of the size of the footer height, so in your case you should also wrap the header, here's a general ex.:
* {
  margin: 0;
}
html, body {
  height: 100%;
}
wrap {
  min-height: 100%;
  /* equal to footer height */
  margin-bottom: -66px;
}
//for clearfix
wrap:after {
  content: "";
  display: block;
}
.site-footer, .page-wrap:after {
  height: 66px;
}
.site-footer {
  background: tomato;
}

there's also other methods of doing this ,  check this out

A: Try http://ryanfait.com/sticky-footer/
CSS
* {
    margin: 0;
}
html, body {
    height: 100%;
}
.wrapper {
    min-height: 100%;
    height: auto !important; /* This line and the next line are not necessary unless you need IE6 support */
    height: 100%;
    margin: 0 auto -155px; /* the bottom margin is the negative value of the footer's height */
}
.footer, .push {
    height: 155px; /* .push must be the same height as .footer */
}

Another Example : https://css-tricks.com/snippets/css/sticky-footer/

A: Here you go, Example for you:
HTML:

Sticky Footer

with Fixed Footer Height

  I'm the Sticky Footer.

CSS:
* {
    margin: 0;
}
html, body {
    height: 100%;
}
#main {
    min-height: 100%;
    margin:0 auto -142px auto;
    background:#FCF;
}
#main:after {
  content: "";
  display: block;
}
#bottomArea, #main:after {
  /* .push must be the same height as footer */
    height: 142px;
}
#bottomArea {
  background: orange;
}


text:
Q: Stone–Čech compactification and functions that separate points Let $\mathfrak X$ be a completely regular space. We can then consider its Stone–Čech compactification $\beta \mathfrak X$. Every continuous bounded function $f:\mathfrak X \to \mathbb C$ admits a unique continuous extension $\beta f$ to $\beta\mathfrak X$.
Suppose now we are given a family $\mathcal S\subset C(\mathfrak X; [-1,1])$ which separates points of $\mathfrak X$, namely for any $x,y\in\mathfrak X$ with $x\neq y$ there exists $f\in\mathcal S$ such that $f(x)\neq f(y)$.
Set $\beta\mathcal S=\{\beta f; \;f\in \mathcal S\}\subset BC(\beta\mathfrak X)$.
Question: Is it true that $\beta\mathcal S$ separates points of $\beta\mathfrak X$? If it is false, which functions should I add to $\beta\mathcal S$ in order to get the result?

A: $\beta\mathcal S$ need not separate $\beta\mathfrak X$. For example, take $\mathfrak X = \mathbb R$ and $\mathcal S$ to be a collection of functions $f_n$ such that each separates the points of $[-n,n]$ and has value $0$ on all points outside $[-(n+1), n+1)]$. The each $\beta f_n$ will be $0$ on all points of the remainder $\beta\mathbb R \setminus \mathbb R$ and so cannot separate any of its points. You could also choose the functions so that each $f_n(0)=0$, then no $\beta f_n$ will be able to separate $0$ from any point of the remainder.  A similar construction will be possible in any locally-compact $\mathfrak X$.


text:
Q: How to print text when camera captures blue color? I'm working on a script using opencv and python to print text when the camera captures a certain color. I tried to use an if statement, but it fails.
Here's my code:
import cv2
import numpy as np

cap = cv2.VideoCapture(0)

while(1):

    # Take each frame
    _, frame = cap.read()

    # Convert BGR to HSV
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

    # define range of blue color in HSV
    lower_blue = np.array([110,50,50])
    upper_blue = np.array([130,255,255])
    result = lower_blue + upper_blue

    # Threshold the HSV image to get only blue colors
    mask = cv2.inRange(hsv, lower_blue, upper_blue)

    # Bitwise-AND mask and original image
    res = cv2.bitwise_and(frame,frame, mask= mask)

    if result.any() == True:
       print 'I can see blue color'

    cv2.imshow('frame',frame)
    cv2.imshow('mask',mask)
    cv2.imshow('res',res)

    k = cv2.waitKey(5) & 0xFF
    if k == 27:
        break

cv2.destroyAllWindows()

A: I worked out a solution that works for my environment. I'm using Python 2.7 and OpenCV 2.4.6. you may need to modify the blue_threshold value to suit your needs.
import cv2
import numpy as np

cap = cv2.VideoCapture(0)
blue_threshold = 1000000  # This value you could change for what works best

while True:

    # Take each frame
    _, frame = cap.read()

    # Convert BGR to HSV
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

    # define range of blue color in HSV
    lower_blue = np.array([110,50,50])
    upper_blue = np.array([130,255,255])

    # Threshold the HSV image to get only blue colors
    mask = cv2.inRange(hsv, lower_blue, upper_blue)
    count = mask.sum()

    if count > blue_threshold:
       print 'I can see blue color'

    cv2.imshow('frame',frame)
    cv2.imshow('mask',mask)

    k = cv2.waitKey(5) & 0xFF
    if k == 27:
        break

cv2.destroyAllWindows()


text:
Q: Elasticsearch 5.2.2 :: Deleting an entry in a map field has no effect I have a map field, and I'm trying to update it with a script (Painless). when I execute the script with a rest client it works, but not working with the java API (No change, but the result in the UpdateResponse is "UPDATED"). Anyone can help me resolving this:
Elasticsearch 5.2.2 (Tried also on 5.1.1)
--------- Rest Client (Chrome):
POST localhost:9200/context/profile/720c7bc5-9c52-48bd-b281-760f595c6418/_update
BODY :{
    "scriptedUpsert": true,
    "script": {
      "lang": "painless",
      "inline": "ctx._source.put(\"scores\", params.scoringValue)",
      "params": {
      "scoringValue": {
        "_i833rilwd": 333
      }
    }
}
}

--------- Java Client:
String script = "ctx._source.put(\"scores\", params.scoringValue)";

//Map where I remove and put to update
Map scores = toRemove.getScores();

HashMap scriptParams = new HashMap<>();
scriptParams.put("scoringValue", scores);

Script actualScript = new Script(ScriptType.INLINE, "painless", script, scriptParams);

UpdateResponse resp = client.prepareUpdate(index, itemType, itemId).setScript(actualScript)
.execute()
.get();

Thx in advance for your help

A: I am not sure about JAVA but i think problem is in

\"

try this
String script = "ctx._source.put(\\"scores\\", params.scoringValue)";

A: Resolved by doing a refresh index before the remove, if not there was document version conflicts. Hope this will help.


text:
Q: Synchronized, join, and thread safety I have read through other examples, but do not understand why this code with the commented out t.join() does not always have the end value 5000 for count, but when the code is commented in, count always is 5000 at the end. But why? I thought that the static lock object can only be owned by one thread at a time and when it is owned that the other threads have to wait until it is released. So I do not understand why join() is necessary and what exactly is happening.
import java.util.ArrayList;

public class MyClass implements Runnable {
    private static int count = 0;
    private static Object lock = new Object();

    public static void main(String[] args) throws InterruptedException {
        ArrayList<Thread> threads = new ArrayList<>();
        for (int i = 1; i <= 5000; i++)
            threads.add(new Thread(new MyClass()));

        for (Thread t : threads)
            t.start();
        // for (Thread t : threads)
        //     t.join();

        System.out.println("Total count = " + MyClass.getCount());
    }

    public void run() {
        synchronized (lock) {
            count++;
        }
    }

    public static int getCount() {
        return count;
    }
}


text:
Q: Ring spectra structures on a certain spectral analogue of $\mathbb{Z}/2$ We can characterise $\mathbb{Z}$ and $\mathbb{Z}/2$ as the corepresenting abelian groups of the functors
\begin{align*}
    \mathsf{Forget} &\colon \mathsf{Ab} \to \mathsf{Sets},\\
    \mathrm{Inv}    &\colon \mathsf{Ab} \to \mathsf{Sets}
\end{align*}
given by $(A,\cdot_A,1)\mapsto A$ and $A\mapsto\mathrm{Inv}(A)\overset{\mathrm{def}}{=}\left\{a\in A\ \middle|\ a^2=1_A\right\}$.
A similar approach in the $\infty$-world gives the $\mathbb{E}_\infty$-groups $QS^0$ and $\Omega Q\mathbb{RP}^\infty$. Passing to spectra via the equivalence between $\mathbb{E}_\infty$-groups and connective spectra, we obtain the sphere spectrum $\mathbb{S}$ corresponding to $QS^0$ and a spectrum $E$ corresponding to $\Omega Q\mathbb{RP}^\infty$.
(One possible name for $E$ might be "$\mathbb{S}/2$" since it satisfies an analogous universal property to that of $\mathbb{Z}/2$, corepresenting "involutory objects". However, that notation already usually denotes the mod 2 Moore spectrum, so let's write $E$ for it instead.)
For comparison, their first $8$ homotopy groups are as follows:
$$
\begin{aligned}
\pi_0(\mathbb{S}) &\cong \mathbb{Z},\\
\pi_1(\mathbb{S}) &\cong \mathbb{Z}/2,\\
\pi_2(\mathbb{S}) &\cong \mathbb{Z}/2,\\
\pi_3(\mathbb{S}) &\cong \mathbb{Z}/24,\\
\pi_4(\mathbb{S}) &\cong 0,\\
\pi_5(\mathbb{S}) &\cong 0,\\
\pi_6(\mathbb{S}) &\cong \mathbb{Z}/2,\\
\pi_7(\mathbb{S}) &\cong \mathbb{Z}/16\times\mathbb{Z}/3\times\mathbb{Z}/5,
\end{aligned}
\quad\quad
\begin{aligned}
\pi_0(E) &\cong \mathbb{Z}/2,\\
\pi_1(E) &\cong \mathbb{Z}/2,\\
\pi_2(E) &\cong \mathbb{Z}/8,\\
\pi_3(E) &\cong \mathbb{Z}/2,\\
\pi_4(E) &\cong 0,\\
\pi_5(E) &\cong \mathbb{Z}/2,\\
\pi_6(E) &\cong \mathbb{Z}/16\times\mathbb{Z}/2,\\
\pi_7(E) &\cong \mathbb{Z}/2\times\mathbb{Z}/2\times\mathbb{Z}/2.
\end{aligned}
$$
(The ones for $E$ are taken from Liulevicius; see also MO 230790.)

What (homotopy associative, homotopy commutative, $\mathbb{A}_k$-, $\mathbb{E}_k$-, or $\mathbb{E}_\infty$-) ring spectra structures, if any, are there on $E$?

A: There are no left-unital multiplications on E. If there were, then for any element $x$ in $\pi_n(E)$, we would have $x+x = 1 \cdot x + 1 \cdot x = (1+1) \cdot x = 0$ because all elements in $ \pi_0 E$ are 2-torsion. This is not satisfied by the homotopy groups in your table.


text:
Q: How to have all the images in a folder stacked on top of each other in ffmpeg? I have a folder that contains nothing but images named 1.jpg - 484.jpg. Is there a simple way to have all the images stacked on top each other in one long image in ffmpeg? (preferably with one command)
I've searched for this thing a bunch of times but I haven't found the answer I was looking for. Thanks in advance!

A: If needing ffmpeg, the vstack filter complex is useful.  This example uses vstack to iterate in a directory (with even number of files in the subsets and a one pixel high blank buffer 000.jpg).
prev=src/000.jpg; i=0; odd=1; num=0; for file in src/*; do num=$(($num+1)) && if [ $odd == "-1" ]; then ffmpeg -i $prev -i $file -filter_complex "[0:v][1:v]vstack[s]" -map "[s]" -y out/0output$i.jpg; fi && odd=$(($odd*-1)); prev=$file && i=$(($i+1)); done; sets=$(echo "scale=0;sqrt($num)"|bc); n=0; for (( a=0; a<sets ; a++ )); do prev=src/000.jpg && i=0 && n=$(($n+1)) && odd=1 && for file in out/"$(($n-1))"output*.jpg; do if [ $odd == "-1" ]; then ffmpeg -i $prev -i $file -filter_complex "[0:v][1:v]vstack[s]" -map "[s]" -y out/"$n"output$i.jpg; fi && prev=$file && i=$(($i+1)) && odd=$(($odd*-1)); done; done;

Given inputs:  ,,etc
Yielding:


text:
Q: Creating a Drupal service module? Currently, I am trying to connect a to custom built Drupal 7 service module with a flash client.  I can connect to my the amfserver service properly and actually use the Node service to grab and manipulate nodes.  I am trying to build a custom service to remotely provide functions not provided by the available services.  I am trying to put together a simple framework to get communication working between my service module and my server.  I am having tons of issues as I do not know how to properly build a service and most of the information I can find I can not get working well.  Currently, I can confirm that my flash app is connecting to the module but the module is returning NULL.  I figure it is probably something simple but I am not too familiar with php and working with the Drupal API so any assistance would be nice.  Here is the code I currently have for the module.
<?php
// mrbremoteresource.module
/**
 * Implements hook_perm().
 */
function mrbremoteresourse_perm() {
    return array(
        'mrbremote resource search',
    );
}

/**
 * Perform a search node ID.
 *
 * @param string $id
 *  Node ID to lookup
 * @return object
 */
function mrbremoteresource_search($id) {
    $nodes = array();
    $result = db_query("SELECT title FROM {node} WHERE nid=:id", array(':id' => $id));
    $res = $result->fetchObject();
    foreach ($res as $node) {
        $nodes[] = $node;
    }
    return $nodes;
}
/**
 * Implements hook_services_resources().
 */
function mrbremoteresource_services_resources() {
  return array(
    'mrbremote' => array(
       'search' => array(
         'help' => 'Retrieve a node',
         'file' => array('file' => 'inc', 'module' => 'mrbremoteresource'),
         'callback' => '_mrbremoteresource_find',
         'access callback' => '_mrbremoteresource_access',
         'access arguments' => array('view'),
         'access arguments append' => TRUE,
          'args' => array(
           array(
             'name' => 'id',
             'type' => 'int',
             'description' => 'The id of the node to get',
             'source' => array('path' => '0'),
             'optional' => FALSE,
            ),
        ),
      ),
     ),
    );
     }

/**
 * Access callback for the node resource.
 *
 * @param string $op
 *  The operation that's going to be performed.
 * @param array $args
 *  The arguments that will be passed to the callback.
 * @return bool
 *  Whether access is given or not.
 */
function _mrbremoteresource_access($op, $args) {
  global $user;
  $access = FALSE;

  switch ($op) {
    case 'view':
      $node = mrbremoteresource_search($args[0]);
      $access = user_access('this resource view any node');
      $access = $access || $note->uid == $user->uid && user_access('this resource view own nodes');
      break;
  }

  // Force access for debugging
  $access = TRUE;
  return $access;
}?>

<?php
    // noteresource.inc
    /**
     * Callback for retrieving note resources.
     *
     * @param string $id
     *  Node ID to lookup
     * @return object
     */
    function _mrbremoteresource_find($id) {
      return mrbremoteresoure_search($id);
    }
?>

I was using information from Drupal API Documentation to try and accomplish this but have so far been unsuccessful.  What would be the best way to get this working?
EDIT: I am adding code from a simple flash client.  I am actually trying to use this with another application but I just tossed this tiny application together so I could debug with it.
<?xml version="1.0" encoding="utf-8"?.>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
           xmlns:s="library://ns.adobe.com/flex/spark"
           xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"
           initialize="init();">
<fx:Script>
    <![CDATA[
        public function init():void {
            remNode.search("1")
        }
        public function onResult(responds:Object):void {
            trace(responds);
        }
        public function onFault(responds:Object):void {
            trace(responds);
        }
    ]]>
</fx:Script>

<fx:Declarations>
    <s:RemoteObject endpoint="http://localhost/drupal/remmirecipebox"
                    destination="amfserver"
                    source="mrbremote"
                    id="remNode"
                    showBusyCursor="true">
        <s:method name="search" result="onResult(event)" fault="onFault(event)"/>
    </s:RemoteObject>
</fx:Declarations> </s:Application>

In the xml tag at the top I just put a . between the ? and the > because it kept cutting out my code.  It is not in the actual application code.


text:
Q: Crazy widths using SimpleModal in IE9 Has anyone else tried using SimpleModal in IE9? If so, have you experienced that the width of the modal is wildly wrong?
I checked on the homepage for SimpleModal, and the modals are all over the place width-wise there as well.
Does anyone have a fix for this?

A: The best thing I have managed to come up with is to surround the SimpleModal divs that you are creating with another div that specifies the width.
Essentially it seems that the divs will always go to 100% of the container they are in, so use other divs to contain their size, and keep them in alignment.

A: I just released SimpleModal 1.4.1 - see if that resolves your issues.
http://code.google.com/p/simplemodal/downloads/list


text:
Q: Apiary limiting a response return So I'm using Apiary to hold and array of data, and then call the data to display on HTML but I only want Apiary to send a limited amount of data to HTML, not the full array. Still trying to get my head around Apiary syntax, so just wondering if I'm heading in the right direction (or would I be doing this via the frontend?), because what I'm using doesn't work and the documentation isn't clear to me :
##news updates [/articles{?limit}]
###Get all news [GET]

+ Parameters

+ limit (number, optional)
    + Default: '3'

+ Request

  + Header

        Authorization: Basic dXNlcjpwYXNzd29yZA==
        x-api-verson: 1.0

+ Response 200 (application/json)

        {
                "articles": [
                    {
                        *array item one*
                    },
                    {
                        *array item two*
                    },
                    {
                        *array item three*
                    },
                    {
                        *array item four*
                    },
                  ]
         }

A: You can set up multiple examples, per here:
https://github.com/apiaryio/api-blueprint/blob/master/API%20Blueprint%20Specification.md#example-multiple-transaction-examples
And then you can access different examples using the Prefer header in a mock request per "Invoking non-default responses" section here:
http://support.apiary.io/knowledgebase/articles/117119-handling-multiple-actions-on-a-single-resource


text:
Q: Mesos task resources - CPU & Mem I use Meosos for batch Jobs. Jobs will be running as a docker container by the framework. The are 2 salves running on each VM. The resource for each Job was set to
CPUS - 0.1
MEM - 1G

Its a 4 core machine and mesos was considering it as 8 core as there are 2 slaves in each VM. So, it tried to overload the VM by submitting too many tasks, literally up to 80 jobs ( (4+4)/0.1 = 80). So, during the peak load VM used to crash.
Tried changing the CPU to 0.5 so that the VM will not be overloaded. (( (4+4)/0.5 = 20)). But, looks like CPU usage still goes up to 95%. The tasks are not CPU intensive task, but not sure why it is trying to consume 95%.
Is it like, tasks will be using the resource no matter even it actually requires them? So, it will allocate 0.5 by default or max to 0.5 in case it requires?

A: Having two agents on the same host/VM is more like an antipattern. If you want to oversubscribe on resources, have a look at the Mesos docs at http://mesos.apache.org/documentation/latest/oversubscription/


text:
Q: Segmentation fault in NULL check? I am getting a segmentation fault while trying to check if some elements are NULL or not. Can anyone help?
    void addEdge(int i, int j)
{
        if (i >= 0 && j > 0)
    {
        Node* whereto;
        whereto = linkedAdjacencyList[i];
        if(whereto != NULL)
        {
            while(whereto->adj != NULL)
            {whereto = whereto->adj;}
            whereto->adj = linkedAdjacencyList[j];
        }
        else{linkedAdjacencyList[i]->adj = linkedAdjacencyList[j];}
        whereto = linkedAdjacencyList[j];
        if(whereto != NULL)
        {
            while(whereto->adj != NULL)
            {whereto = whereto->adj;}
            whereto->adj = linkedAdjacencyList[i];
        }
        else{linkedAdjacencyList[j]->adj = linkedAdjacencyList[i];}
            }
    }

help!
EDIT: this is the new code, as per your suggestions, but now there is a segmentation fault immediately when the method is called? i'll post the calling...
int edges;
in >> edges;
g.edges = edges;
for(int i = 0; i < edges; i++)
{
    int first;
    int second;
    in >> first >> second;
    g.addEdge(first, second);
}

A: I suggest that linkedAdjacencyList[i] returns NULL, so you are trying to dereference NULL. Just add extra check for NULL :
Node* whereto = NULL;
whereto = linkedAdjacencyList[i];
if (NULL != whereto){
while(whereto->adj != NULL) .....

A: You don't seem to check whether whereto is being initialized properly in whereto = linkedAdjacencyList[i];.

A: The expression whereto -> adj != NULL uses whereto as a pointer and dereferences it with adj at its offset from the beginning of the structure or class.  If that statement is segfaulting, it means whereto has a bad pointer value.  Check what comes out of linkedAdjancencyList[] and don't use it if NULL.

A: Put an if check above the while loop and check whether whereto is NULL.
if(whereto!=NULL){
while(whereto->adj != NULL).........
}


text:
Q: Insert if not exist under RCSI I have a database with READ_COMMITTED_SNAPSHOT_ISOLATION set ON (cannot change that).
I insert new rows into a table on many parallel sessions,
but only if they don't exist there yet (classic left join check).
The inserting code looks like this:
INSERT INTO dbo.Destination(OrderID)
SELECT DISTINCT s.OrderID
FROM dbo.Source s
LEFT JOIN dbo.Destination d ON d.OrderID = s.OrderID
WHERE d.OrderID IS NULL;

If I run this on many parallel sessions I get a lot of duplicate key errors,
since different sessions try to insert the same OrderIDs over and over again.
That is expected due to the lack of SHARED locks under RCSI.
The recommended solution here (as per my research) would be to use the READCOMMITTEDLOCK hint like this:
LEFT JOIN dbo.Destination d WITH (READCOMMITTEDLOCK) ON d.OrderID = s.OrderID

This somewhat works, as greatly reduces the duplicate key errors, but (to my surprise) doesn't completely eliminate them.
As an experiment I removed the unique constraint on the Destination table, and saw that many duplicates enters the table in the very same millisecond originated from different sessions.
It seems that despite the table hint, I still get false positive on the existence check, and the redundant insert fires.
I tried different hints (SERIALIZABLE) but it made it worse and swarmed me with deadlocks.
How could I make this insert work under RCSI?

A: The right lock hint for reading a table you are about to insert into is (UPDLOCK,HOLDLOCK), which will place U locks on the rows as you read them, and also place SERIALIZABLE-style range locks if the row doesn't exist.
The problem with your approach is that each client is attempting to insert a batch of rows, and each batch has to either succeed completely or fail.  If you use row-level locking, you will always have scenarios where a session inserts one row succesfully, but then becomes blocked waiting to read or insert a subsequent row.  This inevitably leads to either PK failures or deadlocks, depending on the type of row lock used.
The solution is to either:
1) Insert the rows one-by-one, and not hold the locks from one row while you check and insert the next row.
2) Simply escalate to a tablockx, or an Applciation Lock to force your concurrent sessions to serialize through this bit of code.
So you can have highly-concurrent loads, or batch loads, but you can't have both.  Well mostly.
3) You could turn on IGNORE_DUP_KEY on the index, which instead of an error will just skip any duplicate when inserting.


text:
Q: Is my formula for the CDF of negative binomial distribution right? Due to the differences in notation for the formula of the CDF of negative binomial distribution from Wikipedia, ScienceDirect and Vose Software, I decide to rewrite it in the way that I can easily understand.  We have:
$x$ number of trials, $x = \textrm{1, 2, ...}$
$r$ number of failures, $r = \textrm{1, 2, ... }x$
$k$ number of successes, $k = x - r = \textrm{0, 1, ... }$
$p$ probability of success, $0<p<1$
The formula for the CDF of binomial distribution is:
$$F_{X_k}(x)=P(X_k\leq x)=\sum_{i=1}^{x}{{k+i}\choose{i}}p^{k}{(1-p)}^{i}$$
Do I have it right?  Many thanks!

A: As in your question Correct formulas for the mean and variance of negative binomial distribution at CrossValidated, the different sites you link to seem to have different ideas of what $p$ is. The $p$ at ScienceDirect seems to be the probability of failure, whereas the $p$ at Wikipedia is the one of success. (The latter appears intuitively more appealing to me. R also uses the convention that the prob parameter to rnbinom() stands for the probability of success.)
Also as in the CV question and as Henry notes, you need to take care of whether you define your random variable as counting the number of trials or of failures until you see $k$ successes. Or even as the number of trials or of successes until you see $r$ failures.
Your random variable $X_k$ apparently counts the number of failures until you see $k$ successes. This is almost exactly the formulation used in Wikipedia, except that Wikipedia's formulation counts the number of successes until we see a certain number of failures. (Conversely, R does it your way.) We can account for this by exchanging the definition of "success" and "failure", which amounts to changing $p$ in the Wikipedia article to $(1-p)$. (Also note that Wikipedia's $r$ is your $k$.) The PMF is then
$$ P(X_k=i) = {i+k-1 \choose i}p^k (1-p)^i. $$
For the CDF, we have to sum from zero (we may see zero failures) to the $x$ you want:
$$ P(X_k\leq x) = \sum_{i=0}^x P(X_k=i) = \sum_{i=0}^x{i+k-1 \choose i}p^k (1-p)^i. $$
This looks a little different from your formula, both in terms of the summation (which needs to start from zero, as above) and of a different binomial coefficient. I can't quite reconstruct where this comes from, but a little simulation in R appears to vindicate the CDF I propose (bars are simulation results, the black line gives my CDF, the red line yours):

rm(list=ls())

pp <- 0.3   # probability of success
kk <- 2 # number of successes

nn <- 10000
failures <- rnbinom(nn,size=kk,prob=pp) # gives number of *failures*, see ?rnbinom

cdf_sk <- Vectorize(function(xx) {
    ii <- 0:xx
    sum(choose(ii+kk-1,ii)*pp^kk*(1-pp)^ii)}, vectorize.args="xx")

cdf_muxo <- Vectorize(function(xx) {
    ii <- 1:xx
    sum(choose(kk+ii,ii)*pp^kk*(1-pp)^ii)}, vectorize.args="xx")

plot(0:max(failures),cumsum(table(factor(failures,levels=0:max(failures))))/nn,
    type="h",xlab="",ylab="",las=1)
lines(0:max(failures), cdf_sk(0:max(failures)))
lines(0:max(failures), cdf_muxo(0:max(failures)),col="red")

A: I think the best way we can think to a Pascal random variable $X_{n}$ with distribution $\mathcal{NB}(p,n)$ is to think at it as a sum of $Y_{1}+\cdots+Y_{n}$ of $n$ random independant with equal geometric distribution $\mathcal{G}(p)-1$.
Infact you can notice this considering $Y_{i}$ as the random variable which keeps tracks of the failures betweeen the $(i-1)$-th and $i$-th success. $Y_{i}$ are clearly independant and have distribution of parameter $p$ minus 1 because the geometric distribution counts the number of trial needed in order to gain a success, which correspond to the number of failures and the the final success.
In this way is easier to verify your distribution correctness. You can find some reference here


text:
Q: APNs Remote Notifications Delegate Methods Not Being Called We have an app thats ONLY designed be run on iOS7. We have installed the PersistentConnectionLogging configuration profile to further debug our issue (as described in the Trouble Shooting Push Notifications technical note).
We have confirmed the phone has a full and valid 3G internet connection through the cellular modem (with WiFi disabled), the application is allowing remote notifications in settings and is successfully working on many other devices running the exact same build on the exact same model phone (iPhone 4S). The phone is also supervised for an MDM service.
On phones that are working it goes something like this (tried to pick out the useful console messages),
Nov 17 11:15:14 MDM-Test-Phone-2 TestApp[546] <Warning>: >>>>>>>> APP LAUNCHED <<<<<<<<

....

Nov 17 11:15:15 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-11-17 11:15:15 -0500 apsd[82]: peer(34) received XPC_ERROR_CONNECTION_INVALID

...

Nov 17 11:15:15 calling, [[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeNewsstandContentAvailability];

...

Nov 17 11:15:15 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-11-17 11:15:15 -0500 apsd[82]: Looking up connection on peer: 15d71590  found <APSConnectionServer: 0x15db0a00>
Nov 17 11:15:15 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-11-17 11:15:15 -0500 apsd[82]:    <APSCourier: 0x15d658d0>: Received request from <APSConnectionServer: 0x15db0a00> to generate token for topic "com.test.test" and identifier ""
Nov 17 11:15:15 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-11-17 11:15:15 -0500 apsd[82]: copyTokenForDomain sandbox.push.apple.com ,fffffff7ffffff93ffffffe039604451ffffff8cffffffccffffff80ffffffe75c0affffffe0ffffffcf5d4dffffff8cffffffa41a
Nov 17 11:15:15 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-11-17 11:15:15 -0500 apsd[82]: <APSCourier: 0x15d658d0> found cached token <c150ca2f 039dc8fb a642ac22 47d8f80b abc9d186 0811a083 a4820d99 d749c09b> for appSpecificIdentifier ,fffffff7ffffff93ffffffe039604451ffffff8cffffffccffffff80ffffffe75c0affffffe0ffffffcf5d4dffffff8cffffffa41a
Nov 17 11:15:15 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-11-17 11:15:15 -0500 apsd[82]: <APSCourier: 0x15d658d0> handleReceivedPublicToken: <c150ca2f 039dc8fb a642ac22 47d8f80b abc9d186 0811a083 a4820d99 d749c09b> forTopic com.test.test identifier
Nov 17 11:15:15 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-11-17 11:15:15 -0500 apsd[82]: Dispatching low priority message: <OS_xpc_dictionary: <dictionary: 0x15dc1660> { count = 4, contents =
    "identifier" => <string: 0x15db2060> { length = 0, contents = "" }
    "message-type" => <int64: 0x15dbb460>: 21
    "topic" => <string: 0x15d9a800> { length = 22, contents = "com.test.test" }
    "token" => <data: 0x15dbd9d0>: { length = 32 bytes, contents = 0xc150ca2f039dc8fba642ac2247d8f80babc9d1860811a083... }
}>

...

didRegisterForRemoteNotificationsWithDeviceToken successfully called

...

Nov 17 11:24:41 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-11-17 11:24:41 -0500 apsd[82]: _getClientIdentity: already had identity: <SecIdentityRef: 0x15da1850>

However, on phones that are not working it goes something like this,
Oct 23 10:50:55 MDM-Test-Phone-2 TestApp[145] <Warning>: >>>>>>>> APP LAUNCHED <<<<<<<<
Oct 23 10:50:56 MDM-Test-Phone-3 apsd[82] <Warning>: 2014-10-23 10:50:56 -0400 apsd[82]: peer(34) received XPC_ERROR_CONNECTION_INVALID
Oct 23 10:50:56 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:50:56 -0400 apsd[82]: _getClientIdentity: already had identity: <SecIdentityRef: 0x14dbcc20>
Oct 23 10:50:56 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:50:56 -0400 apsd[82]: peer(34) received XPC_ERROR_CONNECTION_INVALID

...

Oct 23 10:50:56 calling, [[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeNewsstandContentAvailability];

...

Oct 23 10:51:05 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:05 -0400 apsd[82]: Interface manager: WWAN radio power level notification; DCH status changed to inactive
Oct 23 10:51:05 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:05 -0400 apsd[82]: <APSCourier: 0x14db94b0> <PCInterfaceMonitor: 0x14d7c5f0> interface radio hotness changed to NO
Oct 23 10:51:05 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:05 -0400 apsd[82]: <APSTopicManager: 0x14db9930> isPowerEfficientToSendFilter changed to NO
Oct 23 10:51:05 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:05 -0400 apsd[82]: <APSCourier: 0x14d74090> <PCInterfaceMonitor: 0x14d7c5f0> interface radio hotness changed to NO
Oct 23 10:51:05 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:05 -0400 apsd[82]: <PCInterfaceUsabilityMonitor: 0x14d44ad0> [WWAN](pdp_ip0): isInterfaceUsable? YES reachable YES linkQuality 100 isNetworkCaptive? NO
Oct 23 10:51:05 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:05 -0400 apsd[82] com.apple.Duet.APLSScheduler: <PCPersistentTimer: 0x14dac940> calculating _earlyFireDate. powerStateDetectionSupported = YES = (detectionSupported(YES) && (wwanIsUp(YES) || ! internetReachable(YES)))
Oct 23 10:51:05 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:05 -0400 apsd[82] com.apple.Duet.APLSScheduler: <PCPersistentTimer: 0x14dac940> Device is plugged in, overriding earlyFireProportion to be 1.0
Oct 23 10:51:05 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:05 -0400 apsd[82] com.apple.Duet.APLSScheduler: <PCPersistentTimer: 0x14dac940> Calculated minimum fire date [2014-10-23 16:50:34 -0400] (98.1318%) with fire date [2014-10-23 16:57:34 -0400], start date [2014-10-23 10:42:52 -0400], minimum early fire proportion 0.981318, power state detection supported: yes, in high power state: no
Oct 23 10:51:05 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:05 -0400 apsd[82]: <PCInterfaceUsabilityMonitor: 0x14d44ad0> [WWAN](pdp_ip0): isInterfaceUsable? YES reachable YES linkQuality 100 isNetworkCaptive? NO
Oct 23 10:51:05 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:05 -0400 apsd[82] com.apple.apsd(push.apple.com)-WWAN: <PCPersistentTimer: 0x14d5bad0> calculating _earlyFireDate. powerStateDetectionSupported = YES = (detectionSupported(YES) && (wwanIsUp(YES) || ! internetReachable(YES)))
Oct 23 10:51:05 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:05 -0400 apsd[82] com.apple.apsd(push.apple.com)-WWAN: <PCPersistentTimer: 0x14d5bad0> Device is plugged in, overriding earlyFireProportion to be 1.0
Oct 23 10:51:05 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:05 -0400 apsd[82] com.apple.apsd(push.apple.com)-WWAN: <PCPersistentTimer: 0x14d5bad0> Calculated minimum fire date [2014-10-23 11:24:44 -0400] (100%) with fire date [2014-10-23 11:24:44 -0400], start date [2014-10-23 10:43:51 -0400], minimum early fire proportion 0, power state detection supported: yes, in high power state: no
Oct 23 10:51:07 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:07 -0400 apsd[82] interfacemanager-wifiautoassoc: SimpleTimer <PCSimpleTimer: 0x14d72cd0> has fired
Oct 23 10:51:07 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:07 -0400 apsd[82] interfacemanager-wifiautoassoc: Invalidating simple timer <PCSimpleTimer: 0x14d72cd0>
Oct 23 10:51:07 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:07 -0400 apsd[82]: Disabling power monitoring for <PCSimpleTimer: 0x14d72cd0> - 5 timers
Oct 23 10:51:20 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:20 -0400 apsd[82] interfacemanager-wow: SimpleTimer <PCSimpleTimer: 0x14d561e0> has fired
Oct 23 10:51:20 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:20 -0400 apsd[82] interfacemanager-wow: Invalidating simple timer <PCSimpleTimer: 0x14d561e0>
Oct 23 10:51:20 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:20 -0400 apsd[82]: Disabling power monitoring for <PCSimpleTimer: 0x14d561e0> - 4 timers
Oct 23 10:51:28 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:28 -0400 apsd[82]: Interface manager: WWAN radio power level notification; DCH status changed to active
Oct 23 10:51:28 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:28 -0400 apsd[82]: <APSCourier: 0x14db94b0> <PCInterfaceMonitor: 0x14d7c5f0> interface radio hotness changed to YES
Oct 23 10:51:28 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:28 -0400 apsd[82]: <APSTopicManager: 0x14db9930> isPowerEfficientToSendFilter changed to YES
Oct 23 10:51:28 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:28 -0400 apsd[82]: <APSCourier: 0x14d74090> <PCInterfaceMonitor: 0x14d7c5f0> interface radio hotness changed to YES
Oct 23 10:51:28 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:28 -0400 apsd[82]: <PCInterfaceUsabilityMonitor: 0x14d44ad0> [WWAN](pdp_ip0): isInterfaceUsable? YES reachable YES linkQuality 100 isNetworkCaptive? NO
Oct 23 10:51:28 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:28 -0400 apsd[82] com.apple.Duet.APLSScheduler: <PCPersistentTimer: 0x14dac940> calculating _earlyFireDate. powerStateDetectionSupported = YES = (detectionSupported(YES) && (wwanIsUp(YES) || ! internetReachable(YES)))
Oct 23 10:51:28 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:28 -0400 apsd[82] com.apple.Duet.APLSScheduler: <PCPersistentTimer: 0x14dac940> Device is plugged in, overriding earlyFireProportion to be 1.0
Oct 23 10:51:28 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:28 -0400 apsd[82] com.apple.Duet.APLSScheduler: <PCPersistentTimer: 0x14dac940> Calculated minimum fire date [2014-10-23 16:50:34 -0400] (98.1318%) with fire date [2014-10-23 16:57:34 -0400], start date [2014-10-23 10:42:52 -0400], minimum early fire proportion 0.981318, power state detection supported: yes, in high power state: yes
Oct 23 10:51:28 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:28 -0400 apsd[82]: <PCInterfaceUsabilityMonitor: 0x14d44ad0> [WWAN](pdp_ip0): isInterfaceUsable? YES reachable YES linkQuality 100 isNetworkCaptive? NO
Oct 23 10:51:28 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:28 -0400 apsd[82] com.apple.apsd(push.apple.com)-WWAN: <PCPersistentTimer: 0x14d5bad0> calculating _earlyFireDate. powerStateDetectionSupported = YES = (detectionSupported(YES) && (wwanIsUp(YES) || ! internetReachable(YES)))
Oct 23 10:51:28 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:28 -0400 apsd[82] com.apple.apsd(push.apple.com)-WWAN: <PCPersistentTimer: 0x14d5bad0> Device is plugged in, overriding earlyFireProportion to be 1.0
Oct 23 10:51:28 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:28 -0400 apsd[82] com.apple.apsd(push.apple.com)-WWAN: <PCPersistentTimer: 0x14d5bad0> Calculated minimum fire date [2014-10-23 11:24:44 -0400] (100%) with fire date [2014-10-23 11:24:44 -0400], start date [2014-10-23 10:43:51 -0400], minimum early fire proportion 0, power state detection supported: yes, in high power state: yes
Oct 23 10:51:36 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:36 -0400 apsd[82]: Interface manager: WWAN radio power level notification; DCH status changed to inactive
Oct 23 10:51:36 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:36 -0400 apsd[82]: <APSCourier: 0x14db94b0> <PCInterfaceMonitor: 0x14d7c5f0> interface radio hotness changed to NO
Oct 23 10:51:36 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:36 -0400 apsd[82]: <APSTopicManager: 0x14db9930> isPowerEfficientToSendFilter changed to NO
Oct 23 10:51:36 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:36 -0400 apsd[82]: <APSCourier: 0x14d74090> <PCInterfaceMonitor: 0x14d7c5f0> interface radio hotness changed to NO
Oct 23 10:51:36 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:36 -0400 apsd[82]: <PCInterfaceUsabilityMonitor: 0x14d44ad0> [WWAN](pdp_ip0): isInterfaceUsable? YES reachable YES linkQuality 100 isNetworkCaptive? NO
Oct 23 10:51:36 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:36 -0400 apsd[82] com.apple.Duet.APLSScheduler: <PCPersistentTimer: 0x14dac940> calculating _earlyFireDate. powerStateDetectionSupported = YES = (detectionSupported(YES) && (wwanIsUp(YES) || ! internetReachable(YES)))
Oct 23 10:51:36 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:36 -0400 apsd[82] com.apple.Duet.APLSScheduler: <PCPersistentTimer: 0x14dac940> Device is plugged in, overriding earlyFireProportion to be 1.0
Oct 23 10:51:36 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:36 -0400 apsd[82] com.apple.Duet.APLSScheduler: <PCPersistentTimer: 0x14dac940> Calculated minimum fire date [2014-10-23 16:50:34 -0400] (98.1318%) with fire date [2014-10-23 16:57:34 -0400], start date [2014-10-23 10:42:52 -0400], minimum early fire proportion 0.981318, power state detection supported: yes, in high power state: no
Oct 23 10:51:37 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:37 -0400 apsd[82]: <PCInterfaceUsabilityMonitor: 0x14d44ad0> [WWAN](pdp_ip0): isInterfaceUsable? YES reachable YES linkQuality 100 isNetworkCaptive? NO
Oct 23 10:51:37 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:37 -0400 apsd[82] com.apple.apsd(push.apple.com)-WWAN: <PCPersistentTimer: 0x14d5bad0> calculating _earlyFireDate. powerStateDetectionSupported = YES = (detectionSupported(YES) && (wwanIsUp(YES) || ! internetReachable(YES)))
Oct 23 10:51:37 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:37 -0400 apsd[82] com.apple.apsd(push.apple.com)-WWAN: <PCPersistentTimer: 0x14d5bad0> Device is plugged in, overriding earlyFireProportion to be 1.0
Oct 23 10:51:37 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:37 -0400 apsd[82] com.apple.apsd(push.apple.com)-WWAN: <PCPersistentTimer: 0x14d5bad0> Calculated minimum fire date [2014-10-23 11:24:44 -0400] (100%) with fire date [2014-10-23 11:24:44 -0400], start date [2014-10-23 10:43:51 -0400], minimum early fire proportion 0, power state detection supported: yes, in high power state: no
Oct 23 10:51:55 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:55 -0400 apsd[82]: Screen did lock (Was unlocked for 100.329434 seconds)
Oct 23 10:51:55 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:55 -0400 apsd[82]: Delivering systemDidLock to <APSNetworkMonitor: 0x14d7da10>
Oct 23 10:51:55 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:55 -0400 apsd[82]: <APSNetworkMonitor: 0x14d7da10> systemDidLock, refreshing state
Oct 23 10:51:55 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:55 -0400 apsd[82]: Delivering systemDidLock to <APSNetworkMonitor: 0x14db95c0>
Oct 23 10:51:55 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:55 -0400 apsd[82]: <APSNetworkMonitor: 0x14db95c0> systemDidLock, refreshing state
Oct 23 10:51:55 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:55 -0400 apsd[82]: Delivering systemDidLock to <APSCourier: 0x14d74090>
Oct 23 10:51:55 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:55 -0400 apsd[82]: Delivering systemDidLock to <APSCourier: 0x14db94b0>
Oct 23 10:51:57 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:57 -0400 apsd[82]: Interface manager: WWAN radio power level notification; DCH status changed to active
Oct 23 10:51:57 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:57 -0400 apsd[82]: <APSCourier: 0x14db94b0> <PCInterfaceMonitor: 0x14d7c5f0> interface radio hotness changed to YES
Oct 23 10:51:57 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:57 -0400 apsd[82]: <APSTopicManager: 0x14db9930> isPowerEfficientToSendFilter changed to YES
Oct 23 10:51:57 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:57 -0400 apsd[82]: <APSCourier: 0x14d74090> <PCInterfaceMonitor: 0x14d7c5f0> interface radio hotness changed to YES
Oct 23 10:51:57 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:57 -0400 apsd[82]: <PCInterfaceUsabilityMonitor: 0x14d44ad0> [WWAN](pdp_ip0): isInterfaceUsable? YES reachable YES linkQuality 100 isNetworkCaptive? NO
Oct 23 10:51:57 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:57 -0400 apsd[82] com.apple.Duet.APLSScheduler: <PCPersistentTimer: 0x14dac940> calculating _earlyFireDate. powerStateDetectionSupported = YES = (detectionSupported(YES) && (wwanIsUp(YES) || ! internetReachable(YES)))
Oct 23 10:51:57 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:57 -0400 apsd[82] com.apple.Duet.APLSScheduler: <PCPersistentTimer: 0x14dac940> Device is plugged in, overriding earlyFireProportion to be 1.0
Oct 23 10:51:57 MDM-Test-Phone-2 apsd[82] <Warning>: 2014-10-23 10:51:57 -0400 apsd[82] com.apple.Duet.APLSScheduler: <PCPersistentTimer: 0x14dac940> Calculated minimum fire date [2014-10-23 16:50:34 -0400] (98.1318%) with fire date [2014-10-23 16:57:34 -0400], start date [2014-10-23 10:42:52 -0400], minimum early

So its pretty clear that on the phones that are working the "looking up connection on peer" is triggered immediately after registering for remote notifications. If someone with more expertise in debugging APNs console messages notices anything that stands out or has any suggestions on how to proceed debugging I'd love to hear from you!

A: I'm seeing the exact same problem and have a working theory that it is related to background power usage, and potentially the use of beginBackgroundTaskWithExpirationHandler. iOS potentially making decision on whether to wake up the app based on some type of power usage metric it keeps.
Related: iOS UIBackgroundMode remote-notification doesn't work on 4G
Or it is just a bug in iOS.  Definitely undocumented either way and a major pita.


text:
Q: GIT post-receive hook for more branches - workflow or timestamp problem? I have a development and production folder on the same server and 1 repo behind them to push to both folders depending on the branch that is pushed. I would like the development (test) folder to be deployed to when dev is pushed to the repo and the production folder (www) when master is pushed.
This works, but I have the problem of rewriting all files, not just those that have changed.
Example:

*

*I am on local dev branch, make change only to file index.php, commit,
push - Changes are deployed do development folder, with only
index.php changed (new file timestamp).

*Next step: git checkout master, git merge with dev branch and then
push to master - Changes are properly deployed to production folder,
but not only index.php is changed, but all files on FTP have new
timestamp.

*Next step: git checkout dev, make some changes to fileX.php, commit  and push to dev - Changes are properly deployed to dev folder, but again all files on FTP have new timestamp, not only fileX.php
Is it normal or am I doing something wrong? Maybe can you recommend a better git workflow if I have 1 local PC with git - 1 development domain and 1 production domain ?
Thanks for help
post-receive hook:
#!/bin/sh
while read oldrev newrev ref
do
  branch=`echo $ref | cut -d/ -f3`
  if [ "master" == "$branch" ]; then
    git --work-tree=/home/www/domain.com/subdomains/www --git-dir=/home/www/domain.com/subdomains/repos/myrepo.git checkout master -f
    echo 'changes pushed to production'
  else
    git --work-tree=/home/www/domain.com/subdomains/test--git-dir=/home/www/domain.com/subdomains/repos/myrepo.git checkout dev -f
    echo 'changes pushed to dev'
  fi
done

A: This post-receive hook is badly flawed.  The good news is that it's easily fixed.
The root of your particular problem is that every Git repository, including the bare one1 that is receiving the push here, starts out with one (just one) index.  The index keeps track of the (single, as in just one again) work-tree.  This is true even though the whole point of a bare repository is to have no work-tree: it still has an index.
When one uses git --work-tree=<path> with this bare repository to do a git checkout operation, that checkout operation uses the (one, single) index to keep track of what it has stored in the (temporarily added) work-tree.  That is, for the duration of the git checkout, this bare repository becomes non-bare: it has one index and one work-tree, and the work-tree is the one chosen for this one git checkout operation.
For each subsequent git --work-tree=<path> checkout operation, Git will assume that the index correctly describes the current checkout to the target work-tree.  (Git may discover, as it does its work, that the index doesn't correctly describe the target work-tree, but it starts out assuming that it does.)  The files that Git decides to update in that work-tree will be based on this assumption, with some corrections potentially, but not always, inserted as it goes.  This main assumption, that the index correctly describes the current checkout to the work-tree, holds if and only if the path argument used in the subsequent git checkout is the same as the path argument used in the previous git checkout.
But we have two different git checkout commands:
git --work-tree=/home/www/domain.com/subdomains/www ...

and:
git --work-tree=/home/www/domain.com/subdomains/test

(small aside here: something went wrong with the cut-and-paste above as the --git-dir option is fused with the --work-tree; I have made my own assumption here about fixing it).
These are two different paths.  They therefore need two different index files—or no index at all.2

1A bare repository is a Git repository where core.bare is set to true.  A bare repository has no work-tree and its Git database files are stored in the top level, rather than under a separate .git directory.
2When there is no index, as in the initial git checkout, Git will build one as needed.  This is more compute-intensive, and in a non-bare repository, where we actually use the index to build the next commit, destroying the index loses our carefully-built next commit: Git builds the new one from the current commit again so we have to start over.
The work-tree itself is not affected by this rebuilding process, but if we can afford the space for one index file per work-tree—and index files are generally pretty small—it seems likely that we should do that.  Still, it's an option, if you want it.

Fixing the problem
First, although it's not really related, let's fix the other obvious (but minor) problem:
while read oldrev newrev ref
do
  branch=`echo $ref | cut -d/ -f3`

Suppose we add a tag named master/v1.1.  This ref has, as its full spelling, the name refs/tags/master/v1.1.  Let's see what we get here:
$ ref=refs/tags/master/v1.1
$ branch=`echo $ref | cut -d/ -f3`
$ echo $branch
master

Whoops: our code will think we've updated branch master, when what we did is add the tag master/v1.1.  We probably won't use such a tag, but why not do this correctly?  Instead of using cut, let's check the whole reference:
case $ref in
refs/heads/*) branch=${ref#refs/heads/};;
*) continue;; # not a branch
esac

Trying this out with our test ref we get:
$ case $ref in
> refs/heads/*) branch=${ref#refs/heads/};;
> *) echo not a branch;;
> esac
not a branch

Replacing ref with refs/heads/master we get:
$ ref=refs/heads/master
$ case $ref in
refs/heads/*) branch=${ref#refs/heads/};;
*) echo not a branch;;
esac
$ echo $branch
master

(There's no PS2 output in this section because I used control-P to redo the previous case.)
For real correctness, we should also look at $old and $new to determine whether the ref in question is being created, updated, or deleted; but in this case we can just assume that branch names master and dev won't ever be deleted.  So our new code reads:
#!/bin/sh
while read oldrev newrev ref
do
    case $ref in
    refs/heads/*) branch=${ref#refs/heads/};;
    *) continue;; # not a branch - do not deploy
    esac

    case "$branch" in
    master) wt=/home/www/domain.com/subdomains/www loc=production;;
    dev) wt=home/www/domain.com/subdomains/test loc=dev;;
    *) continue;; # not an INTERESTING branch - do not deploy
    esac

    # It's an interesting branch; deploy it to $wt.  Use an index
    # based on the branch name.  There is no need to specify the
    # git directory, which is in $GIT_DIR right now because this is
    # a post-receive script.
    GIT_INDEX_FILE=index.$branch git --work-tree=$wt checkout $branch -f
    echo "deployed to $loc"
done

The -f option to git checkout here is somewhat dangerous: it will overwrite or remove files that got modified in the work-tree, even though we now have a proper index to keep track of which files should be in which state.  But it was there before, so I've kept it.
This post-receive script (which I should note is entirely untested: watch out for typos) still has a flaw.  Whatever branch we git checkout here, that will leave this repository set to recommend that branch to whoever clones this repository.    Fixing this requires updating HEAD:
git symbolic-ref HEAD refs/heads/master

after the git checkout step.  You have been living with this flaw all along, so maybe you don't really care about this one.