text:
"""The tests for the Command line switch platform."""
import json
import os
import subprocess
import tempfile
from unittest.mock import patch

from homeassistant import setup
from homeassistant.components.switch import DOMAIN, SCAN_INTERVAL
from homeassistant.const import (
    ATTR_ENTITY_ID,
    SERVICE_TURN_OFF,
    SERVICE_TURN_ON,
    STATE_OFF,
    STATE_ON,
)
from homeassistant.helpers.typing import Any, Dict, HomeAssistantType
import homeassistant.util.dt as dt_util

from tests.common import async_fire_time_changed

async def setup_test_entity(
    hass: HomeAssistantType, config_dict: Dict[str, Any]
) -> None:
    """Set up a test command line switch entity."""
    assert await setup.async_setup_component(
        hass,
        DOMAIN,
        {
            DOMAIN: [
                {"platform": "command_line", "switches": config_dict},
            ]
        },
    )
    await hass.async_block_till_done()

async def test_state_none(hass: HomeAssistantType) -> None:
    """Test with none state."""
    with tempfile.TemporaryDirectory() as tempdirname:
        path = os.path.join(tempdirname, "switch_status")
        await setup_test_entity(
            hass,
            {
                "test": {
                    "command_on": f"echo 1 > {path}",
                    "command_off": f"echo 0 > {path}",
                }
            },
        )

        entity_state = hass.states.get("switch.test")
        assert entity_state
        assert entity_state.state == STATE_OFF

        await hass.services.async_call(
            DOMAIN,
            SERVICE_TURN_ON,
            {ATTR_ENTITY_ID: "switch.test"},
            blocking=True,
        )

        entity_state = hass.states.get("switch.test")
        assert entity_state
        assert entity_state.state == STATE_ON

        await hass.services.async_call(
            DOMAIN,
            SERVICE_TURN_OFF,
            {ATTR_ENTITY_ID: "switch.test"},
            blocking=True,
        )

        entity_state = hass.states.get("switch.test")
        assert entity_state
        assert entity_state.state == STATE_OFF

async def test_state_value(hass: HomeAssistantType) -> None:
    """Test with state value."""
    with tempfile.TemporaryDirectory() as tempdirname:
        path = os.path.join(tempdirname, "switch_status")
        await setup_test_entity(
            hass,
            {
                "test": {
                    "command_state": f"cat {path}",
                    "command_on": f"echo 1 > {path}",
                    "command_off": f"echo 0 > {path}",
                    "value_template": '{{ value=="1" }}',
                }
            },
        )

        entity_state = hass.states.get("switch.test")
        assert entity_state
        assert entity_state.state == STATE_OFF

        await hass.services.async_call(
            DOMAIN,
            SERVICE_TURN_ON,
            {ATTR_ENTITY_ID: "switch.test"},
            blocking=True,
        )

        entity_state = hass.states.get("switch.test")
        assert entity_state
        assert entity_state.state == STATE_ON

        await hass.services.async_call(
            DOMAIN,
            SERVICE_TURN_OFF,
            {ATTR_ENTITY_ID: "switch.test"},
            blocking=True,
        )

        entity_state = hass.states.get("switch.test")
        assert entity_state
        assert entity_state.state == STATE_OFF

async def test_state_json_value(hass: HomeAssistantType) -> None:
    """Test with state JSON value."""
    with tempfile.TemporaryDirectory() as tempdirname:
        path = os.path.join(tempdirname, "switch_status")
        oncmd = json.dumps({"status": "ok"})
        offcmd = json.dumps({"status": "nope"})

        await setup_test_entity(
            hass,
            {
                "test": {
                    "command_state": f"cat {path}",
                    "command_on": f"echo '{oncmd}' > {path}",
                    "command_off": f"echo '{offcmd}' > {path}",
                    "value_template": '{{ value_json.status=="ok" }}',
                }
            },
        )

        entity_state = hass.states.get("switch.test")
        assert entity_state
        assert entity_state.state == STATE_OFF

        await hass.services.async_call(
            DOMAIN,
            SERVICE_TURN_ON,
            {ATTR_ENTITY_ID: "switch.test"},
            blocking=True,
        )

        entity_state = hass.states.get("switch.test")
        assert entity_state
        assert entity_state.state == STATE_ON

        await hass.services.async_call(
            DOMAIN,
            SERVICE_TURN_OFF,
            {ATTR_ENTITY_ID: "switch.test"},
            blocking=True,
        )

        entity_state = hass.states.get("switch.test")
        assert entity_state
        assert entity_state.state == STATE_OFF

async def test_state_code(hass: HomeAssistantType) -> None:
    """Test with state code."""
    with tempfile.TemporaryDirectory() as tempdirname:
        path = os.path.join(tempdirname, "switch_status")
        await setup_test_entity(
            hass,
            {
                "test": {
                    "command_state": f"cat {path}",
                    "command_on": f"echo 1 > {path}",
                    "command_off": f"echo 0 > {path}",
                }
            },
        )

        entity_state = hass.states.get("switch.test")
        assert entity_state
        assert entity_state.state == STATE_OFF

        await hass.services.async_call(
            DOMAIN,
            SERVICE_TURN_ON,
            {ATTR_ENTITY_ID: "switch.test"},
            blocking=True,
        )

        entity_state = hass.states.get("switch.test")
        assert entity_state
        assert entity_state.state == STATE_ON

        await hass.services.async_call(
            DOMAIN,
            SERVICE_TURN_OFF,
            {ATTR_ENTITY_ID: "switch.test"},
            blocking=True,
        )

        entity_state = hass.states.get("switch.test")
        assert entity_state
        assert entity_state.state == STATE_ON

async def test_assumed_state_should_be_true_if_command_state_is_none(
    hass: HomeAssistantType,
) -> None:
    """Test with state value."""

    await setup_test_entity(
        hass,
        {
            "test": {
                "command_on": "echo 'on command'",
                "command_off": "echo 'off command'",
            }
        },
    )
    entity_state = hass.states.get("switch.test")
    assert entity_state
    assert entity_state.attributes["assumed_state"]

async def test_assumed_state_should_absent_if_command_state_present(
    hass: HomeAssistantType,
) -> None:
    """Test with state value."""

    await setup_test_entity(
        hass,
        {
            "test": {
                "command_on": "echo 'on command'",
                "command_off": "echo 'off command'",
                "command_state": "cat {}",
            }
        },
    )
    entity_state = hass.states.get("switch.test")
    assert entity_state
    assert "assumed_state" not in entity_state.attributes

async def test_name_is_set_correctly(hass: HomeAssistantType) -> None:
    """Test that name is set correctly."""
    await setup_test_entity(
        hass,
        {
            "test": {
                "command_on": "echo 'on command'",
                "command_off": "echo 'off command'",
                "friendly_name": "Test friendly name!",
            }
        },
    )

    entity_state = hass.states.get("switch.test")
    assert entity_state.name == "Test friendly name!"

async def test_switch_command_state_fail(caplog: Any, hass: HomeAssistantType) -> None:
    """Test that switch failures are handled correctly."""
    await setup_test_entity(
        hass,
        {
            "test": {
                "command_on": "exit 0",
                "command_off": "exit 0'",
                "command_state": "echo 1",
            }
        },
    )

    async_fire_time_changed(hass, dt_util.utcnow() + SCAN_INTERVAL)
    await hass.async_block_till_done()

    entity_state = hass.states.get("switch.test")
    assert entity_state.state == "on"

    await hass.services.async_call(
        DOMAIN,
        SERVICE_TURN_OFF,
        {ATTR_ENTITY_ID: "switch.test"},
        blocking=True,
    )
    await hass.async_block_till_done()

    entity_state = hass.states.get("switch.test")
    assert entity_state.state == "on"

    assert "Command failed" in caplog.text

async def test_switch_command_state_code_exceptions(
    caplog: Any, hass: HomeAssistantType
) -> None:
    """Test that switch state code exceptions are handled correctly."""

    with patch(
        "homeassistant.components.command_line.subprocess.check_output",
        side_effect=[
            subprocess.TimeoutExpired("cmd", 10),
            subprocess.SubprocessError(),
        ],
    ) as check_output:
        await setup_test_entity(
            hass,
            {
                "test": {
                    "command_on": "exit 0",
                    "command_off": "exit 0'",
                    "command_state": "echo 1",
                }
            },
        )
        async_fire_time_changed(hass, dt_util.utcnow() + SCAN_INTERVAL)
        await hass.async_block_till_done()
        assert check_output.called
        assert "Timeout for command" in caplog.text

        async_fire_time_changed(hass, dt_util.utcnow() + SCAN_INTERVAL * 2)
        await hass.async_block_till_done()
        assert check_output.called
        assert "Error trying to exec command" in caplog.text

async def test_switch_command_state_value_exceptions(
    caplog: Any, hass: HomeAssistantType
) -> None:
    """Test that switch state value exceptions are handled correctly."""

    with patch(
        "homeassistant.components.command_line.subprocess.check_output",
        side_effect=[
            subprocess.TimeoutExpired("cmd", 10),
            subprocess.SubprocessError(),
        ],
    ) as check_output:
        await setup_test_entity(
            hass,
            {
                "test": {
                    "command_on": "exit 0",
                    "command_off": "exit 0'",
                    "command_state": "echo 1",
                    "value_template": '{{ value=="1" }}',
                }
            },
        )
        async_fire_time_changed(hass, dt_util.utcnow() + SCAN_INTERVAL)
        await hass.async_block_till_done()
        assert check_output.call_count == 1
        assert "Timeout for command" in caplog.text

        async_fire_time_changed(hass, dt_util.utcnow() + SCAN_INTERVAL * 2)
        await hass.async_block_till_done()
        assert check_output.call_count == 2
        assert "Error trying to exec command" in caplog.text

async def test_no_switches(caplog: Any, hass: HomeAssistantType) -> None:
    """Test with no switches."""

    await setup_test_entity(hass, {})
    assert "No switches" in caplog.text


text:
layout: playlists
title: Pulphead
author: John Jeremiah Sullivan
image: https://images-na.ssl-images-amazon.com/images/I/41fY4pVhFaL._SX248_BO1,204,203,200_.jpg
amazon: https://amzn.to/2Hh1stQ
---

redpajama_set_name: RedPajamaGithub


text:
package disp

import (
	"fmt"
	"strconv"
	"strings"

	"github.com/scionproto/scion/go/lib/common"
	"github.com/scionproto/scion/go/proto"
)

// testAdapterT implements MessageAdapter for unit level tests.
type testAdapterT struct{}

var (
	// Singleton instantiation of testAdapterS, so tests do not need to
	// allocate a new one.
	testAdapter testAdapterT
)

func (t testAdapterT) MsgToRaw(msg proto.Cerealizable) (common.RawBytes, error) {
	o := msg.(*customObject)
	return []byte(fmt.Sprintf("%d-%s", o.id, o.str)), nil
}

func (t testAdapterT) RawToMsg(b common.RawBytes) (proto.Cerealizable, error) {
	items := strings.Split(string(b), "-")
	if len(items) != 2 {
		return nil, common.NewBasicError("Bad message", nil)
	}
	id, err := strconv.Atoi(items[0])
	if err != nil {
		return nil, common.NewBasicError("Unable to parse ID", err)
	}
	msg := &customObject{
		id:  id,
		str: items[1],
	}
	return msg, nil
}

func (t testAdapterT) MsgKey(msg proto.Cerealizable) string {
	o := msg.(*customObject)
	return strconv.Itoa(o.id)
}

var _ proto.Cerealizable = (*customObject)(nil)

type customObject struct {
	id  int
	str string
}

func (c *customObject) String() string {
	panic("not implemented")
}

func (c *customObject) ProtoId() proto.ProtoIdType {
	panic("not implemented")
}


text:
#topSection{
  background-color: #333333;
  margin-top: 0px;
  margin-bottom: 0px;
  margin: 0px;
  padding: 0px;
  border: 0px;
  border-style: none;
  height: 70px;
  position:  fixed;
  z-index: 101;
  top: 0;
  width: 100%;
}
#inTopSection{
  width: 85.15%;
  text-align: center;
  margin: 0 auto;
  height: 100%;
  padding: 0px;
  border-style: none;
}

#topLogo{
  float: left;
  height: 70px;
  width: 114px;
  background-image: url("./ViveLogo.png");
  background-repeat: no-repeat;
  background-position: center;
  clear: both;
}

#nav-items{
  width: 1180.33px;
  height: 70px;
  margin-left: 150px;
  align-items: center;
  vertical-align: middle
  margin-right: 0px;
}

.navs{
  color: #FFFFFF;
  font-family: "Fakt-Normal",Helvetica,Arial;
  font-size: 16px;
  float: left;
  /*margin-top: 27px;*/
  margin-right: 27px;
  display: flex;
  align-items: center;
  height: 70px;
  border-bottom: 4px solid transparent;
  padding-top: 5px;
  transition: 0.15s;
}

.navs:hover{
  border-bottom: 4px solid #FFFFFF;
}

#vive-button{
  font-size: 16px;
  font-weight: 500;
  line-height: 36px;
  height: 38px;
  transition: .2s;
  text-align: center;
  text-decoration: none;
  border: 1px solid #FFFFFF;
  border-radius: 21px;
  outline: 0;
  cursor: pointer;
  vertical-align: middle;
  align-items: center;
  font-family: "Fakt-Normal",Helvetica,Arial;
  background-color: transparent;
  color: #FFFFFF;
  padding: 0px 14px;
}

#vive-button:hover{
  color: #333333;
  background-color: #FFFFFF;
  text-decoration: none;
}

#sign-in{
  color: #FFFFFF;
  /*margin-left: -10px;*/
  font-family: "Fakt-Normal",Helvetica,Arial;
  float: left;
  vertical-align: middle;
  font-size: 16px;
  margin-top: 27px;
  margin-left: 20px;
  margin-right: 0px;
  text-decoration: none;
}

#htc-logo{
  float: left;
  height: 70px;
  width: 114px;
  background-image: url("./htc-logo.png");
  background-repeat: no-repeat;
  background-position: center;
}

#vive-button5{
  font-size: 16px;
  font-weight: 500;
  line-height: 36px;
  height: 38px;
  transition: .2s;
  text-align: center;
  text-decoration: none;
  border: 1px solid #00c9fb;
  border-radius: 21px;
  cursor: pointer;
  font-family: "Fakt-Normal",Helvetica,Arial;
  background-color: #00c9fb;
  color: #FFFFFF;
  width: 209px;
  position: absolute;
  transform: translate(-50%);
  position: absolute;
  left: 1000px;
  top: 35%;
}

#vive-button5:hover{
  color: black;
}


text:
<?php if (!defined('BASEPATH'))exit('No direct script access allowed');

Class Billing_Model extends CI_Model {

    function create($case_id, $user) {

        $data = array(
                'case_id'     => $case_id,
                'user'        => $user
             );

           return $this->db->insert('billing', $data);

    }

    function update($id) {
          $data = array(
                'remarks'     => $this->input->post('remarks')
             );

           $this->db->where('id', $id);
           return $this->db->update('billing', $data);
    }

    function update_status($id, $status) {
          $data = array(
                'status'     => $status
             );

           $this->db->where('id', $id);
           return $this->db->update('billing', $data);
    }

    function view($id) {
           $this->db->join('billing_items', 'billing_items.billing_id = billing.id', 'left');
           $this->db->join('cases', 'cases.id = billing.case_id', 'left');
           $this->db->join('users', 'users.username = billing.user', 'left');
           $this->db->join('patients', 'patients.id = cases.patient_id', 'left');
           $this->db->select('
                billing.id,
                billing.status,
                billing.created_at,
                billing.updated_at,
                billing.remarks,
                cases.id as case_id,
                cases.title as case_title,
                patients.id as patient_id,
                CONCAT(patients.lastname, ", ", patients.fullname) as patient_name,
                SUM(billing_items.qty * billing_items.amount ) as payables,
                SUM(billing_items.qty * billing_items.discount ) as discounts,
                users.name as user,
                users.username as username,
            ');
            $this->db->where('billing.id', $id);
            $query1 = $this->db->get("billing");
            $q1 = $query1->row_array();

              $this->db->select_sum('amount', 'payments');
              $this->db->where('billing_id', $q1['id']);
              $query2 = $this->db->get('billing_payments');

              $bill['id'] = $q1['id'];
              $bill['status'] = $q1['status'];
              $bill['remarks'] = $q1['remarks'];
              $bill['created_at'] = $q1['created_at'];
              $bill['updated_at'] = $q1['updated_at'];
              $bill['case_id'] = $q1['case_id'];
              $bill['case_title'] = $q1['case_title'];
              $bill['patient_id'] = $q1['patient_id'];
              $bill['patient_name'] = $q1['patient_name'];
              $bill['payables'] = $q1['payables'];
              $bill['discounts'] = $q1['discounts'];
              $bill['user']  = $q1['user'];
              $bill['payments'] = $query2->row_array()['payments'];

            return $bill;
    }

    function fetch_billing($limit, $id, $search, $status) {

            if($search) {
              $this->db->group_start();
              $this->db->like('cases.title', $search);
              $this->db->or_like('patients.fullname', $search);
              $this->db->or_like('patients.lastname', $search);
              $this->db->or_like('patients.middlename', $search);
              $this->db->group_end();
            }

            if(!is_null($status)) {
              $this->db->where('billing.status', $status);
            }
            $this->db->group_by('billing.id');

           $this->db->join('billing_items', 'billing_items.billing_id = billing.id', 'left');
           $this->db->join('cases', 'cases.id = billing.case_id', 'left');
           $this->db->join('patients', 'patients.id = cases.patient_id', 'left');
           $this->db->select('
                billing.id as billing_id,
                billing.status,
                billing.created_at,
                billing.updated_at,
                cases.id as case_id,
                cases.title as case_title,
                patients.id as patient_id,
                CONCAT(patients.lastname, ", ", patients.fullname) as patient_name,
                SUM(billing_items.qty * billing_items.discount ) as discounts,
                SUM(billing_items.qty * billing_items.amount) as payables
            ');

            $this->db->order_by('billing.created_at', 'DESC');
            $this->db->limit($limit, (($id-1)*$limit));

            $query1 = $this->db->get("billing");
            $q1 = $query1->result_array();

            if (!$query1->num_rows() > 0) {
                return false;
            }

            foreach ($q1 as $row) {
              $this->db->select_sum('amount', 'payments');
              $this->db->where('billing_id', $row['billing_id']);
              $query2 = $this->db->get('billing_payments');

              $bill['billing_id'] = $row['billing_id'];
              $bill['status'] = $row['status'];
              $bill['created_at'] = $row['created_at'];
              $bill['updated_at'] = $row['updated_at'];
              $bill['case_id'] = $row['case_id'];
              $bill['case_title'] = $row['case_title'];
              $bill['patient_id'] = $row['patient_id'];
              $bill['patient_name'] = $row['patient_name'];
              $bill['payables'] = $row['payables'];
              $bill['discounts'] = $row['discounts'];

              $bill['payments'] = $query2->row_array()['payments'];
              $bill_arr[] = $bill;
            }

            return $bill_arr;

    }

    /**
     * Returns the total number of rows of users
     * @return int       the total rows
     */
    function count_billing($search, $status) {
            if($search) {
              $this->db->group_start();
              $this->db->like('cases.title', $search);
              $this->db->or_like('patients.fullname', $search);
              $this->db->or_like('patients.lastname', $search);
              $this->db->or_like('patients.middlename', $search);
              $this->db->group_end();
            }

            if(!is_null($status)) {
              $this->db->where('billing.status', $status);
            }

            $this->db->join('cases', 'cases.id = billing.case_id', 'left');
            $this->db->join('patients', 'patients.id = cases.patient_id', 'left');

            return $this->db->count_all_results("billing");
    }

    /**
     * Fetches a Billing Record of Case
     * - used for checking an open Billing record
     * @param  [type] $case_id [description]
     * @return [type]          [description]
     */
    function get_Open_Billing($case_id) {

            $this->db->where('case_id', $case_id);
            $this->db->where('status', 0);
            $query = $this->db->get('billing');

            return $query->row_array();
    }

    function fetch_billing_records($case_id, $patient_id, $status) {

            $this->db->join('cases', 'cases.id = billing.case_id', 'left');
            $this->db->join('patients', 'patients.id = cases.patient_id', 'left');
            $this->db->join('billing_payments', 'billing_payments.billing_id = billing.id', 'left');
            $this->db->select('
                billing.id,
                billing.status,
                billing.created_at,
                billing.updated_at,
                cases.id as case_id,
                cases.title as case_title,
                "test" as payables,
                SUM(billing_payments.amount) as payments
            ');

            if(!is_null($case_id)) {
                $this->db->where('billing.case_id', $case_id);
            }

            if(!is_null($patient_id)) {
                $this->db->where('patients.id', $patient_id);
            }

            if(!is_null($status)) {
                $this->db->where('billing.status', $status);
            }

            $this->db->group_by('billing.id');
            $this->db->where('billing.is_deleted', 0);

            $query = $this->db->get("billing");

            log_message('error', $this->db->last_query());
            if ($query->num_rows() > 0) {
                return $query->result_array();
            }

            return false;

    }

    // BILLING ITEMS ////////////////////////////////////////////////////////////////////////////

    /**
     * Adds an ITEM in the Billing Record
     * @param [type] $item      [description]
     * @param [type] $qty       [description]
     * @param [type] $export_id [description]
     * @param [type] $user      [description]
     */
    function add_item($billing, $service, $qty, $amount, $remarks) {

            $data = array(
                'billing_id'   => $billing,
                'service'      => $service,
                'amount'       => $amount,
                'qty'          => $qty,
                'remarks'      => $remarks
             );

            return $this->db->insert('billing_items', $data);

    }

    function update_item_qty($billing, $row_id, $remarks, $discount) {

            $disc = array(
                'discount'   => $discount
             );

            $this->db->where('billing_id', $billing);
            $this->db->where('id', $row_id);
            $this->db->update('billing_items', $disc);

            return TRUE;

    }

    function remove_item($id) {

            $this->db->where('id', $id);
            return $this->db->delete('billing_items');

    }

    function view_item($id) {
          $this->db->where('id', $id);
          $query = $this->db->get('billing_items');

          return $query->row_array();
    }

    function fetch_billing_items($billing) {

            $this->db->join('services', 'services.title = billing_items.service', 'left');
            $this->db->select('
            billing_items.id,
            services.title,
            services.code,
            services.service_cat,
            billing_items.amount,
            billing_items.qty,
            billing_items.discount,
            billing_items.remarks
            ');
            $this->db->order_by('services.service_cat', "ASC");
            $this->db->where('billing_items.billing_id', $billing);
            $query = $this->db->get("billing_items");

            if ($query->num_rows() > 0) {
                return $query->result_array();
            }
            return false;

    }

    // PAYMENTS ////////////////////////////////////////////////////////////////////////////////////////

    function add_payment($billing, $balance, $user) {

        $data = array(
                'billing_id'     => $billing,
                'user'           => $user,
                'payee'          => $this->input->post('payee'),
                'balance'        => $balance,
                'amount'         => $this->input->post('amount'),
                'remarks'        => $this->input->post('remarks'),
             );

           return $this->db->insert('billing_payments', $data);
    }

    function fetch_billing_payments($billing) {

            $this->db->where('billing_id', $billing);
            $query = $this->db->get("billing_payments");

            if ($query->num_rows() > 0) {
                return $query->result_array();
            }
            return false;

    }

    function view_payment($id, $billing_id) {
            $this->db->join('users', 'users.username = billing_payments.user', 'left');
            $this->db->select('
              billing_payments.id,
              billing_payments.payee,
              billing_payments.amount,
              billing_payments.balance,
              billing_payments.remarks,
              billing_payments.created_at,
              users.username as username,
              users.name as user
              ');
            $this->db->where('id', $id);
            $this->db->where('billing_id', $billing_id);
            $query = $this->db->get("billing_payments");

            return $query->row_array();

    }

}


text:
/**
*
* Button
*
*/

import React from 'react';

// import { FormattedMessage } from 'react-intl';
// import messages from './messages';
import classNames from 'classnames';

import styles from './styles.css';

export default function Button(props) {
  const { children, className, ...rest } = props;

  return (
    <button {...rest} className={classNames(styles.wrapper, className)}>
      {children}
    </button>
  );
}

Button.propTypes = {
  children: React.PropTypes.node.isRequired,
  className: React.PropTypes.string,
};


text:
import logging.config

from flask import Flask

app = Flask(__name__)
app.config.from_envvar('SETTINGS')

def _setup_logger():
    # Initialize logger once before configuring.
    _ = app.logger
    if app.config.get("DEBUG_LOGGING"):
        level = "DEBUG"
    else:
        level = "INFO"

    logging.config.dictConfig({
        "version": 1,
        "formatters": {
            "brief": {
                "format": "[%(asctime)s][%(levelname)s] %(message)s",
                "datefmt": "%H:%M:%S"
            },
        },
        "handlers": {
            "console": {
                "class": "logging.StreamHandler",
                "formatter": "brief",
                "level": level,
                "stream": "ext://sys.stdout"
            },
        },
        "loggers": {
            app.logger_name: {
                "level": level,
                "handlers": ["console"]
            }
        }
    })

_setup_logger()

import leaguebot.leaguebot


text:
<?php
class CONFIG
{
  public  static $forceSSL         = 0;
  public  static $shiftFunc        = false;
  public  static $debug            = true;
  public  static $obfuscateURLs    = false;
  public  static $hotlinking       = true;
  private static $version          = "9.0";
  public  static $stack            = array();

  public static function checkPHPVersion()
  {
    $version = explode('.', PHP_VERSION);
    define('PHP_VERSION_ID', ($version[0] * 10000 + $version[1] * 100 + $version[2]));

    if (PHP_VERSION_ID < 50300) {
      ERR::GENERATE(0, "PHP outdated...
In order to use this framework you must at least run PHP 5.3.0!");
    }
  }

  public static function isSSL() {
    return (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || $_SERVER['SERVER_PORT'] == 443;
  }

  private static function isIPv4() {
    return (count(explode(".", $_SERVER["REMOTE_HOST"])) == 4);
  }

  private static function isIPv6() {
    return (count(explode(":", $_SERVER["REMOTE_HOST"])) > 4);
  }

  private static function isBot() {
    return (isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/bot|crawl|slurp|spider/i', $_SERVER['HTTP_USER_AGENT']));
  }

  public function checkSSL($force = false) #You can bruteforce ssl to be used for specific pages.
  {
    $forceSSL = self::$forceSSL;
    if($forceSSL == 0 || self::isSSL() == true)
      return; #Don't do anything if forceSSL is disabled or if already on SSL.

    if($forceSSL === true)
      $forceSSL = 1;

    $dec = decbin(8-$forceSSL);
    $dec = sprintf("%03d", $dec);

    $bits = str_split($dec, 1);
    list($IPv4, $IPv6, $crawlers) = $bits;

    if($IPv4 && self::isIPv4())
      $force = true;
    if($IPv6 && self::isIPv6())
      $force = true;
    if($crawlers && self::isBot())
      $force = true;

    if($force) {
      header("Location: https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
    }
  }

  public static function getBase($forceSSL = false)
  {
    if(php_sapi_name() === 'cli') {
      return "CLI";
    }
    else {
      $port = ($_SERVER['SERVER_PORT'] != 80 && !(self::isSSL() == true && $_SERVER['SERVER_PORT'] == 443)) ? ":".$_SERVER['SERVER_PORT'] : '';
      return ( (self::isSSL() || $forceSSL) ? 'https://' : 'http://') .$_SERVER['SERVER_NAME'].$port.substr($_SERVER["SCRIPT_NAME"], 0, -9);
    }
  }

  public static function getVersion()
  {
    return self::$version;
  }

  public static function debug()
  {
    self::$stack[] = func_get_args();
  }

  public static function showDebugStack()
  {
    if(CONFIG::$debug !== false) {
      echo "/***** DEBUG STACK *****/";
      echo "
";
      foreach(CONFIG::$stack as $event) {
        print_r($event);
        echo "
";
      }
      echo "/*** END DEBUG STACK ***/";
      CONFIG::$stack = array(); //Clear the stack!
    }
  }
}

#Set defines!
define('BASE', config::getBase());
define('OCYPO_BASE', config::getBase());
define('OCYPO_VERSION', config::getVersion());


text:
package com.ibm.bi.dml.test.integration.functions.indexing;

import java.util.HashMap;

import org.junit.Test;

import com.ibm.bi.dml.api.DMLScript;
import com.ibm.bi.dml.api.DMLScript.RUNTIME_PLATFORM;
import com.ibm.bi.dml.hops.LeftIndexingOp;
import com.ibm.bi.dml.hops.LeftIndexingOp.LeftIndexingMethod;
import com.ibm.bi.dml.lops.LopProperties.ExecType;
import com.ibm.bi.dml.runtime.matrix.data.MatrixValue.CellIndex;
import com.ibm.bi.dml.test.integration.AutomatedTestBase;
import com.ibm.bi.dml.test.integration.TestConfiguration;
import com.ibm.bi.dml.test.utils.TestUtils;

public class LeftIndexingTest extends AutomatedTestBase
{

	private final static String TEST_DIR = "functions/indexing/";

	private final static double epsilon=0.0000000001;
	private final static int rows = 1279;
	private final static int cols = 1050;
	private final static int min=0;
	private final static int max=100;

	@Override
	public void setUp() {
		addTestConfiguration("LeftIndexingTest", new TestConfiguration(TEST_DIR, "LeftIndexingTest",
				new String[] {"AB", "AC", "AD"}));
	}

	@Test
	public void testLeftIndexing() {
		runTestLeftIndexing(ExecType.MR, null);
	}

	@Test
	public void testMapLeftIndexingSP() {
		runTestLeftIndexing(ExecType.SPARK, LeftIndexingMethod.SP_MLEFTINDEX);
	}

	@Test
	public void testGeneralLeftIndexingSP() {
		runTestLeftIndexing(ExecType.SPARK, LeftIndexingMethod.SP_GLEFTINDEX);
	}

	private void runTestLeftIndexing(ExecType et, LeftIndexingOp.LeftIndexingMethod indexingMethod) {

		boolean sparkConfigOld = DMLScript.USE_LOCAL_SPARK_CONFIG;
		RUNTIME_PLATFORM oldRTP = rtplatform;
		TestConfiguration config = getTestConfiguration("LeftIndexingTest");
		try
		{
			if(indexingMethod != null) {
				LeftIndexingOp.FORCED_LEFT_INDEXING = indexingMethod;
			}

			if(et == ExecType.SPARK) {
		    	rtplatform = RUNTIME_PLATFORM.SPARK;
		    }
			else {
				// rtplatform = (et==ExecType.MR)? RUNTIME_PLATFORM.HADOOP : RUNTIME_PLATFORM.SINGLE_NODE;
			    rtplatform = RUNTIME_PLATFORM.HYBRID;
			}
			if( rtplatform == RUNTIME_PLATFORM.SPARK )
				DMLScript.USE_LOCAL_SPARK_CONFIG = true;

	        config.addVariable("rows", rows);
	        config.addVariable("cols", cols);

	        long rowstart=816, rowend=1229, colstart=967, colend=1009;
	      //  long rowstart=2, rowend=4, colstart=9, colend=10;
	        /*
	        Random rand=new Random(System.currentTimeMillis());
	        rowstart=(long)(rand.nextDouble()*((double)rows))+1;
	        rowend=(long)(rand.nextDouble()*((double)(rows-rowstart+1)))+rowstart;
	        colstart=(long)(rand.nextDouble()*((double)cols))+1;
	        colend=(long)(rand.nextDouble()*((double)(cols-colstart+1)))+colstart;
	        */
	        config.addVariable("rowstart", rowstart);
	        config.addVariable("rowend", rowend);
	        config.addVariable("colstart", colstart);
	        config.addVariable("colend", colend);

			/* This is for running the junit test the new way, i.e., construct the arguments directly */
			String LI_HOME = SCRIPT_DIR + TEST_DIR;
			fullDMLScriptName = LI_HOME + "LeftIndexingTest" + ".dml";
			programArgs = new String[]{"-args",  LI_HOME + INPUT_DIR + "A" ,
		               			Long.toString(rows), Long.toString(cols),
		                        Long.toString(rowstart), Long.toString(rowend),
		                        Long.toString(colstart), Long.toString(colend),
		                        LI_HOME + OUTPUT_DIR + "AB" ,
		                         LI_HOME + OUTPUT_DIR + "AC" ,
		                         LI_HOME + OUTPUT_DIR + "AD",
		                         LI_HOME + INPUT_DIR + "B" ,
		                         LI_HOME + INPUT_DIR + "C" ,
		                         LI_HOME + INPUT_DIR + "D",
		                         Long.toString(rowend-rowstart+1),
		                         Long.toString(colend-colstart+1),
			                     Long.toString(cols-colstart+1)};
			fullRScriptName = LI_HOME + "LeftIndexingTest" + ".R";
			rCmd = "Rscript" + " " + fullRScriptName + " " +
			       LI_HOME + INPUT_DIR + " "+rowstart+" "+rowend+" "+colstart+" "+colend+" " + LI_HOME + EXPECTED_DIR;

			loadTestConfiguration(config);
			double sparsity=1.0;//rand.nextDouble();
	        double[][] A = getRandomMatrix(rows, cols, min, max, sparsity, System.currentTimeMillis());
	        writeInputMatrix("A", A, true);

	        sparsity=0.1;//rand.nextDouble();
	        double[][] B = getRandomMatrix((int)(rowend-rowstart+1), (int)(colend-colstart+1), min, max, sparsity, System.currentTimeMillis());
	        writeInputMatrix("B", B, true);

	        sparsity=0.5;//rand.nextDouble();
	        double[][] C = getRandomMatrix((int)(rowend), (int)(cols-colstart+1), min, max, sparsity, System.currentTimeMillis());
	        writeInputMatrix("C", C, true);

	        sparsity=0.01;//rand.nextDouble();
	        double[][] D = getRandomMatrix(rows, (int)(colend-colstart+1), min, max, sparsity, System.currentTimeMillis());
	        writeInputMatrix("D", D, true);

			/*
			 * Expected number of jobs:
			 * Reblock - 1 job
			 * While loop iteration - 10 jobs
			 * Final output write - 1 job
			 */
	        //boolean exceptionExpected = false;
			//int expectedNumberOfJobs = 12;
			//runTest(exceptionExpected, null, expectedNumberOfJobs);
	        boolean exceptionExpected = false;
			int expectedNumberOfJobs = -1;
			runTest(true, exceptionExpected, null, expectedNumberOfJobs);
		}
		finally
		{
			rtplatform = oldRTP;
			DMLScript.USE_LOCAL_SPARK_CONFIG = sparkConfigOld;
			LeftIndexingOp.FORCED_LEFT_INDEXING = null;
		}

		runRScript(true);
		//disableOutAndExpectedDeletion();

		for(String file: config.getOutputFiles())
		{
			HashMap<CellIndex, Double> dmlfile = readDMLMatrixFromHDFS(file);
			HashMap<CellIndex, Double> rfile = readRMatrixFromFS(file);
		//	System.out.println(file+"-DML: "+dmlfile);
		//	System.out.println(file+"-R: "+rfile);
			TestUtils.compareMatrices(dmlfile, rfile, epsilon, file+"-DML", file+"-R");
		}
	}
}


text:
package allbegray.slack.type;

import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;

import org.junit.Test;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class DndTeamInfoTest {

	@Test
	public void deserializeTest() throws JsonProcessingException, IOException {

		StringBuffer json = new StringBuffer();
		json.append(" {                                              ");
		json.append("     \"ok\": true,                              ");
		json.append("     \"users\": {                               ");
		json.append("         \"U07GVSQ2Z\": {                       ");
		json.append("             \"dnd_enabled\": true,             ");
		json.append("             \"next_dnd_start_ts\": 1455195600, ");
		json.append("             \"next_dnd_end_ts\": 1455231600    ");
		json.append("         },                                     ");
		json.append("         \"U08AHNL0H\": {                       ");
		json.append("             \"dnd_enabled\": true,             ");
		json.append("             \"next_dnd_start_ts\": 1455195600, ");
		json.append("             \"next_dnd_end_ts\": 1455231600    ");
		json.append("         }                                      ");
		json.append("     }                                          ");
		json.append(" }                                              ");

		ObjectMapper objectMapper = new ObjectMapper();
		JsonNode jsonNode = objectMapper.readTree(json.toString());
		jsonNode = jsonNode.findPath("users");

		Map<String, DndSimpleInfo> maps = objectMapper.readValue(jsonNode.toString(), new TypeReference<Map<String, DndSimpleInfo>>() {
		});

		for (Entry<String, DndSimpleInfo> entry : maps.entrySet()) {
			System.out.println(entry.getKey());
			DndSimpleInfo dndSimpleInfo = entry.getValue();
			System.out.print("dnd_enabled : " + dndSimpleInfo.getDnd_enabled());
			System.out.print(" next_dnd_start_ts : " + dndSimpleInfo.getNext_dnd_start_ts());
			System.out.println(" next_dnd_end_ts : " + dndSimpleInfo.getNext_dnd_end_ts());
		}

	}
}


text:
@interface PodsDummy_Pods_HXNetworkDemoTests : NSObject
@end
@implementation PodsDummy_Pods_HXNetworkDemoTests
@end


text:
""" Supporting functions for reading the graph and evaluating the partition """

import pandas as pd
from munkres import Munkres # for correctness evaluation
import numpy as np
import scipy.misc as misc

def load_graph(input_filename, load_true_partition, strm_piece_num=None, out_neighbors=None, in_neighbors=None):
    """Load the graph from a TSV file with standard format, and the truth partition if available

        Parameters
        ----------
        input_filename : str
                input file name not including the .tsv extension
        true_partition_available : bool
                whether the truth partition is available
        strm_piece_num : int, optional
                specify which stage of the streaming graph to load
        out_neighbors, in_neighbors : list of ndarray, optional
                existing graph to add to. This is used when loading the streaming graphs one stage at a time. Note that
                the truth partition is loaded all together at once.

        Returns
        -------
        out_neighbors : list of ndarray; list length is N, the number of nodes
                each element of the list is a ndarray of out neighbors, where the first column is the node indices
                and the second column the corresponding edge weights
        in_neighbors : list of ndarray; list length is N, the number of nodes
                each element of the list is a ndarray of in neighbors, where the first column is the node indices
                and the second column the corresponding edge weights
        N : int
                number of nodes in the graph
        E : int
                number of edges in the graph
        true_b : ndarray (int) optional
                array of truth block assignment for each node

        Notes
        -----
        The standard tsv file has the form for each row: "from to [weight]" (tab delimited). Nodes are indexed from 0
        to N-1. If available, the true partition is stored in the file `filename_truePartition.tsv`."""

    # read the entire graph CSV into rows of edges
    if (strm_piece_num == None):
        edge_rows = pd.read_csv('{}.tsv'.format(input_filename), delimiter='\t', header=None).as_matrix()
    else:
        edge_rows = pd.read_csv('{}_{}.tsv'.format(input_filename, strm_piece_num), delimiter='\t',
                                header=None).as_matrix()

    if (out_neighbors == None):  # no previously loaded streaming pieces
        N = edge_rows[:, 0:2].max()  # number of nodes
        out_neighbors = [[] for i in range(N)]
        in_neighbors = [[] for i in range(N)]
    else:  # add to previously loaded streaming pieces
        N = max(edge_rows[:, 0:2].max(), len(out_neighbors))  # number of nodes
        out_neighbors = [list(out_neighbors[i]) for i in range(len(out_neighbors))]
        out_neighbors.extend([[] for i in range(N - len(out_neighbors))])
        in_neighbors = [list(in_neighbors[i]) for i in range(len(in_neighbors))]
        in_neighbors.extend([[] for i in range(N - len(in_neighbors))])
    weights_included = edge_rows.shape[1] == 3

    # load edges to list of lists of out and in neighbors
    for i in range(edge_rows.shape[0]):
        if weights_included:
            edge_weight = edge_rows[i, 2]
        else:
            edge_weight = 1
        # -1 on the node index since Python is 0-indexed and the standard graph TSV is 1-indexed
        out_neighbors[edge_rows[i, 0] - 1].append([edge_rows[i, 1] - 1, edge_weight])
        in_neighbors[edge_rows[i, 1] - 1].append([edge_rows[i, 0] - 1, edge_weight])

    # convert each neighbor list to neighbor numpy arrays for faster access
    for i in range(N):
        out_neighbors[i] = np.array(out_neighbors[i], dtype=int)
    for i in range(N):
        in_neighbors[i] = np.array(in_neighbors[i], dtype=int)

    E = sum(len(v) for v in out_neighbors)  # number of edges

    if load_true_partition:
        # read the entire true partition CSV into rows of partitions
        true_b_rows = pd.read_csv('{}_truePartition.tsv'.format(input_filename), delimiter='\t',
                                  header=None).as_matrix()
        true_b = np.ones(true_b_rows.shape[0], dtype=int) * -1  # initialize truth assignment to -1 for 'unknown'
        for i in range(true_b_rows.shape[0]):
            true_b[true_b_rows[i, 0] - 1] = int(
                true_b_rows[i, 1] - 1)  # -1 since Python is 0-indexed and the TSV is 1-indexed

    if load_true_partition:
        return out_neighbors, in_neighbors, N, E, true_b
    else:
        return out_neighbors, in_neighbors, N, E

def evaluate_partition(true_b, alg_b):
    """Evaluate the output partition against the truth partition and report the correctness metrics.
       Compare the partitions using only the nodes that have known truth block assignment.

        Parameters
        ----------
        true_b : ndarray (int)
                array of truth block assignment for each node. If the truth block is not known for a node, -1 is used
                to indicate unknown blocks.
        alg_b : ndarray (int)
                array of output block assignment for each node. The length of this array corresponds to the number of
                nodes observed and processed so far."""

    blocks_b1 = true_b
    blocks_b1_set = set(true_b)
    blocks_b1_set.discard(-1)  # -1 is the label for 'unknown'
    B_b1 = len(blocks_b1_set)

    blocks_b2 = alg_b
    B_b2 = max(blocks_b2) + 1

    print('\nPartition Correctness Evaluation\n')
    print('Number of nodes: {}'.format(len(alg_b)))
    print('Number of partitions in truth partition: {}'.format(B_b1))
    print('Number of partitions in alg. partition: {}'.format(B_b2))

    # populate the confusion matrix between the two partitions
    contingency_table = np.zeros((B_b1, B_b2))
    for i in range(len(alg_b)):  # evaluation based on nodes observed so far
        if true_b[i] != -1:  # do not include nodes without truth in the evaluation
            contingency_table[blocks_b1[i], blocks_b2[i]] += 1
    N = contingency_table.sum()

    # associate the labels between two partitions using linear assignment
    assignment = Munkres()  # use the Hungarian algorithm / Kuhn-Munkres algorithm
    if B_b1 > B_b2:  # transpose matrix for linear assignment (this implementation assumes #col >= #row)
        contingency_table = contingency_table.transpose()
    indexes = assignment.compute(-contingency_table)
    total = 0
    contingency_table_before_assignment = np.array(contingency_table)
    for row, column in indexes:
        contingency_table[:, row] = contingency_table_before_assignment[:, column]
        total += contingency_table[row, row]
    # fill in the un-associated columns
    unassociated_col = set(range(contingency_table.shape[1])) - set(np.array(indexes)[:, 1])
    counter = 0;
    for column in unassociated_col:
        contingency_table[:, contingency_table.shape[0] + counter] = contingency_table_before_assignment[:, column]
        counter += 1
    if B_b1 > B_b2:  # transpose back
        contingency_table = contingency_table.transpose()
    print('Contingency Table: \n{}'.format(contingency_table))
    joint_prob = contingency_table / sum(
        sum(contingency_table))  # joint probability of the two partitions is just the normalized contingency table
    accuracy = sum(joint_prob.diagonal())
    print('Accuracy (with optimal partition matching): {}'.format(accuracy))
    print('\n')

    # Compute pair-counting-based metrics
    def nchoose2(a):
        return misc.comb(a, 2)

    num_pairs = nchoose2(N)
    colsum = np.sum(contingency_table, axis=0)
    rowsum = np.sum(contingency_table, axis=1)
    # compute counts of agreements and disagreement (4 types) and the regular rand index
    sum_table_squared = sum(sum(contingency_table ** 2))
    sum_colsum_squared = sum(colsum ** 2)
    sum_rowsum_squared = sum(rowsum ** 2)
    count_in_each_b1 = np.sum(contingency_table, axis=1)
    count_in_each_b2 = np.sum(contingency_table, axis=0)
    num_same_in_b1 = sum(count_in_each_b1 * (count_in_each_b1 - 1)) / 2
    num_same_in_b2 = sum(count_in_each_b2 * (count_in_each_b2 - 1)) / 2
    num_agreement_same = 0.5 * sum(sum(contingency_table * (contingency_table - 1)));
    num_agreement_diff = 0.5 * (N ** 2 + sum_table_squared - sum_colsum_squared - sum_rowsum_squared);
    num_agreement = num_agreement_same + num_agreement_diff
    rand_index = num_agreement / num_pairs

    vectorized_nchoose2 = np.vectorize(nchoose2)
    sum_table_choose_2 = sum(sum(vectorized_nchoose2(contingency_table)))
    sum_colsum_choose_2 = sum(vectorized_nchoose2(colsum))
    sum_rowsum_choose_2 = sum(vectorized_nchoose2(rowsum))
    adjusted_rand_index = (sum_table_choose_2 - sum_rowsum_choose_2 * sum_colsum_choose_2 / num_pairs) / (
        0.5 * (sum_rowsum_choose_2 + sum_colsum_choose_2) - sum_rowsum_choose_2 * sum_colsum_choose_2 / num_pairs)
    print('Rand Index: {}'.format(rand_index))
    print('Adjusted Rand Index: {}'.format(adjusted_rand_index))
    print('Pairwise Recall: {}'.format(num_agreement_same / (num_same_in_b1)))
    print('Pairwise Precision: {}'.format(num_agreement_same / (num_same_in_b2)))
    print('\n')

    # compute the information theoretic metrics
    marginal_prob_b2 = np.sum(joint_prob, 0)
    marginal_prob_b1 = np.sum(joint_prob, 1)
    idx1 = np.nonzero(marginal_prob_b1)
    idx2 = np.nonzero(marginal_prob_b2)
    conditional_prob_b2_b1 = np.zeros(joint_prob.shape)
    conditional_prob_b1_b2 = np.zeros(joint_prob.shape)
    conditional_prob_b2_b1[idx1, :] = joint_prob[idx1, :] / marginal_prob_b1[idx1, None]
    conditional_prob_b1_b2[:, idx2] = joint_prob[:, idx2] / marginal_prob_b2[None, idx2]
    # compute entropy of the non-partition2 and the partition2 version
    H_b2 = -np.sum(marginal_prob_b2[idx2] * np.log(marginal_prob_b2[idx2]))
    H_b1 = -np.sum(marginal_prob_b1[idx1] * np.log(marginal_prob_b1[idx1]))

    # compute the conditional entropies
    idx = np.nonzero(joint_prob)
    H_b2_b1 = -np.sum(np.sum(joint_prob[idx] * np.log(conditional_prob_b2_b1[idx])))
    H_b1_b2 = -np.sum(np.sum(joint_prob[idx] * np.log(conditional_prob_b1_b2[idx])))
    # compute the mutual information (symmetric)
    marginal_prod = np.dot(marginal_prob_b1[:, None], np.transpose(marginal_prob_b2[:, None]))
    MI_b1_b2 = np.sum(np.sum(joint_prob[idx] * np.log(joint_prob[idx] / marginal_prod[idx])))

    if H_b1 > 0:
        fraction_missed_info = H_b1_b2 / H_b1
    else:
        fraction_missed_info = 0
    if H_b2 > 0:
        fraction_err_info = H_b2_b1 / H_b2
    else:
        fraction_err_info = 0
    print('Entropy of truth partition: {}'.format(abs(H_b1)))
    print('Entropy of alg. partition: {}'.format(abs(H_b2)))
    print('Conditional entropy of truth partition given alg. partition: {}'.format(abs(H_b1_b2)))
    print('Conditional entropy of alg. partition given truth partition: {}'.format(abs(H_b2_b1)))
    print('Mututal informationion between truth partition and alg. partition: {}'.format(abs(MI_b1_b2)))
    print('Fraction of missed information: {}'.format(abs(fraction_missed_info)))
    print('Fraction of erroneous information: {}'.format(abs(fraction_err_info)))


text:
using namespace std;
using namespace std::chrono;

class GameDriver
{
public:
	static GameDriver* getInstance();	//TODO: Should probably set this to reference to not allow random delete the object
	~GameDriver();

	void startGame();
	std::thread startGameThread();	//Call this to initiate startGame on a new thread.

	// setters
	void setTotalPlayers(int n);
	void setPlayers(vector<Player*> p);
	void setSelectedMap(Map* m);

private:
	static GameDriver* instance;

	StatsObserver* statsObserver = nullptr;

	int totalPlayers;
	vector<Player*> players;
	vector<PlayerView*> playerViews;
	Map* selectedMap = nullptr;

	GameDriver();

	bool checkWinCondition();	//return true if one player left in the game, false otherwise.

	void playerAssignReinforcmentToCountries(Player* player);

	void log();

	void play();
	void reinforcePhase(Player* player);
	void attackPhase(Player* player);
	void fortifcationPhase(Player* player);
	void saveGame();
	void switchPlayerType(Player* player);

	void displayCountriesWithArmy(vector<Country*> countries);
};
#endif


text:
<?php
namespace ARIPD\DefaultBundle\Types\Type\Spatial;

use Doctrine\ORM\Query\AST\Functions\FunctionNode;
use Doctrine\ORM\Query\Lexer;

/**
 * DQL function for calculating distances between two points
 *
 * Example: DISTANCE(foo.point, POINT_STR(:param))
 *
 * SELECT username, X(coordinate), Y(coordinate), (GLength(LineStringFromWKB(LineString(coordinate, GeomFromText('POINT(40.993974 29.12585)'))))) AS distance FROM user ORDER BY distance ASC
 *
 */
class Distance extends FunctionNode {
	private $firstArg;
	private $secondArg;

	public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) {
		//Need to do this hacky linestring length thing because
		//despite what MySQL manual claims, DISTANCE isn't actually implemented...
		return 'GLength(LineString(' . $this->firstArg->dispatch($sqlWalker)
				. ', ' . $this->secondArg->dispatch($sqlWalker) . '))';
	}

	public function parse(\Doctrine\ORM\Query\Parser $parser) {
		$parser->match(Lexer::T_IDENTIFIER);
		$parser->match(Lexer::T_OPEN_PARENTHESIS);
		$this->firstArg = $parser->ArithmeticPrimary();
		$parser->match(Lexer::T_COMMA);
		$this->secondArg = $parser->ArithmeticPrimary();
		$parser->match(Lexer::T_CLOSE_PARENTHESIS);
	}
}


text:
export const FooterComponent = {
    template: `

     © 2016 Abel Salas.

  `
}


text:
package com.ifttt.sparklemotion;

import android.support.annotation.NonNull;
import android.view.View;
import android.view.ViewTreeObserver;

/**
 * {@link Animation} subclass used for running slide out animation when {@link Decor.Builder#slideIn()} is used.
 * Note that this animation has state, therefore cannot be reused by other Views, each View needs to have
 * a new instance of it.
 */
final class SlideInAnimation extends Animation {

    private boolean mOriginalTranslationSet;

    /**
     * Distance of the View to slide out of the screen.
     */
    float mDistance;

    /**
     * Translation X of the View before running this animation.
     */
    float mOriginalTranslationX;

    public SlideInAnimation(@NonNull Page page) {
        super(page);
    }

    @Override
    public void onAnimate(View view, float offset, float offsetInPixel) {
        if (!mOriginalTranslationSet) {
            mOriginalTranslationSet = true;
            initViewPosition(view, 1 - offset);
        }

        offset = Math.abs(offset);
        view.setTranslationX(mOriginalTranslationX + (1 - offset) * mDistance);
    }

    /**
     * Initialize the View's position by adding a {@link android.view.ViewTreeObserver.OnPreDrawListener}, listening to
     * pre-draw, then assign the initial frame and destination frame.
     *
     * @param view   View to be animated.
     * @param offset Initial offset.
     */
    private void initViewPosition(final View view, final float offset) {
        view.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                view.getViewTreeObserver().removeOnPreDrawListener(this);
                mOriginalTranslationX = view.getTranslationX();
                View parent = (View) view.getParent();
                if (parent == null) {
                    return false;
                }

                mDistance = parent.getWidth() - view.getLeft();

                // Once initialized, run the initial animation frame.
                view.setTranslationX(mOriginalTranslationX + Math.abs(offset) * mDistance);
                return false;
            }
        });
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>Dr. Eric's Psychedelic Wonderland: Class Index</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Dr. Eric's Psychedelic Wonderland

Dr. Eric is a scientist that was cleaning up his lab after an accidental mishap causes him to ingest some experimental chemicals. As he tries to go home his body pulls off Dr Eric's head and begins to run into a psychedelic wonderland. Now you have to help Dr. Eric explore this new world and find his body before he is stuck as a head forever.

Main Page

Related Pages

Packages

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

Class Index

B | C | F | R | V

  B

  F

  R

  V

BallController   	FadeUI   	RandomColorLerper   	VictoryController

  C

	FlingObject   	RandomRotations

CrossPlatformInitialize (UnityStandardAssets.CrossPlatformInput.Inspector)

B | C | F | R | V

<address class="footer">
Generated on Mon Aug 3 2015 21:05:40 for Dr. Eric's Psychedelic Wonderland by

 1.8.9.1
</address>


text:
export default function(){
  this.transition(
    this.fromRoute('items'),
    this.toRoute('item'),
    this.use('toLeft'),
    this.reverse('toRight')
  );
   this.transition(
    this.fromRoute('items'),
    this.toRoute('groups'),
    this.use('crossFade'),
    this.reverse('crossFade')
  );
   this.transition(
    this.fromRoute('item'),
    this.toRoute('groups'),
    this.use('crossFade'),
    this.reverse('crossFade')
  );
  this.transition(
    this.fromRoute('groups'),
    this.toRoute('group'),
    this.use('toLeft'),
    this.reverse('toRight')
  );
   this.transition(
    this.fromRoute('items'),
    this.toRoute('group'),
    this.use('crossFade'),
    this.reverse('crossFade')
  );
   this.transition(
    this.fromRoute('item'),
    this.toRoute('group'),
    this.use('crossFade'),
    this.reverse('crossFade')
  );
}


text:
'''Copyright 2014, 2015 Zack Weinberg

Category Metadata
-----------------

A plugin to read metadata for each category from an index file in that
category's directory.

For this plugin to work properly, your articles should not have a
Category: tag in their metadata; instead, they should be stored in
(subdirectories of) per-category directories.  Each per-category
directory must have a file named 'index.ext' at its top level, where
.ext is any extension that will be picked up by an article reader.
The metadata of that article becomes the metadata for the category,
copied over verbatim, with three special cases:

 * The category's name is set to the article's title.
 * The category's slug is set to the name of the parent directory
   of the index.ext file.
 * The _text_ of the article is stored as category.description.
'''

from pelican import signals
import os
import re

import logging
logger = logging.getLogger(__name__)

### CORE BUG: https://github.com/getpelican/pelican/issues/1547
### Content.url_format does not honor category.slug (or author.slug).
### The sanest way to work around this is to dynamically redefine each
### article's class to a subclass of itself with the bug fixed.
###
### Core was fixed in rev 822fb134e041c6938c253dd4db71813c4d0dc74a,
### which is not yet in any release, so we dynamically detect whether
### the installed version of Pelican still has the bug.

patched_subclasses = {}
def make_patched_subclass(klass):
    if klass.__name__ not in patched_subclasses:
        class PatchedContent(klass):
            @property
            def url_format(self):
                metadata = super(PatchedContent, self).url_format
                if hasattr(self, 'author'):
                    metadata['author'] = self.author.slug
                if hasattr(self, 'category'):
                    metadata['category'] = self.category.slug

                return metadata
        # Code in core uses Content class names as keys for things.
        PatchedContent.__name__ = klass.__name__
        patched_subclasses[klass.__name__] = PatchedContent
    return patched_subclasses[klass.__name__]

def patch_urlformat(cont):
    # Test whether this content object needs to be patched.
    md = cont.url_format
    if ((hasattr(cont, 'author') and cont.author.slug != md['author']) or
        (hasattr(cont, 'category') and cont.category.slug != md['category'])):
        logger.debug("Detected bug 1547, applying workaround.")
        cont.__class__ = make_patched_subclass(cont.__class__)

### END OF BUG WORKAROUND

def make_category(article, slug):
    # Reuse the article's existing category object.
    category = article.category

    # Setting a category's name resets its slug, so do that first.
    category.name = article.title
    category.slug = slug

    # Description from article text.
    # XXX Relative URLs in the article content may not be handled correctly.
    setattr(category, 'description', article.content)

    # Metadata, to the extent that this makes sense.
    for k, v in article.metadata.items():
        if k not in ('path', 'slug', 'category', 'name', 'title',
                     'description', 'reader'):
            setattr(category, k, v)

    logger.debug("Category: %s -> %s", category.slug, category.name)
    return category

def pretaxonomy_hook(generator):
    """This hook is invoked before the generator's .categories property is
       filled in. Each article has already been assigned a category
       object, but these objects are _not_ unique per category and so are
       not safe to tack metadata onto (as is).

       The category metadata we're looking for is represented as an
       Article object, one per directory, whose filename is 'index.ext'.
    """

    category_objects = {}
    real_articles = []

    for article in generator.articles:
        dirname, fname = os.path.split(article.source_path)
        fname, _ = os.path.splitext(fname)
        if fname == 'index':
            category_objects[dirname] = \
                make_category(article, os.path.basename(dirname))
        else:
            real_articles.append(article)

    category_assignment = \
        re.compile("^(" +
                   "|".join(re.escape(prefix)
                            for prefix in category_objects.keys()) +
                   ")/")

    for article in real_articles:
        m = category_assignment.match(article.source_path)
        if not m or m.group(1) not in category_objects:
            logger.error("No category assignment for %s (%s)",
                         article, article.source_path)
            continue

        article.category = category_objects[m.group(1)]
        patch_urlformat(article)

    generator.articles = real_articles

def register():
    signals.article_generator_pretaxonomy.connect(pretaxonomy_hook)


text:
wixWalker
=========

Directory walker that outputs partial WIX XML. A NodeJS application that will write out WIX XML for all files in a directory and all it's subdirectories.

This is not intended to create the full WIX file. It is meant to reduce the tedium of creating the XML structure for a large number of files.

Usage
-----

`>node wixWalker.js folderToCrawl outputFile [wixSourcePathVariable]`

folderToCrawl - This is the root folder to scan. This folder, along with all its subfolders will be scanned.

outputFile - Full path, file name and extension of the XML file to be written.

wixSourcePathVariable - The wix variable to the root path of the files. Defaults to `$(var.sourceDirectory)`.

Example
-------

Given the following structure
* /temp/foo/
    * baz.txt
    * quz.txt
    * /temp/foo/bar/
        * quux.txt
        * /temp/foo/bar/corge/
            * baz.txt

`node wixWalker.js /temp/foo/ /temp/wix-example-stub.xml $(var.exampleSourceDir)`

The output written to wix-example-stub.xml will be:

```xml
<Directory Id="fooDirectory" Name="foo">
    <Component Id="fooComponent" Guid="4cee7111-e4f0-47cf-82dc-86d0078dd6fc">
        <File Id="baz.txt" Name="baz.txt" DiskId="1" Source="$(var.exampleSourceDir)baz.txt" Vital="yes" />
        <File Id="qux.txt" Name="qux.txt" DiskId="1" Source="$(var.exampleSourceDir)qux.txt" Vital="yes" />
    </Component>
    <Directory Id="barDirectory" Name="bar">
        <Component Id="barComponent" Guid="f99eda21-5739-492e-9cf6-8f071ad25d53">
            <File Id="quux.txt" Name="quux.txt" DiskId="1" Source="$(var.exampleSourceDir)bar\quux.txt" Vital="yes" />
        </Component>
        <Directory Id="corgeDirectory" Name="corge">
            <Component Id="corgeComponent" Guid="ebe1f5a7-93f9-4cf2-9a5e-f080ec5b75f2">
                <File Id="baz.txt1" Name="baz.txt" DiskId="1" Source="$(var.exampleSourceDir)bar\corge\baz.txt" Vital="yes" />
            </Component>
        </Directory>
    </Directory>
</Directory>

<ComponentRef Id="fooComponent" />
<ComponentRef Id="barComponent" />
<ComponentRef Id="corgeComponent" />
```

Requirements
------------
Underscore
`npm install underscore`

UUID
`npm install uuid`

OR just run an update against the included package.json
`npm update`


text:
<!doctype html>

  <meta charset="utf-8">
  <title>Child Process Node.js v0.10.24 Manual & Documentation</title>
  <link rel="stylesheet" href="assets/style.css">
  <link rel="stylesheet" href="assets/sh.css">
  <link rel="canonical" href="http://nodejs.org/api/child_process.html">

Home

Download

About

npm Registry

Docs

Blog

Community

Logos

Jobs

@nodejs

Node.js v0.10.24 Manual & Documentation

                Index |
                View on single page |
                View as JSON

Table of Contents

Child Process

Class: ChildProcess

Event:  'error'

Event:  'exit'

Event: 'close'

Event: 'disconnect'

Event: 'message'

child.stdin

child.stdout

child.stderr

child.pid

child.connected

child.kill([signal])

child.send(message, [sendHandle])

Example: sending server object

Example: sending socket object

child.disconnect()

child_process.spawn(command, [args], [options])

child_process.exec(command, [options], callback)

child_process.execFile(file, args, options, callback)

child_process.fork(modulePath, [args], [options])

Child Process#

Stability: 3 - Stable

Node provides a tri-directional popen(3) facility through the
child_process module.

It is possible to stream data through a child's stdin, stdout, and
stderr in a fully non-blocking way.  (Note that some programs use
line-buffered I/O internally.  That doesn't affect node.js but it means
data you send to the child process is not immediately consumed.)

To create a child process use require('child_process').spawn() or
require('child_process').fork().  The semantics of each are slightly
different, and explained below.

Class: ChildProcess#

ChildProcess is an EventEmitter.

Child processes always have three streams associated with them. child.stdin,
child.stdout, and child.stderr.  These may be shared with the stdio
streams of the parent process, or they may be separate stream objects
which can be piped to and from.

The ChildProcess class is not intended to be used directly.  Use the
spawn() or fork() methods to create a Child Process instance.

Event:  'error'#

err Error Object the error.

Emitted when:

The process could not be spawned, or

The process could not be killed, or

Sending a message to the child process failed for whatever reason.

Note that the exit-event may or may not fire after an error has occured. If
you are listening on both events to fire a function, remember to guard against
calling your function twice.

See also ChildProcess#kill() and
ChildProcess#send().

Event:  'exit'#

code Number the exit code, if it exited normally.

signal String the signal passed to kill the child process, if it
was killed by the parent.

This event is emitted after the child process ends. If the process terminated
normally, code is the final exit code of the process, otherwise null. If
the process terminated due to receipt of a signal, signal is the string name
of the signal, otherwise null.

Note that the child process stdio streams might still be open.

Also, note that node establishes signal handlers for 'SIGINT' and 'SIGTERM',
so it will not terminate due to receipt of those signals, it will exit.

See waitpid(2).

Event: 'close'#

code Number the exit code, if it exited normally.

signal String the signal passed to kill the child process, if it
was killed by the parent.

This event is emitted when the stdio streams of a child process have all
terminated.  This is distinct from 'exit', since multiple processes
might share the same stdio streams.

Event: 'disconnect'#

This event is emitted after calling the .disconnect() method in the parent
or in the child. After disconnecting it is no longer possible to send messages,
and the .connected property is false.

Event: 'message'#

message Object a parsed JSON object or primitive value

sendHandle Handle object a Socket or Server object

Messages send by .send(message, [sendHandle]) are obtained using the
message event.

child.stdin#

Stream object

A Writable Stream that represents the child process's stdin.
Closing this stream via end() often causes the child process to terminate.

If the child stdio streams are shared with the parent, then this will
not be set.

child.stdout#

Stream object

A Readable Stream that represents the child process's stdout.

If the child stdio streams are shared with the parent, then this will
not be set.

child.stderr#

Stream object

A Readable Stream that represents the child process's stderr.

If the child stdio streams are shared with the parent, then this will
not be set.

child.pid#

Integer

The PID of the child process.

Example:

var spawn = require('child_process').spawn,
    grep  = spawn('grep', ['ssh']);

console.log('Spawned child pid: ' + grep.pid);
grep.stdin.end();

child.connected#

Boolean Set to false after `.disconnect' is called

If .connected is false, it is no longer possible to send messages.

child.kill([signal])#

signal String

Send a signal to the child process. If no argument is given, the process will
be sent 'SIGTERM'. See signal(7) for a list of available signals.

var spawn = require('child_process').spawn,
    grep  = spawn('grep', ['ssh']);

grep.on('close', function (code, signal) {
  console.log('child process terminated due to receipt of signal '+signal);
});

// send SIGHUP to process
grep.kill('SIGHUP');

May emit an 'error' event when the signal cannot be delivered. Sending a
signal to a child process that has already exited is not an error but may
have unforeseen consequences: if the PID (the process ID) has been reassigned
to another process, the signal will be delivered to that process instead.
What happens next is anyone's guess.

Note that while the function is called kill, the signal delivered to the
child process may not actually kill it.  kill really just sends a signal
to a process.

See kill(2)

child.send(message, [sendHandle])#

message Object

sendHandle Handle object

When using child_process.fork() you can write to the child using
child.send(message, [sendHandle]) and messages are received by
a 'message' event on the child.

For example:

var cp = require('child_process');

var n = cp.fork(__dirname + '/sub.js');

n.on('message', function(m) {
  console.log('PARENT got message:', m);
});

n.send({ hello: 'world' });

And then the child script, 'sub.js' might look like this:

process.on('message', function(m) {
  console.log('CHILD got message:', m);
});

process.send({ foo: 'bar' });

In the child the process object will have a send() method, and process
will emit objects each time it receives a message on its channel.

There is a special case when sending a {cmd: 'NODE_foo'} message. All messages
containing a NODE_ prefix in its cmd property will not be emitted in
the message event, since they are internal messages used by node core.
Messages containing the prefix are emitted in the internalMessage event, you
should by all means avoid using this feature, it is subject to change without notice.

The sendHandle option to child.send() is for sending a TCP server or
socket object to another process. The child will receive the object as its
second argument to the message event.

Emits an 'error' event if the message cannot be sent, for example because
the child process has already exited.

Example: sending server object#

Here is an example of sending a server:

var child = require('child_process').fork('child.js');

// Open up the server object and send the handle.
var server = require('net').createServer();
server.on('connection', function (socket) {
  socket.end('handled by parent');
});
server.listen(1337, function() {
  child.send('server', server);
});

And the child would the receive the server object as:

process.on('message', function(m, server) {
  if (m === 'server') {
    server.on('connection', function (socket) {
      socket.end('handled by child');
    });
  }
});

Note that the server is now shared between the parent and child, this means
that some connections will be handled by the parent and some by the child.

For dgram servers the workflow is exactly the same.  Here you listen on
a message event instead of connection and use server.bind instead of
server.listen.  (Currently only supported on UNIX platforms.)

Example: sending socket object#

Here is an example of sending a socket. It will spawn two children and handle
connections with the remote address 74.125.127.100 as VIP by sending the
socket to a "special" child process. Other sockets will go to a "normal" process.

var normal = require('child_process').fork('child.js', ['normal']);
var special = require('child_process').fork('child.js', ['special']);

// Open up the server and send sockets to child
var server = require('net').createServer();
server.on('connection', function (socket) {

  // if this is a VIP
  if (socket.remoteAddress === '74.125.127.100') {
    special.send('socket', socket);
    return;
  }
  // just the usual dudes
  normal.send('socket', socket);
});
server.listen(1337);

The child.js could look like this:

process.on('message', function(m, socket) {
  if (m === 'socket') {
    socket.end('You were handled as a ' + process.argv[2] + ' person');
  }
});

Note that once a single socket has been sent to a child the parent can no
longer keep track of when the socket is destroyed. To indicate this condition
the .connections property becomes null.
It is also recommended not to use .maxConnections in this condition.

child.disconnect()#

Close the IPC channel between parent and child, allowing the child to exit
gracefully once there are no other connections keeping it alive. After calling
this method the .connected flag will be set to false in both the parent and
child, and it is no longer possible to send messages.

The 'disconnect' event will be emitted when there are no messages in the process
of being received, most likely immediately.

Note that you can also call process.disconnect() in the child process.

child_process.spawn(command, [args], [options])#

command String The command to run

args Array List of string arguments

options Object

cwd String Current working directory of the child process

stdio Array|String Child's stdio configuration. (See below)

customFds Array Deprecated File descriptors for the child to use
for stdio.  (See below)

env Object Environment key-value pairs

detached Boolean The child will be a process group leader.  (See below)

uid Number Sets the user identity of the process. (See setuid(2).)

gid Number Sets the group identity of the process. (See setgid(2).)

return: ChildProcess object

Launches a new process with the given command, with  command line arguments in args.
If omitted, args defaults to an empty Array.

The third argument is used to specify additional options, which defaults to:

{ cwd: undefined,
  env: process.env
}

cwd allows you to specify the working directory from which the process is spawned.
Use env to specify environment variables that will be visible to the new process.

Example of running ls -lh /usr, capturing stdout, stderr, and the exit code:

var spawn = require('child_process').spawn,
    ls    = spawn('ls', ['-lh', '/usr']);

ls.stdout.on('data', function (data) {
  console.log('stdout: ' + data);
});

ls.stderr.on('data', function (data) {
  console.log('stderr: ' + data);
});

ls.on('close', function (code) {
  console.log('child process exited with code ' + code);
});

Example: A very elaborate way to run 'ps ax | grep ssh'

var spawn = require('child_process').spawn,
    ps    = spawn('ps', ['ax']),
    grep  = spawn('grep', ['ssh']);

ps.stdout.on('data', function (data) {
  grep.stdin.write(data);
});

ps.stderr.on('data', function (data) {
  console.log('ps stderr: ' + data);
});

ps.on('close', function (code) {
  if (code !== 0) {
    console.log('ps process exited with code ' + code);
  }
  grep.stdin.end();
});

grep.stdout.on('data', function (data) {
  console.log('' + data);
});

grep.stderr.on('data', function (data) {
  console.log('grep stderr: ' + data);
});

grep.on('close', function (code) {
  if (code !== 0) {
    console.log('grep process exited with code ' + code);
  }
});

Example of checking for failed exec:

var spawn = require('child_process').spawn,
    child = spawn('bad_command');

child.stderr.setEncoding('utf8');
child.stderr.on('data', function (data) {
  if (/^execvp\(\)/.test(data)) {
    console.log('Failed to start child process.');
  }
});

Note that if spawn receives an empty options object, it will result in
spawning the process with an empty environment rather than using
process.env. This due to backwards compatibility issues with a deprecated
API.

The 'stdio' option to child_process.spawn() is an array where each
index corresponds to a fd in the child.  The value is one of the following:

'pipe' - Create a pipe between the child process and the parent process.
The parent end of the pipe is exposed to the parent as a property on the
child_process object as ChildProcess.stdio[fd]. Pipes created for
fds 0 - 2 are also available as ChildProcess.stdin, ChildProcess.stdout
and ChildProcess.stderr, respectively.

'ipc' - Create an IPC channel for passing messages/file descriptors
between parent and child. A ChildProcess may have at most one IPC stdio
file descriptor. Setting this option enables the ChildProcess.send() method.
If the child writes JSON messages to this file descriptor, then this will
trigger ChildProcess.on('message').  If the child is a Node.js program, then
the presence of an IPC channel will enable process.send() and
process.on('message').

'ignore' - Do not set this file descriptor in the child. Note that Node
will always open fd 0 - 2 for the processes it spawns. When any of these is
ignored node will open /dev/null and attach it to the child's fd.

Stream object - Share a readable or writable stream that refers to a tty,
file, socket, or a pipe with the child process. The stream's underlying
file descriptor is duplicated in the child process to the fd that
corresponds to the index in the stdio array.

Positive integer - The integer value is interpreted as a file descriptor
that is is currently open in the parent process. It is shared with the child
process, similar to how Stream objects can be shared.

null, undefined - Use default value. For stdio fds 0, 1 and 2 (in other
words, stdin, stdout, and stderr) a pipe is created. For fd 3 and up, the
default is 'ignore'.

As a shorthand, the stdio argument may also be one of the following
strings, rather than an array:

ignore - ['ignore', 'ignore', 'ignore']

pipe - ['pipe', 'pipe', 'pipe']

inherit - [process.stdin, process.stdout, process.stderr] or [0,1,2]

Example:

var spawn = require('child_process').spawn;

// Child will use parent's stdios
spawn('prg', [], { stdio: 'inherit' });

// Spawn child sharing only stderr
spawn('prg', [], { stdio: ['pipe', 'pipe', process.stderr] });

// Open an extra fd=4, to interact with programs present a
// startd-style interface.
spawn('prg', [], { stdio: ['pipe', null, null, null, 'pipe'] });

If the detached option is set, the child process will be made the leader of a
new process group.  This makes it possible for the child to continue running
after the parent exits.

By default, the parent will wait for the detached child to exit.  To prevent
the parent from waiting for a given child, use the child.unref() method,
and the parent's event loop will not include the child in its reference count.

Example of detaching a long-running process and redirecting its output to a
file:

 var fs = require('fs'),
     spawn = require('child_process').spawn,
     out = fs.openSync('./out.log', 'a'),
     err = fs.openSync('./out.log', 'a');

 var child = spawn('prg', [], {
   detached: true,
   stdio: [ 'ignore', out, err ]
 });

 child.unref();

When using the detached option to start a long-running process, the process
will not stay running in the background unless it is provided with a stdio
configuration that is not connected to the parent.  If the parent's stdio is
inherited, the child will remain attached to the controlling terminal.

There is a deprecated option called customFds which allows one to specify
specific file descriptors for the stdio of the child process. This API was
not portable to all platforms and therefore removed.
With customFds it was possible to hook up the new process' [stdin, stdout,
stderr] to existing streams; -1 meant that a new stream should be created.
Use at your own risk.

See also: child_process.exec() and child_process.fork()

child_process.exec(command, [options], callback)#

command String The command to run, with space-separated arguments

options Object

cwd String Current working directory of the child process

env Object Environment key-value pairs

encoding String (Default: 'utf8')

timeout Number (Default: 0)

maxBuffer Number (Default: 200*1024)

killSignal String (Default: 'SIGTERM')

callback Function called with the output when process terminates

error Error

stdout Buffer

stderr Buffer

Return: ChildProcess object

Runs a command in a shell and buffers the output.

var exec = require('child_process').exec,
    child;

child = exec('cat *.js bad_file | wc -l',
  function (error, stdout, stderr) {
    console.log('stdout: ' + stdout);
    console.log('stderr: ' + stderr);
    if (error !== null) {
      console.log('exec error: ' + error);
    }
});

The callback gets the arguments (error, stdout, stderr). On success, error
will be null.  On error, error will be an instance of Error and err.code
will be the exit code of the child process, and err.signal will be set to the
signal that terminated the process.

There is a second optional argument to specify several options. The
default options are

{ encoding: 'utf8',
  timeout: 0,
  maxBuffer: 200*1024,
  killSignal: 'SIGTERM',
  cwd: null,
  env: null }

If timeout is greater than 0, then it will kill the child process
if it runs longer than timeout milliseconds. The child process is killed with
killSignal (default: 'SIGTERM'). maxBuffer specifies the largest
amount of data allowed on stdout or stderr - if this value is exceeded then
the child process is killed.

child_process.execFile(file, args, options, callback)#

file String The filename of the program to run

args Array List of string arguments

options Object

cwd String Current working directory of the child process

env Object Environment key-value pairs

encoding String (Default: 'utf8')

timeout Number (Default: 0)

maxBuffer Number (Default: 200*1024)

killSignal String (Default: 'SIGTERM')

callback Function called with the output when process terminates

error Error

stdout Buffer

stderr Buffer

Return: ChildProcess object

This is similar to child_process.exec() except it does not execute a
subshell but rather the specified file directly. This makes it slightly
leaner than child_process.exec. It has the same options.

child_process.fork(modulePath, [args], [options])#

modulePath String The module to run in the child

args Array List of string arguments

options Object

cwd String Current working directory of the child process

env Object Environment key-value pairs

encoding String (Default: 'utf8')

execPath String Executable used to create the child process

execArgv Array List of string arguments passed to the executable
(Default: process.execArgv)

silent Boolean If true, prevent stdout and stderr in the spawned node
process from being associated with the parent's (default is false)

Return: ChildProcess object

This is a special case of the spawn() functionality for spawning Node
processes. In addition to having all the methods in a normal ChildProcess
instance, the returned object has a communication channel built-in. See
child.send(message, [sendHandle]) for details.

These child Nodes are still whole new instances of V8. Assume at least 30ms
startup and 10mb memory for each new Node. That is, you cannot create many
thousands of them.

The execPath property in the options object allows for a process to be
created for the child rather than the current node executable. This should be
done with care and by default will talk over the fd represented an
environmental variable NODE_CHANNEL_FD on the child process. The input and
output on this fd is expected to be line delimited JSON objects.

        Joyent

Node.js

Download

About

npm Registry

Docs

Blog

Community

Logos

Jobs

@nodejs

Copyright Joyent, Inc, Node.js is a trademark of Joyent, Inc. View license.


text:
package EasySqlFactory;

import java.util.ArrayList;
import java.util.List;
import org.jsoup.helper.StringUtil;

/**
 * Classe para criar um update dinamicamente.
 * @author Victor Vaz <victor-vaz@hotmail.com>
 */
public class Insert implements Query
{
    public String tabela;

    public List<String> campos = new ArrayList<>();

    public List<List<String>> valores = new ArrayList<>();

    /**
     * Cria a sql de acordo com os parâmetros.
     * @return String sql criada.
     */
    @Override
    public String create()
    {
        // Lista de campos:
        String sqlCampos = " (" + StringUtil.join(campos, ", ") + ") ";

        // Lista de valores:
        List<String> sqlSubValores = new ArrayList<>();
        for (int i = 0; i < valores.size(); i++)
        {
            List<String> listaValores = valores.get(i);
            sqlSubValores.add(" (" + StringUtil.join(listaValores, ", ") + ") ");
        }

        String sqlValores = StringUtil.join(sqlSubValores, ", ");

        String sqlFull = "INSERT INTO " + tabela + " " + sqlCampos + " VALUES " + sqlValores;

        return sqlFull;
    }

}


text:
import index from './routes/index';
import users from './routes/users';
import {initServiceRoutes} from './services';

export default function setupRoutes(app) {
  app.use('/', index);
  app.use('/users', users);

  initServiceRoutes(app);
}


text:
@component('sts-page2')
class StsPage2 extends polymer.Base {
}

StsPage2.register();


text:
package com.groundupworks.wings.facebook;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;

import com.facebook.widget.LoginButton;

/**
 * {@link android.app.Activity} with Facebook login button.
 */
public class FacebookLoginActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.facebook_activity_login);

        LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setResult(Activity.RESULT_OK);
                finish();
            }
        });
    }
}


text:
Package.describe({
	name: 'rocketchat:ui',
	version: '0.1.0',
	// Brief, one-line summary of the package.
	summary: '',
	// URL to the Git repository containing the source code for this package.
	git: '',
	// By default, Meteor will default to using README.md for documentation.
	// To avoid submitting documentation, set this field to null.
	documentation: 'README.md'
});

Package.onUse(function(api) {
	api.versionsFrom('1.2.1');

	api.use([
		'accounts-base',
		'mongo',
		'session',
		'jquery',
		'tracker',
		'reactive-var',
		'ecmascript',
		'templating',
		'coffeescript',
		'underscore',
		'rocketchat:lib',
		'raix:push',
		'raix:ui-dropped-event'
	]);

	api.use('kadira:flow-router', 'client');

	// LIB FILES
	api.addFiles('lib/getAvatarUrlFromUsername.coffee');
	api.addFiles('lib/accountBox.coffee', 'client');
	api.addFiles('lib/accounts.coffee', 'client');
	api.addFiles('lib/avatar.coffee', 'client');
	api.addFiles('lib/chatMessages.coffee', 'client');
	api.addFiles('lib/collections.coffee', 'client');
	api.addFiles('lib/constallation.js', 'client');
	api.addFiles('lib/customEventPolyfill.js', 'client');
	api.addFiles('lib/fileUpload.coffee', 'client');
	api.addFiles('lib/fireEvent.coffee', 'client');
	api.addFiles('lib/jquery.swipebox.min.js', 'client');
	api.addFiles('lib/menu.coffee', 'client');
	api.addFiles('lib/modal.coffee', 'client');
	api.addFiles('lib/Modernizr.js', 'client');
	api.addFiles('lib/msgTyping.coffee', 'client');
	api.addFiles('lib/notification.coffee', 'client');
	api.addFiles('lib/parentTemplate.js', 'client');
	api.addFiles('lib/particles.js', 'client');
	api.addFiles('lib/readMessages.coffee', 'client');
	api.addFiles('lib/rocket.coffee', 'client');
	api.addFiles('lib/RoomHistoryManager.coffee', 'client');
	api.addFiles('lib/RoomManager.coffee', 'client');
	api.addFiles('lib/sideNav.coffee', 'client');
	api.addFiles('lib/tapi18n.coffee', 'client');
	api.addFiles('lib/textarea-autogrow.js', 'client');

	// LIB CORDOVA
	api.addFiles('lib/cordova/facebook-login.coffee', 'client');
	api.addFiles('lib/cordova/keyboard-fix.coffee', 'client');
	api.addFiles('lib/cordova/push.coffee', 'client');
	api.addFiles('lib/cordova/urls.coffee', 'client');
	api.addFiles('lib/cordova/user-state.coffee', 'client');

	// LIB RECORDERJS
	api.addFiles('lib/recorderjs/audioRecorder.coffee', 'client');
	api.addFiles('lib/recorderjs/videoRecorder.coffee', 'client');
	api.addFiles('lib/recorderjs/recorder.js', 'client');

	// LIB CLIPBOARDJS
	api.addFiles('lib/clipboardjs/clipboard.js', 'client');

	// TEXTAREA CURSOR MANAGEMENT
	api.addFiles('lib/textarea-cursor/set-cursor-position.js', 'client');

	// TEMPLATE FILES
	api.addFiles('views/cmsPage.html', 'client');
	api.addFiles('views/fxos.html', 'client');
	api.addFiles('views/modal.html', 'client');
	api.addFiles('views/404/roomNotFound.html', 'client');
	api.addFiles('views/404/invalidSecretURL.html', 'client');
	api.addFiles('views/app/audioNotification.html', 'client');
	api.addFiles('views/app/burger.html', 'client');
	api.addFiles('views/app/home.html', 'client');
	api.addFiles('views/app/notAuthorized.html', 'client');
	api.addFiles('views/app/pageContainer.html', 'client');
	api.addFiles('views/app/pageSettingsContainer.html', 'client');
	api.addFiles('views/app/privateHistory.html', 'client');
	api.addFiles('views/app/room.html', 'client');
	api.addFiles('views/app/roomSearch.html', 'client');
	api.addFiles('views/app/secretURL.html', 'client');
	api.addFiles('views/app/userSearch.html', 'client');
	api.addFiles('views/app/spotlight/spotlight.html', 'client');
	api.addFiles('views/app/videoCall/videoButtons.html', 'client');
	api.addFiles('views/app/videoCall/videoCall.html', 'client');

	api.addFiles('views/cmsPage.coffee', 'client');
	api.addFiles('views/fxos.coffee', 'client');
	api.addFiles('views/modal.coffee', 'client');
	api.addFiles('views/404/roomNotFound.coffee', 'client');
	api.addFiles('views/app/burger.coffee', 'client');
	api.addFiles('views/app/home.coffee', 'client');
	api.addFiles('views/app/privateHistory.coffee', 'client');
	api.addFiles('views/app/room.coffee', 'client');
	api.addFiles('views/app/roomSearch.coffee', 'client');
	api.addFiles('views/app/secretURL.coffee', 'client');
	api.addFiles('views/app/spotlight/mobileMessageMenu.coffee', 'client');
	api.addFiles('views/app/spotlight/spotlight.coffee', 'client');
	api.addFiles('views/app/videoCall/videoButtons.coffee', 'client');
	api.addFiles('views/app/videoCall/videoCall.coffee', 'client');
});


text:
package org.apache.poi.xssf.usermodel;

import org.apache.poi.ss.usermodel.BaseTestSheet;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.XSSFITestDataProvider;
import org.apache.poi.xssf.XSSFTestDataSamples;
import org.apache.poi.xssf.model.CommentsTable;
import org.apache.poi.xssf.model.StylesTable;
import org.apache.poi.xssf.usermodel.helpers.ColumnHelper;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCols;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTComments;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRow;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTXf;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.STPane;

public class TestXSSFChartSheet extends BaseTestSheet {

    @Override
    protected XSSFITestDataProvider getTestDataProvider() {
        return XSSFITestDataProvider.getInstance();
    }

    public void testXSSFFactory() {
        XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("chart_sheet.xlsx");
        assertEquals(4, wb.getNumberOfSheets());

        //the third sheet is of type 'chartsheet'
        assertEquals("Chart1", wb.getSheetName(2));
        assertTrue(wb.getSheetAt(2) instanceof XSSFChartSheet);
        assertEquals("Chart1", wb.getSheetAt(2).getSheetName());

    }

    public void testGetAccessors() {
        XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("chart_sheet.xlsx");
        XSSFChartSheet sheet = (XSSFChartSheet)wb.getSheetAt(2);
        for(Row row : sheet) {
            fail("Row iterator for chart sheets should return zero rows");
        }
        //access to a arbitrary row
        assertEquals(null, sheet.getRow(1));

        //some basic get* accessors
        assertEquals(0, sheet.getNumberOfComments());
        assertEquals(0, sheet.getNumHyperlinks());
        assertEquals(0, sheet.getNumMergedRegions());
        assertEquals(null, sheet.getActiveCell());
        assertEquals(true, sheet.getAutobreaks());
        assertEquals(null, sheet.getCellComment(0, 0));
        assertEquals(0, sheet.getColumnBreaks().length);
        assertEquals(true, sheet.getRowSumsBelow());
    }

    /**
     * YK: disable failing test from the superclass
     */
    @Override
    public void testDefaultColumnStyle() {

    }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<updateSite xmlns="http://ns.taverna.org.uk/2013/application/profile" xmlns:ns2="http://ns.taverna.org.uk/2013/application/versions" xmlns:ns3="http://ns.taverna.org.uk/2013/application/plugin" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://ns.taverna.org.uk/2013/application/profile http://localhost/2013/application/profile/ApplicationProfile.xsd">
    <versions>
        <ns2:id>uk.org.taverna.workbench.taverna-workbench-product</ns2:id>
        <ns2:name>Taverna Workbench</ns2:name>
        <ns2:latestVersion>
            <ns2:version>3.0.1.20131211T1539</ns2:version>
            <ns2:file>ApplicationProfile-3.0.1.20131211T1539.xml</ns2:file>
        </ns2:latestVersion>
    </versions>
</updateSite>


text:
package com.ansorgit.plugins.bash.lang.parser.arithmetic;

import com.ansorgit.plugins.bash.lang.parser.BashPsiBuilder;
import com.ansorgit.plugins.bash.lang.parser.util.ParserUtil;
import com.intellij.lang.PsiBuilder;

/**
 * Parsing of prefix increment operators.
 * <br>
 * @author jansorg
 */
class PreIncrementExpr implements ArithmeticParsingFunction {
    private final ArithmeticParsingFunction next;

    PreIncrementExpr(ArithmeticParsingFunction next) {
        this.next = next;
    }

    public boolean isValid(BashPsiBuilder builder) {
        return arithmeticPreOps.contains(builder.getTokenType()) || next.isValid(builder);
    }

    public boolean parse(BashPsiBuilder builder) {
        PsiBuilder.Marker marker = builder.mark();
        boolean mark = ParserUtil.conditionalRead(builder, arithmeticPreOps);

        boolean ok = next.parse(builder);

        if (mark) {
            marker.done(ARITH_PRE_INC_ELEMENT);
        } else {
            marker.drop();
        }

        return ok;
    }
}


text:
package com.google.collide.client.logging;

public class LogView {

}


text:
package io.wcm.handler.link;

import static io.wcm.handler.link.LinkNameConstants.PN_COMPONENT_LINK_TARGET_URL_FALLBACK_PROPERTY;
import static io.wcm.handler.link.LinkNameConstants.PN_COMPONENT_LINK_TARGET_WINDOW_TARGET_FALLBACK_PROPERTY;

import org.apache.sling.api.resource.Resource;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.osgi.annotation.versioning.ProviderType;

import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import io.wcm.wcm.commons.component.ComponentPropertyResolution;
import io.wcm.wcm.commons.component.ComponentPropertyResolver;
import io.wcm.wcm.commons.component.ComponentPropertyResolverFactory;

/**
 * Resolves Link Handler component properties for the component associated
 * with the given resource from content policies and properties defined in the component resource.
 * Please make sure to {@link #close()} instances of this class after usage.
 */
@ProviderType
public final class LinkComponentPropertyResolver implements AutoCloseable {

  private final ComponentPropertyResolver resolver;

  /**
   * @param resource Resource containing link properties
   * @param componentPropertyResolverFactory Component property resolver factory
   */
  public LinkComponentPropertyResolver(@NotNull Resource resource,
      @NotNull ComponentPropertyResolverFactory componentPropertyResolverFactory) {
    // resolve media component properties 1. from policies and 2. from component definition
    resolver = componentPropertyResolverFactory.get(resource, true)
        .contentPolicyResolution(ComponentPropertyResolution.RESOLVE)
        .componentPropertiesResolution(ComponentPropertyResolution.RESOLVE_INHERIT);
  }

  /**
   * @param resource Resource containing link properties
   * @deprecated Please use {@link #LinkComponentPropertyResolver(Resource, ComponentPropertyResolverFactory)}
   */
  @Deprecated
  @SuppressWarnings("resource")
  public LinkComponentPropertyResolver(@NotNull Resource resource) {
    // resolve media component properties 1. from policies and 2. from component definition
    resolver = new ComponentPropertyResolver(resource, true)
        .contentPolicyResolution(ComponentPropertyResolution.RESOLVE)
        .componentPropertiesResolution(ComponentPropertyResolution.RESOLVE_INHERIT);
  }

  /**
   * @return Link target URL fallback property name
   */
  @SuppressFBWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE")
  public @NotNull String @Nullable [] getLinkTargetUrlFallbackProperty() {
    return resolver.get(PN_COMPONENT_LINK_TARGET_URL_FALLBACK_PROPERTY, String[].class);
  }

  /**
   * @return Link target window target fallback property name
   */
  @SuppressFBWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE")
  public @NotNull String @Nullable [] getLinkTargetWindowTargetFallbackProperty() {
    return resolver.get(PN_COMPONENT_LINK_TARGET_WINDOW_TARGET_FALLBACK_PROPERTY, String[].class);
  }

  @Override
  public void close() throws Exception {
    resolver.close();
  }

}