text:
      <form class="form-horizontal" id="user-registration-form">

                        First Name

                            <input class="form-control" type="text" required name="firstname" id="firstname" placeholder="First Name">

                        Last Name

                            <input class="form-control" type="text" required name="lastname" id="lastname" placeholder="Last Name">

                        Email

                            <input id="email" name="email" required placeholder="Email" type="email" class="form-control">

                        Username

                            <input class="form-control" type="text" required name="username" id="username" placeholder="Username">

                        Password

                            <input class="form-control" type="password" required name="password" id="password" placeholder="Password">

                        Background

                           <select class="form-control" id="background-select" name="background">
                                <option value="student_el">Elementary School Student</option>
                                <option value="student_ms">Middle School Student</option>
                                <option value="student_hs" selected="selected">High School Student</option>
                                <option value="student_home">Homeschooled Student</option>
                                <option value="student_undergrad">Undergraduate</option>
                                <option value="student_grad">Graduate Student</option>
                                <option value="teacher">Teacher</option>
                                <option value="secprof">Security Professional</option>
                                <option value="hobbyist">CTF Hobbyist (non-Student)</option>
                                <option value="other">Other</option>
                            </select>

                        Country

                            <select class="form-control" id="country-select" name="country">
                                 Countries get added here
                            </select>

                        Note that only K-12 students from the United States are eligible for prizes. Others are encouraged to play picoCTF, but will not appear on the public scoreboard.

                                <input type="radio">Create a New Team

                                <input type="radio">Join an Existing Team

                                <input type="radio">Create a Teacher Account

                                    Team Name

                                        <input id="team-name-new" name="team-name-new" class="form-control" type="text" placeholder="Team Name">

                                    Passphrase*

                                        <input id="team-password-new" name="team-password-new" class="form-control" type="text" placeholder="Team Passphrase">

                                    School

                                        <input id="team-school-new" name="team-school-new" placeholder="School or Affiliation" type="text" class="form-control">

                                <input type="checkbox" id="checkbox-emails-create"> I would like to receive emails about other CTFs for high school students.

                        *While your password should be kept a secret and only used by you, your Team Passphrase is shared with the other members of your team. If you forget your Team Passphrase, it will be displayed on the "Team" page after you log in.

                            <button id="register-button-create" type="submit" class="btn btn-primary">
                                Register
                            </button>

                                Team Name

                                    <input id="team-name-existing" name="team-name-existing" placeholder="Team Name" type="text" class="form-control">

                                Passphrase

                                    <input id="team-password-existing" name="team-password-existing" placeholder="Team Passphrase"  type="text" class="form-control">

                            <button id="register-button-existing" type="submit" class="btn btn-primary">
                                Register
                            </button>

                                School

                                    <input id="teacher-school" name="teacher-school" placeholder="School or Affiliation" type="text" class="form-control">

                                <input type="checkbox" id="checkbox-emails-teacher"> I would like to receive emails about other CTFs for high school students.

Note that while Teacher Accounts can solve challenges during the competition, they do not appear on the public scoreboard.

                            <button id="register-button-teacher" type="submit" class="btn btn-primary">
                                Register
                            </button>

        </form>


text:
"""The tests the MQTT alarm control panel component."""
import copy
import json

import pytest

from homeassistant.components import alarm_control_panel
from homeassistant.const import (
    STATE_ALARM_ARMED_AWAY,
    STATE_ALARM_ARMED_CUSTOM_BYPASS,
    STATE_ALARM_ARMED_HOME,
    STATE_ALARM_ARMED_NIGHT,
    STATE_ALARM_ARMING,
    STATE_ALARM_DISARMED,
    STATE_ALARM_DISARMING,
    STATE_ALARM_PENDING,
    STATE_ALARM_TRIGGERED,
    STATE_UNKNOWN,
)
from homeassistant.setup import async_setup_component

from .test_common import (
    help_test_availability_when_connection_lost,
    help_test_availability_without_topic,
    help_test_custom_availability_payload,
    help_test_default_availability_payload,
    help_test_discovery_broken,
    help_test_discovery_removal,
    help_test_discovery_update,
    help_test_discovery_update_attr,
    help_test_entity_debug_info_message,
    help_test_entity_device_info_remove,
    help_test_entity_device_info_update,
    help_test_entity_device_info_with_connection,
    help_test_entity_device_info_with_identifier,
    help_test_entity_id_update_discovery_update,
    help_test_entity_id_update_subscriptions,
    help_test_setting_attribute_via_mqtt_json_message,
    help_test_setting_attribute_with_template,
    help_test_unique_id,
    help_test_update_with_json_attrs_bad_JSON,
    help_test_update_with_json_attrs_not_dict,
)

from tests.common import assert_setup_component, async_fire_mqtt_message
from tests.components.alarm_control_panel import common

CODE_NUMBER = "1234"
CODE_TEXT = "HELLO_CODE"

DEFAULT_CONFIG = {
    alarm_control_panel.DOMAIN: {
        "platform": "mqtt",
        "name": "test",
        "state_topic": "alarm/state",
        "command_topic": "alarm/command",
    }
}

DEFAULT_CONFIG_CODE = {
    alarm_control_panel.DOMAIN: {
        "platform": "mqtt",
        "name": "test",
        "state_topic": "alarm/state",
        "command_topic": "alarm/command",
        "code": "1234",
        "code_arm_required": True,
    }
}

async def test_fail_setup_without_state_topic(hass, mqtt_mock):
    """Test for failing with no state topic."""
    with assert_setup_component(0) as config:
        assert await async_setup_component(
            hass,
            alarm_control_panel.DOMAIN,
            {
                alarm_control_panel.DOMAIN: {
                    "platform": "mqtt",
                    "command_topic": "alarm/command",
                }
            },
        )
        assert not config[alarm_control_panel.DOMAIN]

async def test_fail_setup_without_command_topic(hass, mqtt_mock):
    """Test failing with no command topic."""
    with assert_setup_component(0):
        assert await async_setup_component(
            hass,
            alarm_control_panel.DOMAIN,
            {
                alarm_control_panel.DOMAIN: {
                    "platform": "mqtt",
                    "state_topic": "alarm/state",
                }
            },
        )

async def test_update_state_via_state_topic(hass, mqtt_mock):
    """Test updating with via state topic."""
    assert await async_setup_component(
        hass, alarm_control_panel.DOMAIN, DEFAULT_CONFIG,
    )
    await hass.async_block_till_done()

    entity_id = "alarm_control_panel.test"

    assert hass.states.get(entity_id).state == STATE_UNKNOWN

    for state in (
        STATE_ALARM_DISARMED,
        STATE_ALARM_ARMED_HOME,
        STATE_ALARM_ARMED_AWAY,
        STATE_ALARM_ARMED_NIGHT,
        STATE_ALARM_ARMED_CUSTOM_BYPASS,
        STATE_ALARM_PENDING,
        STATE_ALARM_ARMING,
        STATE_ALARM_DISARMING,
        STATE_ALARM_TRIGGERED,
    ):
        async_fire_mqtt_message(hass, "alarm/state", state)
        assert hass.states.get(entity_id).state == state

async def test_ignore_update_state_if_unknown_via_state_topic(hass, mqtt_mock):
    """Test ignoring updates via state topic."""
    assert await async_setup_component(
        hass, alarm_control_panel.DOMAIN, DEFAULT_CONFIG,
    )
    await hass.async_block_till_done()

    entity_id = "alarm_control_panel.test"

    assert hass.states.get(entity_id).state == STATE_UNKNOWN

    async_fire_mqtt_message(hass, "alarm/state", "unsupported state")
    assert hass.states.get(entity_id).state == STATE_UNKNOWN

async def test_arm_home_publishes_mqtt(hass, mqtt_mock):
    """Test publishing of MQTT messages while armed."""
    assert await async_setup_component(
        hass, alarm_control_panel.DOMAIN, DEFAULT_CONFIG,
    )
    await hass.async_block_till_done()

    await common.async_alarm_arm_home(hass)
    mqtt_mock.async_publish.assert_called_once_with(
        "alarm/command", "ARM_HOME", 0, False
    )

async def test_arm_home_not_publishes_mqtt_with_invalid_code_when_req(hass, mqtt_mock):
    """Test not publishing of MQTT messages with invalid.

    When code_arm_required = True
    """
    assert await async_setup_component(
        hass, alarm_control_panel.DOMAIN, DEFAULT_CONFIG_CODE,
    )

    call_count = mqtt_mock.async_publish.call_count
    await common.async_alarm_arm_home(hass, "abcd")
    assert mqtt_mock.async_publish.call_count == call_count

async def test_arm_home_publishes_mqtt_when_code_not_req(hass, mqtt_mock):
    """Test publishing of MQTT messages.

    When code_arm_required = False
    """
    config = copy.deepcopy(DEFAULT_CONFIG_CODE)
    config[alarm_control_panel.DOMAIN]["code_arm_required"] = False
    assert await async_setup_component(hass, alarm_control_panel.DOMAIN, config,)
    await hass.async_block_till_done()

    await common.async_alarm_arm_home(hass)
    mqtt_mock.async_publish.assert_called_once_with(
        "alarm/command", "ARM_HOME", 0, False
    )

async def test_arm_away_publishes_mqtt(hass, mqtt_mock):
    """Test publishing of MQTT messages while armed."""
    assert await async_setup_component(
        hass, alarm_control_panel.DOMAIN, DEFAULT_CONFIG,
    )
    await hass.async_block_till_done()

    await common.async_alarm_arm_away(hass)
    mqtt_mock.async_publish.assert_called_once_with(
        "alarm/command", "ARM_AWAY", 0, False
    )

async def test_arm_away_not_publishes_mqtt_with_invalid_code_when_req(hass, mqtt_mock):
    """Test not publishing of MQTT messages with invalid code.

    When code_arm_required = True
    """
    assert await async_setup_component(
        hass, alarm_control_panel.DOMAIN, DEFAULT_CONFIG_CODE,
    )

    call_count = mqtt_mock.async_publish.call_count
    await common.async_alarm_arm_away(hass, "abcd")
    assert mqtt_mock.async_publish.call_count == call_count

async def test_arm_away_publishes_mqtt_when_code_not_req(hass, mqtt_mock):
    """Test publishing of MQTT messages.

    When code_arm_required = False
    """
    config = copy.deepcopy(DEFAULT_CONFIG_CODE)
    config[alarm_control_panel.DOMAIN]["code_arm_required"] = False
    assert await async_setup_component(hass, alarm_control_panel.DOMAIN, config,)
    await hass.async_block_till_done()

    await common.async_alarm_arm_away(hass)
    mqtt_mock.async_publish.assert_called_once_with(
        "alarm/command", "ARM_AWAY", 0, False
    )

async def test_arm_night_publishes_mqtt(hass, mqtt_mock):
    """Test publishing of MQTT messages while armed."""
    assert await async_setup_component(
        hass, alarm_control_panel.DOMAIN, DEFAULT_CONFIG,
    )
    await hass.async_block_till_done()

    await common.async_alarm_arm_night(hass)
    mqtt_mock.async_publish.assert_called_once_with(
        "alarm/command", "ARM_NIGHT", 0, False
    )

async def test_arm_night_not_publishes_mqtt_with_invalid_code_when_req(hass, mqtt_mock):
    """Test not publishing of MQTT messages with invalid code.

    When code_arm_required = True
    """
    assert await async_setup_component(
        hass, alarm_control_panel.DOMAIN, DEFAULT_CONFIG_CODE,
    )

    call_count = mqtt_mock.async_publish.call_count
    await common.async_alarm_arm_night(hass, "abcd")
    assert mqtt_mock.async_publish.call_count == call_count

async def test_arm_night_publishes_mqtt_when_code_not_req(hass, mqtt_mock):
    """Test publishing of MQTT messages.

    When code_arm_required = False
    """
    config = copy.deepcopy(DEFAULT_CONFIG_CODE)
    config[alarm_control_panel.DOMAIN]["code_arm_required"] = False
    assert await async_setup_component(hass, alarm_control_panel.DOMAIN, config,)
    await hass.async_block_till_done()

    await common.async_alarm_arm_night(hass)
    mqtt_mock.async_publish.assert_called_once_with(
        "alarm/command", "ARM_NIGHT", 0, False
    )

async def test_arm_custom_bypass_publishes_mqtt(hass, mqtt_mock):
    """Test publishing of MQTT messages while armed."""
    assert await async_setup_component(
        hass,
        alarm_control_panel.DOMAIN,
        {
            alarm_control_panel.DOMAIN: {
                "platform": "mqtt",
                "name": "test",
                "state_topic": "alarm/state",
                "command_topic": "alarm/command",
            }
        },
    )
    await hass.async_block_till_done()

    await common.async_alarm_arm_custom_bypass(hass)
    mqtt_mock.async_publish.assert_called_once_with(
        "alarm/command", "ARM_CUSTOM_BYPASS", 0, False
    )

async def test_arm_custom_bypass_not_publishes_mqtt_with_invalid_code_when_req(
    hass, mqtt_mock
):
    """Test not publishing of MQTT messages with invalid code.

    When code_arm_required = True
    """
    assert await async_setup_component(
        hass,
        alarm_control_panel.DOMAIN,
        {
            alarm_control_panel.DOMAIN: {
                "platform": "mqtt",
                "name": "test",
                "state_topic": "alarm/state",
                "command_topic": "alarm/command",
                "code": "1234",
                "code_arm_required": True,
            }
        },
    )
    await hass.async_block_till_done()

    call_count = mqtt_mock.async_publish.call_count
    await common.async_alarm_arm_custom_bypass(hass, "abcd")
    assert mqtt_mock.async_publish.call_count == call_count

async def test_arm_custom_bypass_publishes_mqtt_when_code_not_req(hass, mqtt_mock):
    """Test publishing of MQTT messages.

    When code_arm_required = False
    """
    assert await async_setup_component(
        hass,
        alarm_control_panel.DOMAIN,
        {
            alarm_control_panel.DOMAIN: {
                "platform": "mqtt",
                "name": "test",
                "state_topic": "alarm/state",
                "command_topic": "alarm/command",
                "code": "1234",
                "code_arm_required": False,
            }
        },
    )
    await hass.async_block_till_done()

    await common.async_alarm_arm_custom_bypass(hass)
    mqtt_mock.async_publish.assert_called_once_with(
        "alarm/command", "ARM_CUSTOM_BYPASS", 0, False
    )

async def test_disarm_publishes_mqtt(hass, mqtt_mock):
    """Test publishing of MQTT messages while disarmed."""
    assert await async_setup_component(
        hass, alarm_control_panel.DOMAIN, DEFAULT_CONFIG,
    )
    await hass.async_block_till_done()

    await common.async_alarm_disarm(hass)
    mqtt_mock.async_publish.assert_called_once_with("alarm/command", "DISARM", 0, False)

async def test_disarm_publishes_mqtt_with_template(hass, mqtt_mock):
    """Test publishing of MQTT messages while disarmed.

    When command_template set to output json
    """
    config = copy.deepcopy(DEFAULT_CONFIG_CODE)
    config[alarm_control_panel.DOMAIN]["code"] = "1234"
    config[alarm_control_panel.DOMAIN]["command_template"] = (
        '{"action":"{{ action }}",' '"code":"{{ code }}"}'
    )
    assert await async_setup_component(hass, alarm_control_panel.DOMAIN, config,)
    await hass.async_block_till_done()

    await common.async_alarm_disarm(hass, 1234)
    mqtt_mock.async_publish.assert_called_once_with(
        "alarm/command", '{"action":"DISARM","code":"1234"}', 0, False
    )

async def test_disarm_publishes_mqtt_when_code_not_req(hass, mqtt_mock):
    """Test publishing of MQTT messages while disarmed.

    When code_disarm_required = False
    """
    config = copy.deepcopy(DEFAULT_CONFIG_CODE)
    config[alarm_control_panel.DOMAIN]["code"] = "1234"
    config[alarm_control_panel.DOMAIN]["code_disarm_required"] = False
    assert await async_setup_component(hass, alarm_control_panel.DOMAIN, config,)
    await hass.async_block_till_done()

    await common.async_alarm_disarm(hass)
    mqtt_mock.async_publish.assert_called_once_with("alarm/command", "DISARM", 0, False)

async def test_disarm_not_publishes_mqtt_with_invalid_code_when_req(hass, mqtt_mock):
    """Test not publishing of MQTT messages with invalid code.

    When code_disarm_required = True
    """
    assert await async_setup_component(
        hass, alarm_control_panel.DOMAIN, DEFAULT_CONFIG_CODE,
    )

    call_count = mqtt_mock.async_publish.call_count
    await common.async_alarm_disarm(hass, "abcd")
    assert mqtt_mock.async_publish.call_count == call_count

async def test_update_state_via_state_topic_template(hass, mqtt_mock):
    """Test updating with template_value via state topic."""
    assert await async_setup_component(
        hass,
        alarm_control_panel.DOMAIN,
        {
            alarm_control_panel.DOMAIN: {
                "platform": "mqtt",
                "name": "test",
                "command_topic": "test-topic",
                "state_topic": "test-topic",
                "value_template": "\
                {% if (value | int)  == 100 %}\
                  armed_away\
                {% else %}\
                   disarmed\
                {% endif %}",
            }
        },
    )
    await hass.async_block_till_done()

    state = hass.states.get("alarm_control_panel.test")
    assert state.state == STATE_UNKNOWN

    async_fire_mqtt_message(hass, "test-topic", "100")

    state = hass.states.get("alarm_control_panel.test")
    assert state.state == STATE_ALARM_ARMED_AWAY

async def test_attributes_code_number(hass, mqtt_mock):
    """Test attributes which are not supported by the vacuum."""
    config = copy.deepcopy(DEFAULT_CONFIG)
    config[alarm_control_panel.DOMAIN]["code"] = CODE_NUMBER

    assert await async_setup_component(hass, alarm_control_panel.DOMAIN, config)
    await hass.async_block_till_done()

    state = hass.states.get("alarm_control_panel.test")
    assert (
        state.attributes.get(alarm_control_panel.ATTR_CODE_FORMAT)
        == alarm_control_panel.FORMAT_NUMBER
    )

async def test_attributes_code_text(hass, mqtt_mock):
    """Test attributes which are not supported by the vacuum."""
    config = copy.deepcopy(DEFAULT_CONFIG)
    config[alarm_control_panel.DOMAIN]["code"] = CODE_TEXT

    assert await async_setup_component(hass, alarm_control_panel.DOMAIN, config)
    await hass.async_block_till_done()

    state = hass.states.get("alarm_control_panel.test")
    assert (
        state.attributes.get(alarm_control_panel.ATTR_CODE_FORMAT)
        == alarm_control_panel.FORMAT_TEXT
    )

async def test_availability_when_connection_lost(hass, mqtt_mock):
    """Test availability after MQTT disconnection."""
    await help_test_availability_when_connection_lost(
        hass, mqtt_mock, alarm_control_panel.DOMAIN, DEFAULT_CONFIG_CODE
    )

async def test_availability_without_topic(hass, mqtt_mock):
    """Test availability without defined availability topic."""
    await help_test_availability_without_topic(
        hass, mqtt_mock, alarm_control_panel.DOMAIN, DEFAULT_CONFIG_CODE
    )

async def test_default_availability_payload(hass, mqtt_mock):
    """Test availability by default payload with defined topic."""
    await help_test_default_availability_payload(
        hass, mqtt_mock, alarm_control_panel.DOMAIN, DEFAULT_CONFIG_CODE
    )

async def test_custom_availability_payload(hass, mqtt_mock):
    """Test availability by custom payload with defined topic."""
    await help_test_custom_availability_payload(
        hass, mqtt_mock, alarm_control_panel.DOMAIN, DEFAULT_CONFIG_CODE
    )

async def test_setting_attribute_via_mqtt_json_message(hass, mqtt_mock):
    """Test the setting of attribute via MQTT with JSON payload."""
    await help_test_setting_attribute_via_mqtt_json_message(
        hass, mqtt_mock, alarm_control_panel.DOMAIN, DEFAULT_CONFIG
    )

async def test_setting_attribute_with_template(hass, mqtt_mock):
    """Test the setting of attribute via MQTT with JSON payload."""
    await help_test_setting_attribute_with_template(
        hass, mqtt_mock, alarm_control_panel.DOMAIN, DEFAULT_CONFIG
    )

async def test_update_with_json_attrs_not_dict(hass, mqtt_mock, caplog):
    """Test attributes get extracted from a JSON result."""
    await help_test_update_with_json_attrs_not_dict(
        hass, mqtt_mock, caplog, alarm_control_panel.DOMAIN, DEFAULT_CONFIG
    )

async def test_update_with_json_attrs_bad_JSON(hass, mqtt_mock, caplog):
    """Test attributes get extracted from a JSON result."""
    await help_test_update_with_json_attrs_bad_JSON(
        hass, mqtt_mock, caplog, alarm_control_panel.DOMAIN, DEFAULT_CONFIG
    )

async def test_discovery_update_attr(hass, mqtt_mock, caplog):
    """Test update of discovered MQTTAttributes."""
    await help_test_discovery_update_attr(
        hass, mqtt_mock, caplog, alarm_control_panel.DOMAIN, DEFAULT_CONFIG
    )

async def test_unique_id(hass, mqtt_mock):
    """Test unique id option only creates one alarm per unique_id."""
    config = {
        alarm_control_panel.DOMAIN: [
            {
                "platform": "mqtt",
                "name": "Test 1",
                "state_topic": "test-topic",
                "command_topic": "command-topic",
                "unique_id": "TOTALLY_UNIQUE",
            },
            {
                "platform": "mqtt",
                "name": "Test 2",
                "state_topic": "test-topic",
                "command_topic": "command-topic",
                "unique_id": "TOTALLY_UNIQUE",
            },
        ]
    }
    await help_test_unique_id(hass, mqtt_mock, alarm_control_panel.DOMAIN, config)

async def test_discovery_removal_alarm(hass, mqtt_mock, caplog):
    """Test removal of discovered alarm_control_panel."""
    data = json.dumps(DEFAULT_CONFIG[alarm_control_panel.DOMAIN])
    await help_test_discovery_removal(
        hass, mqtt_mock, caplog, alarm_control_panel.DOMAIN, data
    )

async def test_discovery_update_alarm(hass, mqtt_mock, caplog):
    """Test update of discovered alarm_control_panel."""
    config1 = copy.deepcopy(DEFAULT_CONFIG[alarm_control_panel.DOMAIN])
    config2 = copy.deepcopy(DEFAULT_CONFIG[alarm_control_panel.DOMAIN])
    config1["name"] = "Beer"
    config2["name"] = "Milk"

    data1 = json.dumps(config1)
    data2 = json.dumps(config2)
    await help_test_discovery_update(
        hass, mqtt_mock, caplog, alarm_control_panel.DOMAIN, data1, data2
    )

@pytest.mark.no_fail_on_log_exception
async def test_discovery_broken(hass, mqtt_mock, caplog):
    """Test handling of bad discovery message."""
    data1 = '{ "name": "Beer" }'
    data2 = (
        '{ "name": "Milk",'
        '  "state_topic": "test_topic",'
        '  "command_topic": "test_topic" }'
    )
    await help_test_discovery_broken(
        hass, mqtt_mock, caplog, alarm_control_panel.DOMAIN, data1, data2
    )

async def test_entity_device_info_with_connection(hass, mqtt_mock):
    """Test MQTT alarm control panel device registry integration."""
    await help_test_entity_device_info_with_connection(
        hass, mqtt_mock, alarm_control_panel.DOMAIN, DEFAULT_CONFIG
    )

async def test_entity_device_info_with_identifier(hass, mqtt_mock):
    """Test MQTT alarm control panel device registry integration."""
    await help_test_entity_device_info_with_identifier(
        hass, mqtt_mock, alarm_control_panel.DOMAIN, DEFAULT_CONFIG
    )

async def test_entity_device_info_update(hass, mqtt_mock):
    """Test device registry update."""
    await help_test_entity_device_info_update(
        hass, mqtt_mock, alarm_control_panel.DOMAIN, DEFAULT_CONFIG
    )

async def test_entity_device_info_remove(hass, mqtt_mock):
    """Test device registry remove."""
    await help_test_entity_device_info_remove(
        hass, mqtt_mock, alarm_control_panel.DOMAIN, DEFAULT_CONFIG
    )

async def test_entity_id_update_subscriptions(hass, mqtt_mock):
    """Test MQTT subscriptions are managed when entity_id is updated."""
    await help_test_entity_id_update_subscriptions(
        hass, mqtt_mock, alarm_control_panel.DOMAIN, DEFAULT_CONFIG
    )

async def test_entity_id_update_discovery_update(hass, mqtt_mock):
    """Test MQTT discovery update when entity_id is updated."""
    await help_test_entity_id_update_discovery_update(
        hass, mqtt_mock, alarm_control_panel.DOMAIN, DEFAULT_CONFIG
    )

async def test_entity_debug_info_message(hass, mqtt_mock):
    """Test MQTT debug info."""
    await help_test_entity_debug_info_message(
        hass, mqtt_mock, alarm_control_panel.DOMAIN, DEFAULT_CONFIG
    )

redpajama_set_name: RedPajamaGithub


text:
package sk.badand.beehive.gui.queen;

import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.Initializable;

/**
 * FXML Controller class
 *
 * @author abadinka
 */
public class QueenPresenter implements Initializable {

    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO
    }

}


text:
export type HttpMethod = 'get'|'post'|'put'|'patch'|'delete';

export type Url = string;

export type PhoneNumber = string;

export type Sid = string;

export interface ListEachOptions<TInstance> {
  /**
   * Upper limit for the number of records to return.
   * each() guarantees never to return more than limit.
   * Default is no limit
   */
  limit?: number;
  /**
   * Number of records to fetch per request,
   * when not set will use the default value of 50 records.
   * If no pageSize is defined but a limit is defined,
   * each() will attempt to read the limit with the most efficient
   * page size, i.e. min(limit, 1000)
   */
  pageSize?: number;
  /**
   * Function to process each record. If this and a positional
   * callback are passed, this one will be used
   */
  callback?: (item: TInstance, done: (err?: Error) => void) => void;
  /**
   * Function to be called upon completion of streaming
   */
  done?: (err?: Error) => void;
}

export interface ListOptions<TInstance> {
  /**
   * Upper limit for the number of records to return.
   * each() guarantees never to return more than limit.
   * Default is no limit
   */
  limit?: number;
  /**
   * Number of records to fetch per request,
   * when not set will use the default value of 50 records.
   * If no pageSize is defined but a limit is defined,
   * each() will attempt to read the limit with the most efficient
   * page size, i.e. min(limit, 1000)
   */
  pageSize?: number;
  /**
   * Callback to handle list of records
   */
  callback?: (items: TInstance[]) => void;
}

export interface PageOptions<TPage> {
  /**
   * PageToken provided by the API
   */
  pageToken?: string;
  /**
   * Page Number, this value is simply for client state
   */
  pageNumber?: number;
  /**
   * Number of records to return, defaults to 50
   */
  pageSize?: number;
  /**
   * Callback to handle list of records
   */
  callback?: (page: TPage) => void;
}

/**
 * A generic type that returns all property names of a class whose type is not "function"
 */
export type NonFunctionPropertyNames<T> = {
  [K in keyof T]: T[K] extends Function ? never : K;
}[keyof T];

/**
 * A generic type that returns only properties of a class that are not functions
 */
export type NonFunctionProperties<T> = Pick<T, NonFunctionPropertyNames<T>>;

/**
 * A type alias for better readibility
 */
export type Json<T> = NonFunctionProperties<T>;

export declare class SerializableClass {
  /**
   * Converts the current instance in a regular JSON.
   * It will be automatically called by JSON.stringify()
   */
  toJSON(): Json<this>;
}


text:
package org.apache.river.mercury.proxy;

import java.io.PrintStream;
import java.io.PrintWriter;

/**
 * This exception denotes a problem with the local implementation of the
 * EventMailbox interface.  The detail field
 * will give a description that can be reported to the mailbox developer
 * (and may be documented in that mailbox's external documentation).
 *
 * @author Sun Microsystems, Inc.
 *
 * @since 1.1
 */
public class InternalMailboxException extends RuntimeException {

    private static final long serialVersionUID = 1L;

    /**
     * The exception (if any) that triggered the internal exception.  This
     * field may be null.
     *
     * @serial
     */
    public final Throwable nestedException;

    /**
     * Create an exception, passing the string to the superclass'
     * constructor. The nested exception will be null.
     * @param str message detail.
     */
    public InternalMailboxException(String str) {
	super(str);
	nestedException = null;
    }

    /**
     * Create an exception, passing the string to the superclass'
     * constructor. The nested exception will be set to the provided
     * <tt>Throwable</tt> argument.
     * @param str message detail
     * @param ex the cause.
     */
    public InternalMailboxException(String str, Throwable ex) {
	super(str, ex);
	nestedException = ex;
    }

    /**
     * Print the stack trace of this exception and that of the nested
     * exception, if any.
     */
    public void printStackTrace() {
	printStackTrace(System.err);
    }

    /**
     * Print the stack trace of this exception and that of the nested
     * exception, if any.
     */
    public void printStackTrace(PrintStream out) {
	super.printStackTrace(out);
	if (nestedException != null) {
	    out.println("nested exception:");
	    nestedException.printStackTrace(out);
	}
    }

    /**
     * Print the stack trace of this exception and that of the nested
     * exception, if any.
     */
    public void printStackTrace(PrintWriter out) {
	super.printStackTrace(out);
	if (nestedException != null) {
	    out.println("nested exception:");
	    nestedException.printStackTrace(out);
	}
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>RodentBot</groupId>
  <artifactId>RodentBot</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.0</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencyManagement>
  	<dependencies>
  		<dependency>
  			<groupId>org.pircbotx</groupId>
  			<artifactId>pircbotx</artifactId>
  			<version>2.1</version>
  		</dependency>
  	</dependencies>
  </dependencyManagement>
  <dependencies>
  	<dependency>
  		<groupId>org.pircbotx</groupId>
  		<artifactId>pircbotx</artifactId>
  		<version>2.1</version>
  	</dependency>
  </dependencies>
</project>


text:
#ifndef __LINUX_SEQNO_FENCE_H
#define __LINUX_SEQNO_FENCE_H

#include <linux/fence.h>
#include <linux/dma-buf.h>

enum seqno_fence_condition {
	SEQNO_FENCE_WAIT_GEQUAL,
	SEQNO_FENCE_WAIT_NONZERO
};

struct seqno_fence {
	struct fence base;

	const struct fence_ops *ops;
	struct dma_buf *sync_buf;
	uint32_t seqno_ofs;
	enum seqno_fence_condition condition;
};

extern const struct fence_ops seqno_fence_ops;

/**
 * to_seqno_fence - cast a fence to a seqno_fence
 * @fence: fence to cast to a seqno_fence
 *
 * Returns NULL if the fence is not a seqno_fence,
 * or the seqno_fence otherwise.
 */
static inline struct seqno_fence *
to_seqno_fence(struct fence *fence)
{
	if (fence->ops != &seqno_fence_ops)
		return NULL;
	return container_of(fence, struct seqno_fence, base);
}

/**
 * seqno_fence_init - initialize a seqno fence
 * @fence: seqno_fence to initialize
 * @lock: pointer to spinlock to use for fence
 * @sync_buf: buffer containing the memory location to signal on
 * @context: the execution context this fence is a part of
 * @seqno_ofs: the offset within @sync_buf
 * @seqno: the sequence # to signal on
 * @cond: fence wait condition
 * @ops: the fence_ops for operations on this seqno fence
 *
 * This function initializes a struct seqno_fence with passed parameters,
 * and takes a reference on sync_buf which is released on fence destruction.
 *
 * A seqno_fence is a dma_fence which can complete in software when
 * enable_signaling is called, but it also completes when
 * (s32)((sync_buf)[seqno_ofs] - seqno) >= 0 is true
 *
 * The seqno_fence will take a refcount on the sync_buf until it's
 * destroyed, but actual lifetime of sync_buf may be longer if one of the
 * callers take a reference to it.
 *
 * Certain hardware have instructions to insert this type of wait condition
 * in the command stream, so no intervention from software would be needed.
 * This type of fence can be destroyed before completed, however a reference
 * on the sync_buf dma-buf can be taken. It is encouraged to re-use the same
 * dma-buf for sync_buf, since mapping or unmapping the sync_buf to the
 * device's vm can be expensive.
 *
 * It is recommended for creators of seqno_fence to call fence_signal
 * before destruction. This will prevent possible issues from wraparound at
 * time of issue vs time of check, since users can check fence_is_signaled
 * before submitting instructions for the hardware to wait on the fence.
 * However, when ops.enable_signaling is not called, it doesn't have to be
 * done as soon as possible, just before there's any real danger of seqno
 * wraparound.
 */
static inline void
seqno_fence_init(struct seqno_fence *fence, spinlock_t *lock,
		 struct dma_buf *sync_buf,  uint32_t context,
		 uint32_t seqno_ofs, uint32_t seqno,
		 enum seqno_fence_condition cond,
		 const struct fence_ops *ops)
{
	BUG_ON(!fence || !sync_buf || !ops);
	BUG_ON(!ops->wait || !ops->enable_signaling ||
	       !ops->get_driver_name || !ops->get_timeline_name);

	/*
	 * ops is used in fence_init for get_driver_name, so needs to be
	 * initialized first
	 */
	fence->ops = ops;
	fence_init(&fence->base, &seqno_fence_ops, lock, context, seqno);
	get_dma_buf(sync_buf);
	fence->sync_buf = sync_buf;
	fence->seqno_ofs = seqno_ofs;
	fence->condition = cond;
}

#endif /* __LINUX_SEQNO_FENCE_H */


text:
Package.describe({
  name: "telescope:newsletter",
  summary: "Telescope email newsletter package",
  version: "0.24.1",
  git: "https://github.com/TelescopeJS/telescope-newsletter.git"
});

Npm.depends({
  "html-to-text": "1.3.1"
});

Package.onUse(function (api) {

  api.versionsFrom("METEOR@1.0");

  api.use([
    'telescope:core@0.24.0',
    'miro:mailchimp@1.1.0',
  ]);

  api.addFiles([
    'package-tap.i18n',
    'lib/newsletter.js'
  ], ['client', 'server']);

  api.addFiles([
    'lib/client/templates/newsletter_banner.html',
    'lib/client/templates/newsletter_banner.js',
    'lib/client/stylesheets/newsletter_banner.scss'
  ], ['client']);

  api.addFiles([
    'lib/server/campaign.js',
    'lib/server/cron.js',
    'lib/server/mailchimp.js',
    'lib/server/routes.js',
    'lib/server/templates/emailDigest.handlebars',
    'lib/server/templates/emailDigestConfirmation.handlebars',
    'lib/server/templates/emailPostItem.handlebars'
  ], ['server']);

  var languages = ["ar", "bg", "cs", "da", "de", "el", "en", "es", "et", "fr", "hu", "it", "ja", "ko", "nl", "pl", "pt-BR", "ro", "ru", "sv", "th", "tr", "vi", "zh-CN"];
  var languagesPaths = languages.map(function (language) {
    return "i18n/"+language+".i18n.json";
  });
  api.addFiles(languagesPaths, ["client", "server"]);

  api.export([
    'resetNewsletterSchedule'
  ]);
});


text:
class Palette : public IObject {
public:
    virtual const Color& GetColor(int index) = 0;
};

#endif


text:
// Dependencies
var nock = require('nock'),
   solr = require('./../main'),
   vows = require('vows'),
   assert = require('assert'),
   fs = require('fs'),
   mocks = require('./mocks'),
   JSONStream = require('JSONStream'),
   EventEmitter = require('events').EventEmitter;

// Load configuration file
var config = JSON.parse(fs.readFileSync(__dirname + '/config.json'));

/*
if(config.mocked){
   //nock.recorder.rec();
   mocks.createAddStream(nock);
}
*/

if(!config.mocked){

   // Suite Test

   var suite = vows.describe('Solr Client API: createAddStream');

   suite.addBatch({
      'Adding documents through a stream' : {
         topic : function(){
            var promise = new EventEmitter();
            var client = solr.createClient();
            client.autoCommit = true;
            var addStream = client.createAddStream();
            var data = '';
            addStream
               .on('end',function(){
                  promise.emit('success',JSON.parse(data));
               })
               .on('data',function(buffer,encoding){
                  data += buffer.toString(encoding);
               })
               .on('error',function(err){
                  promise.emit('error',err);
               });
            var n = 50;
            for(var i = 0; i < n; i++){
               addStream.write({ id : i , title_t : 'title' + i, test_b : true});
            }
            addStream.end();
            return promise;
         },
         'should works' : function(err,data){
            assert.equal(data.responseHeader.status,0);
            assert.isNull(err);
         }
      }
   }).export(module);

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

     Copyright 2005-2015 Red Hat, Inc.

     Red Hat licenses this file to you under the Apache License, version
     2.0 (the "License"); you may not use this file except in compliance
     with the License.  You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
     implied.  See the License for the specific language governing
     permissions and limitations under the License.

-->
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <groupId>io.fabric8.examples</groupId>
  <artifactId>example-camel-cdi</artifactId>
  <version>1.0-SNAPSHOT</version>
  <name>Example : Camel CDI</name>
  <description>Camel route using CDI in a standalone Java Container</description>
  <properties>
    <fabric8.label.container>java</fabric8.label.container>
    <fabric8.iconRef>icons/camel.svg</fabric8.iconRef>
    <version.maven-bundle-plugin>2.3.7</version.maven-bundle-plugin>
    <docker.registryPrefix></docker.registryPrefix>
    <fabric8.maven.plugin.version>3.2.9</fabric8.maven.plugin.version>

    <skipTests>false</skipTests>
    <testExclusionPattern>**/*KubernetesTest.java</testExclusionPattern>

    <docker.image>${docker.registryPrefix}fabric8/${project.artifactId}:${project.version}</docker.image>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.source>1.8</maven.compiler.source>
    <docker.from>fabric8/java</docker.from>
    <docker.port.container.jolokia>8778</docker.port.container.jolokia>
    <fabric8.label.group>quickstarts</fabric8.label.group>
    <camel.version>2.18.1</camel.version>
    <docker.env.MAIN>org.apache.camel.cdi.Main</docker.env.MAIN>
    <version.compiler.plugin>2.3.1</version.compiler.plugin>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <docker.assemblyDescriptorRef>artifact-with-dependencies</docker.assemblyDescriptorRef>
  </properties>
  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.apache.camel</groupId>
        <artifactId>camel-netty4-http</artifactId>
        <version>${camel.version}</version>
      </dependency>
    </dependencies>
  </dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>org.apache.camel</groupId>
      <artifactId>camel-cdi</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.geronimo.specs</groupId>
      <artifactId>geronimo-ejb_3.1_spec</artifactId>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.jboss.weld.se</groupId>
      <artifactId>weld-se</artifactId>
    </dependency>
    <dependency>
      <groupId>org.jboss.weld.servlet</groupId>
      <artifactId>weld-servlet</artifactId>
    </dependency>
    <dependency>
      <groupId>org.jboss.weld</groupId>
      <artifactId>weld-core</artifactId>
    </dependency>
    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.deltaspike.cdictrl</groupId>
      <artifactId>deltaspike-cdictrl-weld</artifactId>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.camel</groupId>
      <artifactId>camel-netty4-http</artifactId>
    </dependency>

    <!-- testing -->
    <dependency>
      <groupId>io.fabric8</groupId>
      <artifactId>fabric8-arquillian</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.jboss.arquillian.junit</groupId>
      <artifactId>arquillian-junit-container</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.jboss.shrinkwrap.resolver</groupId>
      <artifactId>shrinkwrap-resolver-impl-maven</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <resources>
      <resource>
        <filtering>true</filtering>
        <directory>src/main/resources</directory>
      </resource>
    </resources>
    <finalName>${project.artifactId}</finalName>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>${version.compiler.plugin}</version>
        <configuration>
          <source>${maven.compiler.source}</source>
          <target>${maven.compiler.target}</target>
        </configuration>
      </plugin>
      <plugin>
        <groupId>io.fabric8</groupId>
        <artifactId>fabric8-maven-plugin</artifactId>
        <version>${fabric8.maven.plugin.version}</version>
        <executions>
          <execution>
            <id>json</id>
            <goals>
              <goal>json</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>exec-maven-plugin</artifactId>
        <version>1.4.0</version>
        <configuration>
          <mainClass>org.apache.camel.cdi.Main</mainClass>
          <includePluginDependencies>false</includePluginDependencies>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.camel</groupId>
        <artifactId>camel-maven-plugin</artifactId>
        <version>${camel.version}</version>
        <configuration>
          <useCDI>true</useCDI>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>${maven.surefire.plugin.version}</version>
        <inherited>true</inherited>
        <configuration>
          <skipTests>${skipTests}</skipTests>
          <excludes>
            <exclude>${testExclusionPattern}</exclude>
          </excludes>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <profiles>
    <profile>
      <id>docker-public</id>
      <properties>
        <docker.registryPrefix></docker.registryPrefix>
      </properties>
    </profile>
    <profile>
        <id>ts.kube</id>
        <properties>
            <testExclusionPattern>**/*ExcludedTest.java</testExclusionPattern>
        </properties>
    </profile>
  </profiles>
</project>


text:
package org.apache.drill.exec.store.hbase.config;

import static org.apache.drill.exec.store.hbase.config.HBasePStoreProvider.FAMILY;
import static org.apache.drill.exec.store.hbase.config.HBasePStoreProvider.FAMILY_BLOB;
import static org.apache.drill.exec.store.hbase.config.HBasePStoreProvider.QUALIFIER;

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

import org.apache.drill.common.exceptions.DrillRuntimeException;
import org.apache.drill.exec.store.sys.PStore;
import org.apache.drill.exec.store.sys.PStoreConfig;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HTableInterface;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.util.Bytes;

public class HBasePStore<V> implements PStore<V> {
  static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(HBasePStore.class);

  private final PStoreConfig<V> config;

  private final HTableInterface table;

  private final String tableName;
  private final byte[] tableNameStartKey;
  private final byte[] tableNameStopKey;

  public HBasePStore(PStoreConfig<V> config, HTableInterface table) throws IOException {
    this.tableName = config.getName() + '\0';
    this.tableNameStartKey = Bytes.toBytes(tableName); // "tableName\x00"
    this.tableNameStopKey = this.tableNameStartKey.clone();
    this.tableNameStopKey[tableNameStartKey.length-1] = 1;
    this.config = config;
    this.table = table;
  }

  @Override
  public V get(String key) {
    return get(key, FAMILY);
  }

  @Override
  public V getBlob(String key) {
    return get(key, FAMILY_BLOB);
  }

  protected synchronized V get(String key, byte[] family) {
    try {
      Get get = new Get(row(key));
      get.addColumn(family, QUALIFIER);
      return value(table.get(get));
    } catch (IOException e) {
      throw new DrillRuntimeException("Caught error while getting row '" + key + "' from for table:" + Bytes.toString(table.getTableName()), e);
    }
  }

  @Override
  public void put(String key, V value) {
    put(key, FAMILY, value);
  }

  @Override
  public void putBlob(String key, V value) {
    put(key, FAMILY_BLOB, value);
  }

  protected synchronized void put(String key, byte[] family, V value) {
    try {
      Put put = new Put(row(key));
      put.add(family, QUALIFIER, bytes(value));
      table.put(put);
    } catch (IOException e) {
      throw new DrillRuntimeException("Caught error while putting row '" + key + "' from for table:" + Bytes.toString(table.getTableName()), e);
    }
  }

  @Override
  public synchronized boolean putIfAbsent(String key, V value) {
    try {
      Put put = new Put(row(key));
      put.add(FAMILY, QUALIFIER, bytes(value));
      return table.checkAndPut(put.getRow(), FAMILY, QUALIFIER, null /*absent*/, put);
    } catch (IOException e) {
      throw new DrillRuntimeException("Caught error while putting row '" + key + "' from for table:" + Bytes.toString(table.getTableName()), e);
    }
  }

  @Override
  public synchronized void delete(String key) {
    delete(row(key));
  }

  @Override
  public Iterator<Entry<String, V>> iterator() {
    return new Iter();
  }

  private byte[] row(String key) {
    return Bytes.toBytes(this.tableName + key);
  }

  private byte[] bytes(V value) {
    try {
      return config.getSerializer().serialize(value);
    } catch (IOException e) {
      throw new DrillRuntimeException(e);
    }
  }

  private V value(Result result) {
    try {
      return config.getSerializer().deserialize(result.value());
    } catch (IOException e) {
      throw new DrillRuntimeException(e);
    }
  }

  private void delete(byte[] row) {
    try {
      Delete del = new Delete(row);
      table.delete(del);
    } catch (IOException e) {
      throw new DrillRuntimeException("Caught error while deleting row '" + Bytes.toStringBinary(row)
          + "' from for table:" + Bytes.toString(table.getTableName()), e);
    }
  }

  private class Iter implements Iterator<Entry<String, V>> {
    private ResultScanner scanner;
    private Result current = null;
    private Result last = null;
    private boolean done = false;

    Iter() {
      try {
        Scan scan = new Scan(tableNameStartKey, tableNameStopKey);
        scan.addColumn(FAMILY, QUALIFIER);
        scan.setCaching(100);
        scanner = table.getScanner(scan);
      } catch (IOException e) {
        throw new DrillRuntimeException("Caught error while creating HBase scanner for table:" + Bytes.toString(table.getTableName()), e);
      }
    }

    @Override
    public boolean hasNext()  {
      if (!done && current == null) {
        try {
          if ((current = scanner.next()) == null) {
            done = true;
            scanner.close();
          }
        } catch (IOException e) {
          throw new DrillRuntimeException("Caught error while fetching rows from for table:" + Bytes.toString(table.getTableName()), e);
        }
      }
      return (current != null);
    }

    @Override
    public Entry<String, V> next() {
      if (!hasNext()) {
        throw new NoSuchElementException();
      }
      last = current;
      current = null;
      return new DeferredEntry(last);
    }

    @Override
    public void remove() {
      if (last == null) {
        throw new IllegalStateException("remove() called on HBase persistent store iterator, but there is no last row.");
      }
      delete(last.getRow());
    }

  }

  private class DeferredEntry implements Entry<String, V>{

    private Result result;

    public DeferredEntry(Result result) {
      super();
      this.result = result;
    }

    @Override
    public String getKey() {
      return Bytes.toString(result.getRow(), tableNameStartKey.length, result.getRow().length-tableNameStartKey.length);
    }

    @Override
    public V getValue() {
      return value(result);
    }

    @Override
    public V setValue(V value) {
      throw new UnsupportedOperationException();
    }

  }

}


text:
class CreateCountries < ActiveRecord::Migration
  def change
    create_table :countries do |t|
      t.string :name
      t.string :iso_code
      t.integer :dial_code
      t.boolean :is_active, default: true, null: false
      t.timestamps null: false
    end
  end
end


text:
package com.sunny.grokkingalgorithms.fasttrack.week3;

import java.lang.management.ManagementFactory;

class myTask implements Runnable{

  @Override
  public void run() {
    long start = System.currentTimeMillis();
    String str = "test";
    for(int i = 0 ; i < 20000 ; i++){
      str += i;
    }
    System.out.println(str);
    long end = System.currentTimeMillis();
    System.out.println(Thread.currentThread().getName() + " " + (end - start) + " Wmillsecs");
  }
}
/**
 * Created by sundas on 7/6/2018.
 */
public class FindFastestThread {

  /*
  Find fastest thread
   */

  /**
   *
   * @param args
   */
  public static void main(String[] args) {
    Thread t1 = new Thread(new myTask());
    Thread t2 = new Thread(new myTask());
    Thread t3 = new Thread(new myTask());
    /*long time1 = ManagementFactory.getThreadMXBean().getThreadCpuTime(t1.getId());
    long time2 = ManagementFactory.getThreadMXBean().getThreadCpuTime(t2.getId());
    long time3 = ManagementFactory.getThreadMXBean().getThreadCpuTime(t3.getId());
    System.out.println(Math.max(Math.max(time1,time2),time3));*/
    t1.start();
    t2.start();
    t3.start();
  }

}


text:
set -e

GRAPHS_DIR=${1:-~/graphs}
NEO4J_DIR=${2:-~/neo4j}
IMPLEMENTATION=${3:-algolib}

PROJECT=graphalytics-1.0.0-neo4j-0.1-SNAPSHOT

rm -rf $PROJECT
mvn package -DskipTests
tar xf $PROJECT-bin.tar.gz
cd $PROJECT/
cp -r config-template config
sed -i "s|^graphs.root-directory =$|graphs.root-directory = $GRAPHS_DIR|g" config/benchmark.properties
sed -i "s|^graphs.validation-directory =$|graphs.validation-directory = $GRAPHS_DIR|g" config/benchmark.properties
sed -i "s|^platform.neo4j.home =$|platform.neo4j.home = $NEO4J_DIR|g" config/platform.properties
sed -i "s|^platform.impl =$|platform.impl = $IMPLEMENTATION|g" config/platform.properties


text:
void PrintControls();
void ReconfigureD6Joint();
int main(int argc, char** argv);

#endif  // LESSON215_H


text:
<?php

namespace ZFTest\JsonLD\Plugin\TestAsset;

class EmbeddedEntityWithCustomIdentifier
{
    public $custom_id;
    public $name;

    public function __construct($id, $name)
    {
        $this->custom_id = $id;
        $this->name      = $name;
    }
}


text:
Spree::Core::Engine.routes.draw do

  namespace :api do
    resources :quick_orders, only: [:show]
  end

end


text:
__author__ = 'Robert Meyer'

import multiprocessing
# Monkey Patch from here: https://bitbucket.org/ned/coveragepy/issue/117/enable-coverage-measurement-of-code-run-by
def coverage_multiprocessing_process(): # pragma: no cover
    try:
        import coverage as _coverage
        _coverage
    except:
        return

    from coverage.collector import Collector
    from coverage import coverage
    # detect if coverage was running in forked process
    if Collector._collectors:
        original = multiprocessing.Process._bootstrap
        class Process_WithCoverage(multiprocessing.Process):
            def _bootstrap(self):
                cov = coverage(data_suffix=True,
                    omit='*/compat.py,*/ptcompat.py,*/pypet/tests/*,*/shareddata.py'.split(','))

                cov.start()
                try:
                    return original(self)
                finally:
                    cov.stop()
                    cov.save()
        return Process_WithCoverage

ProcessCoverage = coverage_multiprocessing_process()
if ProcessCoverage:
    multiprocessing.Process = ProcessCoverage
    print('Added Monkey-Patch for multiprocessing and code-coverage')

import sys
import os

pypetpath=os.path.abspath(os.getcwd())
sys.path.append(pypetpath)
print('Appended path `%s`' % pypetpath)

from pypet.tests.testutils.ioutils import run_suite, discover_tests, TEST_IMPORT_ERROR, parse_args

if __name__ == '__main__':
    opt_dict = parse_args()
    tests_include = set(('TestMPImmediatePostProcLock',
                    'MultiprocFrozenPoolSortQueueTest',
                    'MultiprocFrozenPoolSortPipeTest',
                    'MultiprocLinkNoPoolLockTest',
                    'MultiprocLinkNoPoolQueueTest',
                    'MultiprocLinkQueueTest',
                    'MultiprocPoolSortLocalTest',
                    'MultiprocSCOOPSortLocalTest',
                    'MultiprocFrozenSCOOPSortNetlockTest',
                    'MultiprocFrozenSCOOPSortNetqueueTest',
                    'Brain2NetworkTest',
                    'BrainNetworkTest',
                    'CapTest'))
    pred = lambda class_name, test_name, tags: (class_name in tests_include or
                                                 'multiproc' not in tags)
    suite = discover_tests(pred)
    run_suite(suite=suite, **opt_dict)


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Rhizocarpon distinctum var. protectum H. Magn.

### Remarks
null


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

	<!-- Licensed to the Apache Software Foundation (ASF) under one or more
		contributor license agreements. See the NOTICE file distributed with this
		work for additional information regarding copyright ownership. The ASF licenses
		this file to You under the Apache License, Version 2.0 (the "License"); you
		may not use this file except in compliance with the License. You may obtain
		a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless
		required by applicable law or agreed to in writing, software distributed
		under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
		OR CONDITIONS OF ANY KIND, either express or implied. See the License for
		the specific language governing permissions and limitations under the License. -->

	<parent>
		<groupId>ch.sourcepond</groupId>
		<artifactId>component</artifactId>
		<version>1.0.0-SNAPSHOT</version>
	</parent>
	<modelVersion>4.0.0</modelVersion>
	<groupId>ch.sourcepond.cdi</groupId>
	<artifactId>pax-cdi-nonosgi</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<inceptionYear>2015</inceptionYear>
	<packaging>jar</packaging>
	<description>
		Very simple CDI extension to use OSGi/Pax-CDI bundles in non-OSGi environments.
		Basically, it replaces @OsgiServiceProvier annotations through @Singleton and removes @OsgiService
		from injection points. Currently, the extension does not consider any OSGi filter nor service properties.
	</description>

	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.ops4j.pax.cdi</groupId>
				<artifactId>pax-cdi-openwebbeans</artifactId>
				<type>pom</type>
				<scope>import</scope>
				<version>${pax-cdi-api.version}</version>
			</dependency>
		</dependencies>
	</dependencyManagement>

	<dependencies>
		<dependency>
			<groupId>org.osgi</groupId>
			<artifactId>org.osgi.core</artifactId>
		</dependency>
		<dependency>
			<scope>provided</scope>
			<groupId>javax.enterprise</groupId>
			<artifactId>cdi-api</artifactId>
		</dependency>
		<dependency>
			<groupId>org.ops4j.pax.cdi</groupId>
			<artifactId>pax-cdi-api</artifactId>
		</dependency>

		<!-- Testing -->
		<dependency>
			<groupId>org.apache.openwebbeans</groupId>
			<artifactId>openwebbeans-spi</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.openwebbeans</groupId>
			<artifactId>openwebbeans-impl</artifactId>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>com.coderplus.maven.plugins</groupId>
				<artifactId>copy-rename-maven-plugin</artifactId>
			</plugin>
			<plugin>
				<groupId>org.ops4j.pax.exam</groupId>
				<artifactId>maven-paxexam-plugin</artifactId>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-failsafe-plugin</artifactId>
				<executions>
					<execution>
						<goals>
							<goal>integration-test</goal>
							<goal>verify</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
</project>


text:
package com.hitsoysauce.net.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class MainServer {
	public static void main(String[] args) throws IOException {
		ServerSocket serverSocket = new ServerSocket(4000);

		while(true) {
			Socket socket = serverSocket.accept();

			//启动读写线程
			new ServerInputThread(socket).start();
			new ServerOutputThread(socket).start();
		}
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace GameFramework.Implementation
{
    public abstract class WPGame : Microsoft.Xna.Framework.Game, GameFramework.Game
    {
        #region Fields
        /// <summary>
        /// Parametr 'Screen' - reprezentant klasy abstrakcyjnej odpowiedzialnej za wykonywanie podstawowych
        /// metod dzia³ania gry - aktualizacji, rysowania, zwalniania zasobów i obs³ugi przycisku wstecz.
        /// </summary>
        public Screen Screen { get; set; }

        protected GraphicsDeviceManager device;
        protected SpriteBatch spriteBatch;

        protected Audio audio;
        protected Graphics graphics;
        #endregion
        #region Properties
        /// <summary>
        /// Parametr zwracaj¹cy instacjê implementacji interfejsu Audio.
        /// W frameworku odpowiedzialny za ³adowanie muzyki, dŸwiêku i ich¿e odtwarzanie.
        /// </summary>
        public Audio Audio
        {
            get { return audio; }
        }

        /// <summary>
        /// Parametr zwracaj¹cy instancjê implementacji interfejsu Graphics.
        /// W frameworku odpowiedzialny za ³adowanie obrazów i animacji oraz wyœwietlaniu ich na ekranie.
        /// </summary>
        public Graphics Graphics
        {
            get { return graphics; }
        }
        #endregion
        #region Constructors
        protected WPGame()
        {
            device = new GraphicsDeviceManager(this);
            SetupDevice(device);

            Content.RootDirectory = "Content";

            TargetElapsedTime = TimeSpan.FromTicks(333333);
            InactiveSleepTime = TimeSpan.FromSeconds(1);
            audio = new WPAudio(Content);
        }
        #endregion
        #region Methods
        /// <summary>
        /// Metoda inicjuj¹ca podstawowe parametry XNA.
        /// </summary>
        protected override void Initialize()
        {
            base.Initialize();
        }

        /// <summary>
        /// Metoda wczytuj¹ca zasoby do pamiêci programu.
        /// Wykorzystuje abstrakcyjn¹ metodê 'GetStartScreen'.
        /// </summary>
        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);
            graphics = new WPGraphics(device, spriteBatch, Content);

            Screen = GetStartScreen();
        }

        /// <summary>
        /// Metoda zwalniaj¹ca przydzielane zasoby.
        /// </summary>
        protected override void UnloadContent()
        {
            graphics.Dispose();
            Screen.Dispose();
        }

        /// <summary>
        /// Metoda aktualizuj¹ca stan obiektów na ekranie.
        /// Odpowiada za takie funkcje jak: aktualizacja, pobranie danych I/O.
        /// </summary>
        /// <param name="gameTime">Zrzut informacji opisuj¹cych up³ywaj¹cy czas.</param>
        protected override void Update(GameTime gameTime)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                Screen.Back();

            base.Update(gameTime);
            Screen.Update(gameTime.ElapsedGameTime.Milliseconds);
        }

        /// <summary>
        /// Metoda odpowiedzialna za rysowanie obiektów na ekranie.
        /// </summary>
        /// <param name="gameTime">Zrzut informacji opisuj¹cych up³ywaj¹cy czas.</param>
        protected override void Draw(GameTime gameTime)
        {
            base.Draw(gameTime);
            graphics.Clear(Color.Black);
            spriteBatch.Begin();
            Screen.Draw(gameTime.ElapsedGameTime.Milliseconds);
            spriteBatch.End();
        }
        #endregion
        #region To Implement in derrived class
        /// <summary>
        /// Punkt zaczepny gry.
        /// W celu okreœlenia ekranu pocz¹tkowego nale¿y zaimplementowaæ tê w³¹œnie metodê.
        /// </summary>
        /// <returns></returns>
        public abstract Screen GetStartScreen();

        /// <summary>
        /// Metoda pozwala na konfiguracjê parametrów urz¹dzenia takich jak preferowana szerokoœæ i wysokoœæ ekranu itp.
        /// </summary>
        /// <param name="device">Urz¹dzenie, którego kalibracji nale¿y dokonaæ.</param>
        public abstract void SetupDevice(GraphicsDeviceManager device);
        #endregion
    }
}


text:
layout: layout
title: "Posts"
---

    {% for post in site.posts %}
      {% unless post.draft %}

        {{ post.title }}

      {% endunless %}
    {% endfor %}

Merissa Ramos

Carlsbad, CA 92008

        (760) 562-3782

        merissaramos@gmail.com

Objective

To obtain a position within a company where I can utilize my cultivated knowledge and experience of sales, marketing and operations to grow the organization in a profitable direction.

Education

2003 B.S Creative Marketing - Johnson & Wales University, Providence, R.I.

Work Experience

Digital Marketing Consultant Independent Contractor

6/2015 - Present

        Welk Resort Group

        San Marcos, CA

    Consulting to implement a new division of Online Brand Protection policies and procedures

Working with additional 3rd party vendors to monitor online reputation

Creating measurable policies and standard operating procedures for client to best address online reviews

Administering and managing an internal review platform for existing customer base

Assisting client to overhaul customer service policies to enhance their overall customer satisfaction

Director of Marketing/Co Owner

5/2010 – 7/2013

        AZ Local Farmers Markets

        Scottsdale, AZ

Created, branded and campaigned 3 year round Farmers Markets and an online Delivery Service by creating relationships with local farmers, food vendors and retail partners

Secured brand awareness through Public Relations, specifically built relationships with ABC 15, Arizona Republic, Scottsdale Republic, Scottsdale Airpark News Magazine, AZ Foothills Magazine, Ciao Bella of Phoenix New Times

Developed social networking communities for each farmers market on Facebook, Twitter. Google Plus and Pinterest with content driven marketing

Executed successful email marketing campaigns utilizing Constant Contact

Implemented Google Analytics to our website and delivery service order form to measure and track effectiveness of all marketing campaigns and public relations exposure

Sales & Marketing

10/2008 - 6/2015

        RAMOS I.T., LLC

        Scottsdale, AZ

Successfully generated business through relationship based sales.

Our scope of services included websites, database creation, network administration services, telecommunication and IT services for executive suite office management.

Director of In House Marketing

6/2006 - 10/2009

        Strategic Alliance Marketing

        Scottsdale, AZ

In charge of the In House Marketing departments for the The Legacy Golf Resort in Phoenix, The Orange Tree Golf Resort in Scottsdale and The Desert Rose Resort in Las Vegas.

Recruited, managed and motivated a team of up to 15 marketers at 3 locations which were responsible for booking 200-375 timeshare tours per month

Consistently exceeded budgeted sales and marketing goals while implementing cost effective ways reduce our overhead

Director of Support Services

1/2007 - 5/2009

        Shell Vacations Club

        Phoenix, AZ

        (THIS POSITION HELD SIMULTANEOUSLY WITH ONE ABOVE)

Support services was responsible for customer service, accounting and gifting operation for the Sales Center.

My staff consisted of a team of 12. We worked closely with sales team of 30-50 agents, verification loan department to ensure vacation club members satisfaction with marketing services generated by Strategic Alliance Marketing.

Concierge & Sales Manager

12/2004 - 6/2006

        Scottsdale Resort & Athletic Club

        Scottsdale, AZ

Built the first Concierge department at this resort

Sold banquet events, group room sales, corporate  and individual athletic club memberships, tennis tournament sponsorships and deeded week timeshare.

Concierge Four Seasons Resort Scottsdale at Troon North

2003 - 2004

        Scottsdale, AZ

        (Entry Level Position)

Met and exceeded customers' expectations in accordance with the Four Seasons Philosophy and Culture.

Awarded Employee Of The Month June 2004.


text:
@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    // Stop playback if music is playing.
    if (!TARGET_IPHONE_SIMULATOR) {
        [[MPMusicPlayerController systemMusicPlayer] stop];
        [self cacheMediaItems];
    }

    return YES;
}

- (void) cacheMediaItems {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        MPMediaQuery *songQuery = [MPMediaQuery songsQuery];
        [songQuery items];
        songQuery = nil;
    });
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end


text:
<?php

/**
 * Class Clientobox
 *
 * Dependencies: CURL, json, php>=5.4
 */
class Clientobox
{
    protected $_apiKey = null;
    protected $_clientoBoxUrl = 'https://app.clientobox.ru';
    protected $_maxTimeout = 300;

    /**
     * Set api key on object construct
     *
     * @param string $apiKey
     * @throws Exception
     */
    function __construct($apiKey)
    {
        if (empty($apiKey)) {
            throw new Exception("API key is empty!");
        }
        $this->_apiKey = urlencode($apiKey);
    }

    /**
     * Request data from API
     *
     * @param $controller
     * @param $method
     * @param array $parameters
     * @throws Exception
     * @return string|array
     */
    function exec($controller, $method, array $parameters = array())
    {
        $url = $this->_clientoBoxUrl . "/api/" . urlencode($controller) . "/" . urlencode($method);
        $parameters['api_key'] = $this->_apiKey;
        $data = json_decode($this->_request($url, $parameters), true);
        if (isset($data['error'])) {
            throw new Exception($data['error']);
        }
        return $data;
    }

    protected function _request($url, array $data = array())
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, $this->_maxTimeout);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $out = curl_exec($ch);
        curl_close($ch);
        return $out;
    }
}


text:
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
/**
 * @module ol/TileQueue
 */
import TileState from './TileState.js';
import { listen, unlisten } from './events.js';
import EventType from './events/EventType.js';
import PriorityQueue from './structs/PriorityQueue.js';
/**
 * @typedef {function(import("./Tile.js").default, string, import("./coordinate.js").Coordinate, number): number} PriorityFunction
 */
var TileQueue = /** @class */ (function (_super) {
    __extends(TileQueue, _super);
    /**
     * @param {PriorityFunction} tilePriorityFunction Tile priority function.
     * @param {function(): ?} tileChangeCallback Function called on each tile change event.
     */
    function TileQueue(tilePriorityFunction, tileChangeCallback) {
        var _this = _super.call(this,
        /**
         * @param {Array} element Element.
         * @return {number} Priority.
         */
        function (element) {
            return tilePriorityFunction.apply(null, element);
        },
        /**
         * @param {Array} element Element.
         * @return {string} Key.
         */
        function (element) {
            return ( /** @type {import("./Tile.js").default} */(element[0]).getKey());
        }) || this;
        /**
         * @private
         * @type {function(): ?}
         */
        _this.tileChangeCallback_ = tileChangeCallback;
        /**
         * @private
         * @type {number}
         */
        _this.tilesLoading_ = 0;
        /**
         * @private
         * @type {!Object<string,boolean>}
         */
        _this.tilesLoadingKeys_ = {};
        return _this;
    }
    /**
     * @inheritDoc
     */
    TileQueue.prototype.enqueue = function (element) {
        var added = _super.prototype.enqueue.call(this, element);
        if (added) {
            var tile = element[0];
            listen(tile, EventType.CHANGE, this.handleTileChange, this);
        }
        return added;
    };
    /**
     * @return {number} Number of tiles loading.
     */
    TileQueue.prototype.getTilesLoading = function () {
        return this.tilesLoading_;
    };
    /**
     * @param {import("./events/Event.js").default} event Event.
     * @protected
     */
    TileQueue.prototype.handleTileChange = function (event) {
        var tile = /** @type {import("./Tile.js").default} */ (event.target);
        var state = tile.getState();
        if (tile.hifi && state === TileState.LOADED || state === TileState.ERROR ||
            state === TileState.EMPTY || state === TileState.ABORT) {
            unlisten(tile, EventType.CHANGE, this.handleTileChange, this);
            var tileKey = tile.getKey();
            if (tileKey in this.tilesLoadingKeys_) {
                delete this.tilesLoadingKeys_[tileKey];
                --this.tilesLoading_;
            }
            this.tileChangeCallback_();
        }
    };
    /**
     * @param {number} maxTotalLoading Maximum number tiles to load simultaneously.
     * @param {number} maxNewLoads Maximum number of new tiles to load.
     */
    TileQueue.prototype.loadMoreTiles = function (maxTotalLoading, maxNewLoads) {
        var newLoads = 0;
        var abortedTiles = false;
        var state, tile, tileKey;
        while (this.tilesLoading_ < maxTotalLoading && newLoads < maxNewLoads &&
            this.getCount() > 0) {
            tile = /** @type {import("./Tile.js").default} */ (this.dequeue()[0]);
            tileKey = tile.getKey();
            state = tile.getState();
            if (state === TileState.ABORT) {
                abortedTiles = true;
            }
            else if (state === TileState.IDLE && !(tileKey in this.tilesLoadingKeys_)) {
                this.tilesLoadingKeys_[tileKey] = true;
                ++this.tilesLoading_;
                ++newLoads;
                tile.load();
            }
        }
        if (newLoads === 0 && abortedTiles) {
            // Do not stop the render loop when all wanted tiles were aborted due to
            // a small, saturated tile cache.
            this.tileChangeCallback_();
        }
    };
    return TileQueue;
}(PriorityQueue));
export default TileQueue;
//# sourceMappingURL=TileQueue.js.map


text:
title: undefined method environment for nil:NilClass
date: 2014-04-04 15:19 JST
tags: rails, error
thumb: /images/2014/undefined_method_environment_for_nil_NilClass.png
---

Railsを4.0.4にしたらエラーに遭遇。
`application.css.sass`がおかしいとか言われる。
そんなバカな。

``` ch
NoMethodError - undefined method `environment' for nil:NilClass
  (in /Users/takuyan/rails/scrum/app/assets/stylesheets/application.css.sass):
```

READMORE

ググってみると`sass-rails`と`sprocket`のバージョンの問題ぽい。

[undefined method environment for nil:NilClass when importing Bootstrap](http://stackoverflow.com/questions/22392862/undefined-method-environment-for-nilnilclass-when-importing-bootstrap)

なのでGemfileを書き換えて対応しましょう。

``` ruby
gem 'sass-rails', '~> 4.0.2'
```

で`bundle update sass-rails`と。
とりあえずはこれで何とかなった。

お疲れ様です。


text:
void initAudioFunctions();

SQInteger emoLoadAudio(HSQUIRRELVM v);
SQInteger emoCreateAudioEngine(HSQUIRRELVM v);
SQInteger emoPlayAudioChannel(HSQUIRRELVM v);
SQInteger emoPauseAudioChannel(HSQUIRRELVM v);
SQInteger emoResumeAudioChannel(HSQUIRRELVM v);
SQInteger emoStopAudioChannel(HSQUIRRELVM v);
SQInteger emoSeekAudioChannel(HSQUIRRELVM v);
SQInteger emoCloseAudioChannel(HSQUIRRELVM v);
SQInteger emoCloseAudioEngine(HSQUIRRELVM v);

SQInteger emoGetAudioChannelCount(HSQUIRRELVM v);
SQInteger emoGetAudioChannelVolume(HSQUIRRELVM v);
SQInteger emoSetAudioChannelVolume(HSQUIRRELVM v);
SQInteger emoGetAudioChannelMaxVolume(HSQUIRRELVM v);
SQInteger emoGetAudioChannelMinVolume(HSQUIRRELVM v);

SQInteger emoSetAudioChannelLooping(HSQUIRRELVM v);
SQInteger emoGetAudioChannelLooping(HSQUIRRELVM v);
SQInteger emoGetAudioChannelState(HSQUIRRELVM v);

SQInteger emoAudioVibrate(HSQUIRRELVM v);


text:
package de.ubt.ferbjmon.threadorder.analysis;

public class NoSuchEvenType extends Exception {

	/**
	 *
	 */
	private static final long serialVersionUID = 4132377817480247231L;

	public NoSuchEvenType(String string2) {
		System.err.println("Ein Event vom Typ: " + string2
				+ " ist nicht bekannt!");
	}

}


text:
/* eslint-disable quotes */
module.exports = {
	instadelete: function (bot, message) {
		if (message.channel.id !== '304430648708300800') return;
		message.delete(10000);
	},
	logger: function (bot, message, moment) {
		if (bot.logChannel === undefined) return;
		if (message.channel.id === bot.logLog.id) return;
		if (message.author.id === bot.user.id) return;
		if (bot.logChannelG === true) {
			if (message.guild.id !== bot.logChannel.id) return;
			bot.logLog.send(`**${message.guild.name}** #${message.channel.name} *${message.author.tag}* at ${moment(message.createdTimestamp).format('h:mm:ss a')}\n ${message.content}`);
		}
		if (bot.logChannelG === false) {
			if (message.channel.id !== bot.logChannel.id) return;
			bot.logLog.send(`**${message.guild.name}** #${message.channel.name} *${message.author.tag}* at ${moment(message.createdTimestamp).format('h:mm:ss a')}\n ${message.content}`);
		}
	},
	levels: function(bot, message, sql, config) {
		if (message.author.bot) return;
		if (message.channel.type != 'text') return;
		if (message.channel.id == '304429222477299712') return;
		sql.get(`SELECT * FROM guildOptions WHERE guildId = ${message.guild.id}`).then(row3 => { //eslint-disable-line quotes
			if (!row3) return sql.run(`INSERT INTO guildOptions (guildId, prefix, levels, swearing) VALUES (?, ?, ?, ?)`, [message.guild.id, '.', 'true', 'true']); //eslint-disable-line quotes
			if (row3.levels == 'false' || row3.levels === false) return;
			let usID = message.author.id;
			let gID = message.guild.id;
			sql.get(`SELECT * FROM guildModeration WHERE userId = '${usID}' AND guildId = '${gID}'`).then(row => {
				sql.get(`SELECT * FROM moderation WHERE userId = '${usID}'`).then(row2 => {
					if (!row) sql.run(`INSERT INTO guildModeration (guildId, userId, bans, kicks, mutes, warns, banEnd, muteEnd, xpLevel, xpTotal, xpCurrent, lastMessage, lastXP, xpM) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [gID, usID, 0, 0, 0, 0, null, null, 0, 0, 0, Date.now(), Date.now(), 1]);
					if (!row2) sql.run(`INSERT INTO moderation (userId, gBans, gKicks, gMutes, gWarns, gCases, gXP) VALUES (?, ?, ?, ?, ?, ?, ?)`, [usID, 0, 0, 0, 0, 0, 0]);
					if (!row || !row2) return;
					if (Date.now() - row.lastXP < config.xp.xpAdd) return sql.run(`UPDATE guildModeration SET lastMessage = ${Date.now()} WHERE userId = '${usID}' AND guildId = '${gID}'`);
					let xpM;
					if (Date.now() - row.lastMessage < 15000) {
						xpM = row.xpM * 1.02;
					} else if (Date.now() - row.lastMessage < 30000) {
						xpM = row.xpM * 1.01;
					} else if (Date.now() - row.lastMessage < 60000) {
						xpM = row.xpM * 1.005;
					} else {
						xpM = 1;
					}
					if (xpM > config.xp.maxMult) xpM = config.xp.maxMult;
					sql.run(`UPDATE guildModeration SET xpM = ${xpM} WHERE userId = '${usID}' AND guildId = '${gID}'`);
					const xpMN = Math.round(xpM * config.xp.base);
					const xpMin = xpMN - config.xp.min;
					const xpMax = xpMN + config.xp.max;
					const xpAdd = Math.round(Math.random() * (xpMax - xpMin) + xpMin);
					const lvArray = [];
					let lvNum = 0;
					let xpL = 0;
					for (let i = 0; i < 101; i++) {
						lvNum += Math.round(config.xp.levelOne * Math.pow(config.xp.eqMult, i));
						lvArray.push(lvNum);
						if (lvNum < row.xpTotal) xpL = i + 1;
					}
					if (row.xpTotal + xpAdd >= lvArray[xpL] && xpL + 1 !== row.xpLevel) {
						sql.run(`UPDATE guildModeration SET xpLevel = ${xpL + 1} WHERE userId = '${usID}' AND guildId = '${gID}'`);
						sql.run(`UPDATE guildModeration SET xpCurrent = ${row.xpTotal + xpAdd - lvArray[xpL]} WHERE userId = '${usID}' AND guildId = '${gID}'`);
						message.channel.send(`Good job, <@${message.author.id}>, you've achieved level **${xpL + 1}**!`);
					} else {
						sql.run(`UPDATE guildModeration SET xpCurrent = ${row.xpCurrent + xpAdd} WHERE userId = '${usID}' AND guildId = '${gID}'`);
					}
					sql.run(`UPDATE guildModeration SET xpTotal = ${row.xpTotal + xpAdd} WHERE userId = '${usID}' AND guildId = '${gID}'`);
					sql.run(`UPDATE guildModeration SET lastXP = ${Date.now()} WHERE userId = '${usID}' AND guildId = '${gID}'`);
					sql.run(`UPDATE guildModeration SET lastMessage = ${Date.now()} WHERE userId = '${usID}' AND guildId = '${gID}'`);
					sql.run(`UPDATE moderation SET gXP = ${row2.gXP + xpAdd} WHERE userId = '${usID}'`);
				});
			});
		});
	},
	games: function (bot) {
		setInterval(() => {
			const games = ['.invite is cool', `${bot.guilds.size} servers`, `${bot.users.size} users`, 'tell your friends', 'textedit ftw', 'random joke: a social life', 'what a lonely life', 'here i am, brain the size of a planet..', '.die 4 69', '.mc :o'];
			bot.user.setGame('.help | ' + games[Math.floor(Math.random() * games.length)], 'https://www.twitch.tv/hey');
		}, 30000);
	}
};


text:
from DefaultKIDSBuildInstaller import DefaultKIDSBuildInstaller

class CustomInstaller(DefaultKIDSBuildInstaller):
  def __init__(self, kidsFile, kidsInstallName,
               seqNo = None, logFile = None, multiBuildList=None,
               duz=17, **kargs):
    print kidsInstallName, seqNo
    assert kidsInstallName == "PXRM*2.0*28" and int(seqNo) == 22
    DefaultKIDSBuildInstaller.__init__(self, kidsFile,
                                       kidsInstallName,
                                       seqNo, logFile,
                                       multiBuildList,
                                       duz, **kargs)
  """
    @override DefaultKIDSBuildInstaller.runPostInstallationRoutine
  """
  def runPostInstallationRoutine(self, connection, **kargs):
    # handle the question asked during installing reminder process
    while True:
      index = connection.expect([" Select one of the following:",
                                 "Linking and enabling dialogs"],
                                timeout=120)
      if index == 0: # just quit the installation
        connection.expect("Enter response: ")
        connection.send("Q\r") # Quit installation
        continue
      else:
        break


text:
package de.erichseifert.gral.util;

/**
 * Indicates the location of components.
 */
public enum Location {
	/** Central location. */
	CENTER(0.5, 0.5),
	/** Northern location. */
	NORTH(0.5, 0.0),
	/** North-eastern location. */
	NORTH_EAST(1.0, 0.0),
	/** Eastern location. */
	EAST(1.0, 0.5),
	/** South-eastern location. */
	SOUTH_EAST(1.0, 1.0),
	/** Southern location. */
	SOUTH(0.5, 1.0),
	/** South-western location. */
	SOUTH_WEST(0.0, 1.0),
	/** Western location. */
	WEST(0.0,  0.5),
	/** North-western location. */
	NORTH_WEST(0.0, 0.0);

	/** Horizontal alignment. */
	private final double alignH;
	/** Vertical alignment. */
	private final double alignV;

	/**
	 * Constructor that initializes a new location.
	 * @param alignH Horizontal alignment.
	 * @param alignV Vertical alignment.
	 */
	Location(double alignH, double alignV) {
		this.alignH = alignH;
		this.alignV = alignV;
	}

	/**
	 * Returns the horizontal alignment as a double value.
	 * @return horizontal alignment
	 */
	public double getAlignmentH() {
		return alignH;
	}
	/**
	 * Returns the vertical alignment as a double value.
	 * @return vertical alignment
	 */
	public double getAlignmentV() {
		return alignV;
	}
}


text:
using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;

using Quasar.Utilities;
using Quasar.HabboHotel.Rooms;
using Quasar.HabboHotel.Users;

namespace Quasar.Communication.Packets.Outgoing.Moderation
{
    class ModeratorUserRoomVisitsComposer : ServerPacket
    {
        public ModeratorUserRoomVisitsComposer(Habbo Data, Dictionary<double, RoomData> Visits)
            : base(ServerPacketHeader.ModeratorUserRoomVisitsMessageComposer)
        {
            base.WriteInteger(Data.Id);
           base.WriteString(Data.Username);
            base.WriteInteger(Visits.Count);

            foreach (KeyValuePair<double, RoomData> Visit in Visits)
            {
                base.WriteInteger(Visit.Value.Id);
               base.WriteString(Visit.Value.Name);
                base.WriteInteger(UnixTimestamp.FromUnixTimestamp(Visit.Key).Hour);
                base.WriteInteger(UnixTimestamp.FromUnixTimestamp(Visit.Key).Minute);
            }
        }
    }
}


text:
process.env.NODE_ENV = 'test';
const config = require("config");
const path = require("path");

var model_dir = config.model_dir || path.join(process.cwd(), "./models");
const Test = require(path.join(model_dir, "test_model"));

var chai = require('chai');
var chaiHttp = require('chai-http');
var should = chai.should();

var init = require("./init");

var server = require("../bin/server");

chai.use(chaiHttp);

const mock_data = {
   users: [
       { email: init.admin_email, password: init.admin_password, name: "Admin User", admin: true, urlid: "admin-user" },
       { email: init.email, password: init.password, name: "Jeff", admin: false, urlid: "jeff" },
    ],
    tests: [
        { foo: "setup_data", bar: "setup_data" }
    ]
}
describe('Setup', () => {
    beforeEach(async function() {
        await init.empty_user_collections();
    })

	describe("setup", () => {
		it("it should setup a primary user", (done) => {
			chai.request(server)
				.post("/setup")
				.send({ email: init.email, password: init.password })
				.end((err, res) => {
					res.should.have.status(200);
					res.body.status.should.equal('success');
                    res.body.name.should.equal('admin');
                    res.body.email.should.equal(init.email);
					done();
				});
		});
    });

    describe("setup_data", () => {
        it("it will set the database up with custom data", (done) => {
			chai.request(server)
				.post("/setup/data")
				.send(mock_data)
				.end((err, res) => {
					res.should.have.status(200);
                    res.body.status.should.equal('success');
                    res.body.results.users.insertedCount.should.equal(2);
                    res.body.results.tests.insertedCount.should.equal(1);
					done();
				});
		});
    })
});


text:
package org.apache.geode.redis.internal.executor.sortedset;

import org.apache.geode.cache.Region;
import org.apache.geode.redis.internal.ByteArrayWrapper;
import org.apache.geode.redis.internal.Coder;
import org.apache.geode.redis.internal.DoubleWrapper;
import org.apache.geode.redis.internal.ExecutionHandlerContext;
import org.apache.geode.redis.internal.RedisDataType;
import org.apache.geode.redis.internal.executor.AbstractExecutor;

public abstract class SortedSetExecutor extends AbstractExecutor {

  final ByteArrayWrapper minus = new ByteArrayWrapper(Coder.stringToBytes("-"));
  final ByteArrayWrapper plus = new ByteArrayWrapper(Coder.stringToBytes("+"));

  @Override
  protected Region<ByteArrayWrapper, DoubleWrapper> getOrCreateRegion(
      ExecutionHandlerContext context, ByteArrayWrapper key, RedisDataType type) {
    @SuppressWarnings("unchecked")
    Region<ByteArrayWrapper, DoubleWrapper> r = (Region<ByteArrayWrapper, DoubleWrapper>) context
        .getRegionProvider().getOrCreateRegion(key, type, context);
    return r;
  }

  protected Region<ByteArrayWrapper, DoubleWrapper> getRegion(ExecutionHandlerContext context,
      ByteArrayWrapper key) {
    @SuppressWarnings("unchecked")
    Region<ByteArrayWrapper, DoubleWrapper> r =
        (Region<ByteArrayWrapper, DoubleWrapper>) context.getRegionProvider().getRegion(key);
    return r;
  }

}


text:
<?php
// swoole.php

if (! defined ( 'DS' )) {
	define ( 'DS', DIRECTORY_SEPARATOR );
	define ( 'ROOT', __DIR__ . \DS .'..'.\DS. 'app' . \DS );
}
$config=include ROOT.'config/config.php';
$sConfig= include __DIR__.\DS.'swoole-config.php';
$config["sessionName"]=$sConfig["sessionName"];
$address=$sConfig['host'].':'.$sConfig['port'];
$config ["siteUrl"] = 'http://'.$address;
require ROOT . './../vendor/autoload.php';
require ROOT.'config/services.php';
$reactServer=new \Ubiquity\servers\swoole\SwooleServer();
$reactServer->init($config, __DIR__);
$reactServer->run($sConfig['host'],$sConfig['port']);


text:
var net = require('net');
var crypto = require('crypto');

var players = [];

function Player(name, socket) {
    this.name = name;
    this.health = 0;
    this.mana = 0;
    this.x = 0;
    this.y = 0;
    this.z = 0;
    this.partyMembers = [];
    this.socket = socket;

    //Initial party hash
    var sum = crypto.createHash('sha256');
    sum.update(name + Math.random());
    this.partyHash = sum.digest('base64');
}

function HealthPacket(player) {
    this.name = player.name;
    this.hp = player.hp;
}

function ManaPacket(player) {
    this.name = player.name;
    this.mana = player.mana;
}

function PositionPacket(player) {
    this.name = player.name;
    this.x = player.x;
    this.y = player.y;
    this.z = player.z;
}

function NameMap(partial, full) {
    this.name = partial;
    this.fullName = full;
}

function changePosition(player, x, y, z) {
    player.x = x;
    player.y = y;
    player.z = z;
    sendDataToParty(player, JSON.stringify(new PositionPacket(player)));
}

function changeHealth(player, hp) {
    player.health = hp;
    sendDataToParty(player, JSON.stringify(new HealthPacket(player)));
}

function changeMana(player, mana) {
    player.mana = mana;
    sendDataToParty(player, JSON.stringify(new ManaPacket(player)));
}

function changeMembers(player, newMems) {
    newMems.sort();
    player.partyMembers = newMems;
    var sum = crypto.createHash('sha256');
    sum.update(player.partyMembers.join('|'));
    player.partyHash = sum.digest('base64');
}

//Gets the full name of a party member of <player>
function getFullName(player, partialName) {
    var oPlayer;
    for (var i = 0; i < players.length; i++) {
        oPlayer = players[i];
        if (oPlayer.partyHash === player.partyHash &&
                oPlayer.name.indexOf(partialName) === 0) {
            return oPlayer.name;
        }
    }
    return partialName;
}

function sendDataToParty(player, dataStr) {
    var partyHash = player.partyHash,
        oPlayer;
    for (var i = 0; i < players.length; i++) {
        oPlayer = players[i];
        if (oPlayer !== player && oPlayer.partyHash === partyHash) {
            oPlayer.socket.write(dataStr);
        }
    }
}

var serv = net.createServer(function(sock) {
    sock.setNoDelay(true);
    var player = null;

    function playerLeave() {
        if (player) {
            var index = players.indexOf(player);
            players.splice(index, 1);
            player = null;
        }
    }

    sock.on('data', function(dataStr) {
        var pkt, p, pos, hp, mana;
        try {
            pkt = JSON.parse(dataStr);
        } catch (e) {
            return;
        }
        if (pkt.type === "JOIN") {
            player = new Player(pkt.name, sock);
            changeMembers(player, pkt.partyMembers);
            changePosition(player, pkt.x, pkt.y, pkt.z);
            changeHealth(player, pkt.hp);
            changeMana(player, pkt.mana);
            for (var i = 0; i < players.length; i++) {
                p = players[i];
                if (p.partyHash === player.partyHash) {
                    pos = new PositionPacket(p);
                    hp = new HealthPacket(p);
                    mana = new ManaPacket(p);
                    sock.write(JSON.stringify(pos));
                    sock.write(JSON.stringify(hp));
                    sock.write(JSON.stringify(mana));
                }
            }
            players.push(player);

        }
        if (pkt.type === "LEAVE") {
            playerLeave();
        }
        if (!player) {
            return;
        }
        switch (pkt.type) {
        case "POS":
            changePosition(player, pkt.x, pkt.y, pkt.z);
            break;
        case "MEMS":
            changeMembers(player, pkt.partyMembers);
            break;
        case "HP":
            changeHealth(player, pkt.hp);
            break;
        case "MANA":
            changeMana(player, pkt.mana);
            break;
        case "GET_NAME":
            var map = new NameMap(pkt.partialName, getFullName(player, pkt.partialName));
            var json = JSON.stringify(map);
            sock.write(json);
            break;
        }
    });

    sock.on('end', function() {
        //Client disconnect
        playerLeave();
    });

    sock.on('error', function(err) {
        playerLeave();
    });
});

serv.listen(4070);