prompt
large_stringlengths 72
9.34k
| completion
large_stringlengths 0
7.61k
|
---|---|
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Sensor to collect the reference daily prices of electricity ('PVPC') in Spain."""
import logging
from random import randint
from typing import Optional
from aiopvpc import PVPCData
from homeassistant import config_entries
from homeassistant.const import CONF_NAME, ENERGY_KILO_WATT_HOUR
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.event import async_call_later, async_track_time_change
from homeassistant.helpers.restore_state import RestoreEntity
import homeassistant.util.dt as dt_util
from .const import ATTR_TARIFF
_LOGGER = logging.getLogger(__name__)
ATTR_PRICE = "price"
ICON = "mdi:currency-eur"
UNIT = f"€/{ENERGY_KILO_WATT_HOUR}"
_DEFAULT_TIMEOUT = 10
async def as<|fim_middle|> hass: HomeAssistant, config_entry: config_entries.ConfigEntry, async_add_entities
):
"""Set up the electricity price sensor from config_entry."""
name = config_entry.data[CONF_NAME]
pvpc_data_handler = PVPCData(
tariff=config_entry.data[ATTR_TARIFF],
local_timezone=hass.config.time_zone,
websession=async_get_clientsession(hass),
logger=_LOGGER,
timeout=_DEFAULT_TIMEOUT,
)
async_add_entities(
[ElecPriceSensor(name, config_entry.unique_id, pvpc_data_handler)], False
)
class ElecPriceSensor(RestoreEntity):
"""Class to hold the prices of electricity as a sensor."""
unit_of_measurement = UNIT
icon = ICON
should_poll = False
def __init__(self, name, unique_id, pvpc_data_handler):
"""Initialize the sensor object."""
self._name = name
self._unique_id = unique_id
self._pvpc_data = pvpc_data_handler
self._num_retries = 0
self._hourly_tracker = None
self._price_tracker = None
async def async_will_remove_from_hass(self) -> None:
"""Cancel listeners for sensor updates."""
self._hourly_tracker()
self._price_tracker()
async def async_added_to_hass(self):
"""Handle entity which will be added."""
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._pvpc_data.state = state.state
# Update 'state' value in hour changes
self._hourly_tracker = async_track_time_change(
self.hass, self.update_current_price, second=[0], minute=[0]
)
# Update prices at random time, 2 times/hour (don't want to upset API)
random_minute = randint(1, 29)
mins_update = [random_minute, random_minute + 30]
self._price_tracker = async_track_time_change(
self.hass, self.async_update_prices, second=[0], minute=mins_update
)
_LOGGER.debug(
"Setup of price sensor %s (%s) with tariff '%s', "
"updating prices each hour at %s min",
self.name,
self.entity_id,
self._pvpc_data.tariff,
mins_update,
)
await self.async_update_prices(dt_util.utcnow())
self.update_current_price(dt_util.utcnow())
@property
def unique_id(self) -> Optional[str]:
"""Return a unique ID."""
return self._unique_id
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the sensor."""
return self._pvpc_data.state
@property
def available(self) -> bool:
"""Return True if entity is available."""
return self._pvpc_data.state_available
@property
def device_state_attributes(self):
"""Return the state attributes."""
return self._pvpc_data.attributes
@callback
def update_current_price(self, now):
"""Update the sensor state, by selecting the current price for this hour."""
self._pvpc_data.process_state_and_attributes(now)
self.async_write_ha_state()
async def async_update_prices(self, now):
"""Update electricity prices from the ESIOS API."""
prices = await self._pvpc_data.async_update_prices(now)
if not prices and self._pvpc_data.source_available:
self._num_retries += 1
if self._num_retries > 2:
_LOGGER.warning(
"%s: repeated bad data update, mark component as unavailable source",
self.entity_id,
)
self._pvpc_data.source_available = False
return
retry_delay = 2 * self._num_retries * self._pvpc_data.timeout
_LOGGER.debug(
"%s: Bad update[retry:%d], will try again in %d s",
self.entity_id,
self._num_retries,
retry_delay,
)
async_call_later(self.hass, retry_delay, self.async_update_prices)
return
if not prices:
_LOGGER.debug("%s: data source is not yet available", self.entity_id)
return
self._num_retries = 0
if not self._pvpc_data.source_available:
self._pvpc_data.source_available = True
_LOGGER.warning("%s: component has recovered data access", self.entity_id)
self.update_current_price(now)
<|fim▁end|> | ync_setup_entry(
|
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Sensor to collect the reference daily prices of electricity ('PVPC') in Spain."""
import logging
from random import randint
from typing import Optional
from aiopvpc import PVPCData
from homeassistant import config_entries
from homeassistant.const import CONF_NAME, ENERGY_KILO_WATT_HOUR
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.event import async_call_later, async_track_time_change
from homeassistant.helpers.restore_state import RestoreEntity
import homeassistant.util.dt as dt_util
from .const import ATTR_TARIFF
_LOGGER = logging.getLogger(__name__)
ATTR_PRICE = "price"
ICON = "mdi:currency-eur"
UNIT = f"€/{ENERGY_KILO_WATT_HOUR}"
_DEFAULT_TIMEOUT = 10
async def async_setup_entry(
hass: HomeAssistant, config_entry: config_entries.ConfigEntry, async_add_entities
):
"""Set up the electricity price sensor from config_entry."""
name = config_entry.data[CONF_NAME]
pvpc_data_handler = PVPCData(
tariff=config_entry.data[ATTR_TARIFF],
local_timezone=hass.config.time_zone,
websession=async_get_clientsession(hass),
logger=_LOGGER,
timeout=_DEFAULT_TIMEOUT,
)
async_add_entities(
[ElecPriceSensor(name, config_entry.unique_id, pvpc_data_handler)], False
)
class ElecPriceSensor(RestoreEntity):
"""Class to hold the prices of electricity as a sensor."""
unit_of_measurement = UNIT
icon = ICON
should_poll = False
def __<|fim_middle|>elf, name, unique_id, pvpc_data_handler):
"""Initialize the sensor object."""
self._name = name
self._unique_id = unique_id
self._pvpc_data = pvpc_data_handler
self._num_retries = 0
self._hourly_tracker = None
self._price_tracker = None
async def async_will_remove_from_hass(self) -> None:
"""Cancel listeners for sensor updates."""
self._hourly_tracker()
self._price_tracker()
async def async_added_to_hass(self):
"""Handle entity which will be added."""
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._pvpc_data.state = state.state
# Update 'state' value in hour changes
self._hourly_tracker = async_track_time_change(
self.hass, self.update_current_price, second=[0], minute=[0]
)
# Update prices at random time, 2 times/hour (don't want to upset API)
random_minute = randint(1, 29)
mins_update = [random_minute, random_minute + 30]
self._price_tracker = async_track_time_change(
self.hass, self.async_update_prices, second=[0], minute=mins_update
)
_LOGGER.debug(
"Setup of price sensor %s (%s) with tariff '%s', "
"updating prices each hour at %s min",
self.name,
self.entity_id,
self._pvpc_data.tariff,
mins_update,
)
await self.async_update_prices(dt_util.utcnow())
self.update_current_price(dt_util.utcnow())
@property
def unique_id(self) -> Optional[str]:
"""Return a unique ID."""
return self._unique_id
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the sensor."""
return self._pvpc_data.state
@property
def available(self) -> bool:
"""Return True if entity is available."""
return self._pvpc_data.state_available
@property
def device_state_attributes(self):
"""Return the state attributes."""
return self._pvpc_data.attributes
@callback
def update_current_price(self, now):
"""Update the sensor state, by selecting the current price for this hour."""
self._pvpc_data.process_state_and_attributes(now)
self.async_write_ha_state()
async def async_update_prices(self, now):
"""Update electricity prices from the ESIOS API."""
prices = await self._pvpc_data.async_update_prices(now)
if not prices and self._pvpc_data.source_available:
self._num_retries += 1
if self._num_retries > 2:
_LOGGER.warning(
"%s: repeated bad data update, mark component as unavailable source",
self.entity_id,
)
self._pvpc_data.source_available = False
return
retry_delay = 2 * self._num_retries * self._pvpc_data.timeout
_LOGGER.debug(
"%s: Bad update[retry:%d], will try again in %d s",
self.entity_id,
self._num_retries,
retry_delay,
)
async_call_later(self.hass, retry_delay, self.async_update_prices)
return
if not prices:
_LOGGER.debug("%s: data source is not yet available", self.entity_id)
return
self._num_retries = 0
if not self._pvpc_data.source_available:
self._pvpc_data.source_available = True
_LOGGER.warning("%s: component has recovered data access", self.entity_id)
self.update_current_price(now)
<|fim▁end|> | init__(s |
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Sensor to collect the reference daily prices of electricity ('PVPC') in Spain."""
import logging
from random import randint
from typing import Optional
from aiopvpc import PVPCData
from homeassistant import config_entries
from homeassistant.const import CONF_NAME, ENERGY_KILO_WATT_HOUR
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.event import async_call_later, async_track_time_change
from homeassistant.helpers.restore_state import RestoreEntity
import homeassistant.util.dt as dt_util
from .const import ATTR_TARIFF
_LOGGER = logging.getLogger(__name__)
ATTR_PRICE = "price"
ICON = "mdi:currency-eur"
UNIT = f"€/{ENERGY_KILO_WATT_HOUR}"
_DEFAULT_TIMEOUT = 10
async def async_setup_entry(
hass: HomeAssistant, config_entry: config_entries.ConfigEntry, async_add_entities
):
"""Set up the electricity price sensor from config_entry."""
name = config_entry.data[CONF_NAME]
pvpc_data_handler = PVPCData(
tariff=config_entry.data[ATTR_TARIFF],
local_timezone=hass.config.time_zone,
websession=async_get_clientsession(hass),
logger=_LOGGER,
timeout=_DEFAULT_TIMEOUT,
)
async_add_entities(
[ElecPriceSensor(name, config_entry.unique_id, pvpc_data_handler)], False
)
class ElecPriceSensor(RestoreEntity):
"""Class to hold the prices of electricity as a sensor."""
unit_of_measurement = UNIT
icon = ICON
should_poll = False
def __init__(self, name, unique_id, pvpc_data_handler):
"""Initialize the sensor object."""
self._name = name
self._unique_id = unique_id
self._pvpc_data = pvpc_data_handler
self._num_retries = 0
self._hourly_tracker = None
self._price_tracker = None
async def as<|fim_middle|>elf) -> None:
"""Cancel listeners for sensor updates."""
self._hourly_tracker()
self._price_tracker()
async def async_added_to_hass(self):
"""Handle entity which will be added."""
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._pvpc_data.state = state.state
# Update 'state' value in hour changes
self._hourly_tracker = async_track_time_change(
self.hass, self.update_current_price, second=[0], minute=[0]
)
# Update prices at random time, 2 times/hour (don't want to upset API)
random_minute = randint(1, 29)
mins_update = [random_minute, random_minute + 30]
self._price_tracker = async_track_time_change(
self.hass, self.async_update_prices, second=[0], minute=mins_update
)
_LOGGER.debug(
"Setup of price sensor %s (%s) with tariff '%s', "
"updating prices each hour at %s min",
self.name,
self.entity_id,
self._pvpc_data.tariff,
mins_update,
)
await self.async_update_prices(dt_util.utcnow())
self.update_current_price(dt_util.utcnow())
@property
def unique_id(self) -> Optional[str]:
"""Return a unique ID."""
return self._unique_id
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the sensor."""
return self._pvpc_data.state
@property
def available(self) -> bool:
"""Return True if entity is available."""
return self._pvpc_data.state_available
@property
def device_state_attributes(self):
"""Return the state attributes."""
return self._pvpc_data.attributes
@callback
def update_current_price(self, now):
"""Update the sensor state, by selecting the current price for this hour."""
self._pvpc_data.process_state_and_attributes(now)
self.async_write_ha_state()
async def async_update_prices(self, now):
"""Update electricity prices from the ESIOS API."""
prices = await self._pvpc_data.async_update_prices(now)
if not prices and self._pvpc_data.source_available:
self._num_retries += 1
if self._num_retries > 2:
_LOGGER.warning(
"%s: repeated bad data update, mark component as unavailable source",
self.entity_id,
)
self._pvpc_data.source_available = False
return
retry_delay = 2 * self._num_retries * self._pvpc_data.timeout
_LOGGER.debug(
"%s: Bad update[retry:%d], will try again in %d s",
self.entity_id,
self._num_retries,
retry_delay,
)
async_call_later(self.hass, retry_delay, self.async_update_prices)
return
if not prices:
_LOGGER.debug("%s: data source is not yet available", self.entity_id)
return
self._num_retries = 0
if not self._pvpc_data.source_available:
self._pvpc_data.source_available = True
_LOGGER.warning("%s: component has recovered data access", self.entity_id)
self.update_current_price(now)
<|fim▁end|> | ync_will_remove_from_hass(s |
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Sensor to collect the reference daily prices of electricity ('PVPC') in Spain."""
import logging
from random import randint
from typing import Optional
from aiopvpc import PVPCData
from homeassistant import config_entries
from homeassistant.const import CONF_NAME, ENERGY_KILO_WATT_HOUR
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.event import async_call_later, async_track_time_change
from homeassistant.helpers.restore_state import RestoreEntity
import homeassistant.util.dt as dt_util
from .const import ATTR_TARIFF
_LOGGER = logging.getLogger(__name__)
ATTR_PRICE = "price"
ICON = "mdi:currency-eur"
UNIT = f"€/{ENERGY_KILO_WATT_HOUR}"
_DEFAULT_TIMEOUT = 10
async def async_setup_entry(
hass: HomeAssistant, config_entry: config_entries.ConfigEntry, async_add_entities
):
"""Set up the electricity price sensor from config_entry."""
name = config_entry.data[CONF_NAME]
pvpc_data_handler = PVPCData(
tariff=config_entry.data[ATTR_TARIFF],
local_timezone=hass.config.time_zone,
websession=async_get_clientsession(hass),
logger=_LOGGER,
timeout=_DEFAULT_TIMEOUT,
)
async_add_entities(
[ElecPriceSensor(name, config_entry.unique_id, pvpc_data_handler)], False
)
class ElecPriceSensor(RestoreEntity):
"""Class to hold the prices of electricity as a sensor."""
unit_of_measurement = UNIT
icon = ICON
should_poll = False
def __init__(self, name, unique_id, pvpc_data_handler):
"""Initialize the sensor object."""
self._name = name
self._unique_id = unique_id
self._pvpc_data = pvpc_data_handler
self._num_retries = 0
self._hourly_tracker = None
self._price_tracker = None
async def async_will_remove_from_hass(self) -> None:
"""Cancel listeners for sensor updates."""
self._hourly_tracker()
self._price_tracker()
async def as<|fim_middle|>elf):
"""Handle entity which will be added."""
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._pvpc_data.state = state.state
# Update 'state' value in hour changes
self._hourly_tracker = async_track_time_change(
self.hass, self.update_current_price, second=[0], minute=[0]
)
# Update prices at random time, 2 times/hour (don't want to upset API)
random_minute = randint(1, 29)
mins_update = [random_minute, random_minute + 30]
self._price_tracker = async_track_time_change(
self.hass, self.async_update_prices, second=[0], minute=mins_update
)
_LOGGER.debug(
"Setup of price sensor %s (%s) with tariff '%s', "
"updating prices each hour at %s min",
self.name,
self.entity_id,
self._pvpc_data.tariff,
mins_update,
)
await self.async_update_prices(dt_util.utcnow())
self.update_current_price(dt_util.utcnow())
@property
def unique_id(self) -> Optional[str]:
"""Return a unique ID."""
return self._unique_id
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the sensor."""
return self._pvpc_data.state
@property
def available(self) -> bool:
"""Return True if entity is available."""
return self._pvpc_data.state_available
@property
def device_state_attributes(self):
"""Return the state attributes."""
return self._pvpc_data.attributes
@callback
def update_current_price(self, now):
"""Update the sensor state, by selecting the current price for this hour."""
self._pvpc_data.process_state_and_attributes(now)
self.async_write_ha_state()
async def async_update_prices(self, now):
"""Update electricity prices from the ESIOS API."""
prices = await self._pvpc_data.async_update_prices(now)
if not prices and self._pvpc_data.source_available:
self._num_retries += 1
if self._num_retries > 2:
_LOGGER.warning(
"%s: repeated bad data update, mark component as unavailable source",
self.entity_id,
)
self._pvpc_data.source_available = False
return
retry_delay = 2 * self._num_retries * self._pvpc_data.timeout
_LOGGER.debug(
"%s: Bad update[retry:%d], will try again in %d s",
self.entity_id,
self._num_retries,
retry_delay,
)
async_call_later(self.hass, retry_delay, self.async_update_prices)
return
if not prices:
_LOGGER.debug("%s: data source is not yet available", self.entity_id)
return
self._num_retries = 0
if not self._pvpc_data.source_available:
self._pvpc_data.source_available = True
_LOGGER.warning("%s: component has recovered data access", self.entity_id)
self.update_current_price(now)
<|fim▁end|> | ync_added_to_hass(s |
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Sensor to collect the reference daily prices of electricity ('PVPC') in Spain."""
import logging
from random import randint
from typing import Optional
from aiopvpc import PVPCData
from homeassistant import config_entries
from homeassistant.const import CONF_NAME, ENERGY_KILO_WATT_HOUR
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.event import async_call_later, async_track_time_change
from homeassistant.helpers.restore_state import RestoreEntity
import homeassistant.util.dt as dt_util
from .const import ATTR_TARIFF
_LOGGER = logging.getLogger(__name__)
ATTR_PRICE = "price"
ICON = "mdi:currency-eur"
UNIT = f"€/{ENERGY_KILO_WATT_HOUR}"
_DEFAULT_TIMEOUT = 10
async def async_setup_entry(
hass: HomeAssistant, config_entry: config_entries.ConfigEntry, async_add_entities
):
"""Set up the electricity price sensor from config_entry."""
name = config_entry.data[CONF_NAME]
pvpc_data_handler = PVPCData(
tariff=config_entry.data[ATTR_TARIFF],
local_timezone=hass.config.time_zone,
websession=async_get_clientsession(hass),
logger=_LOGGER,
timeout=_DEFAULT_TIMEOUT,
)
async_add_entities(
[ElecPriceSensor(name, config_entry.unique_id, pvpc_data_handler)], False
)
class ElecPriceSensor(RestoreEntity):
"""Class to hold the prices of electricity as a sensor."""
unit_of_measurement = UNIT
icon = ICON
should_poll = False
def __init__(self, name, unique_id, pvpc_data_handler):
"""Initialize the sensor object."""
self._name = name
self._unique_id = unique_id
self._pvpc_data = pvpc_data_handler
self._num_retries = 0
self._hourly_tracker = None
self._price_tracker = None
async def async_will_remove_from_hass(self) -> None:
"""Cancel listeners for sensor updates."""
self._hourly_tracker()
self._price_tracker()
async def async_added_to_hass(self):
"""Handle entity which will be added."""
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._pvpc_data.state = state.state
# Update 'state' value in hour changes
self._hourly_tracker = async_track_time_change(
self.hass, self.update_current_price, second=[0], minute=[0]
)
# Update prices at random time, 2 times/hour (don't want to upset API)
random_minute = randint(1, 29)
mins_update = [random_minute, random_minute + 30]
self._price_tracker = async_track_time_change(
self.hass, self.async_update_prices, second=[0], minute=mins_update
)
_LOGGER.debug(
"Setup of price sensor %s (%s) with tariff '%s', "
"updating prices each hour at %s min",
self.name,
self.entity_id,
self._pvpc_data.tariff,
mins_update,
)
await self.async_update_prices(dt_util.utcnow())
self.update_current_price(dt_util.utcnow())
@property
def un<|fim_middle|>elf) -> Optional[str]:
"""Return a unique ID."""
return self._unique_id
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the sensor."""
return self._pvpc_data.state
@property
def available(self) -> bool:
"""Return True if entity is available."""
return self._pvpc_data.state_available
@property
def device_state_attributes(self):
"""Return the state attributes."""
return self._pvpc_data.attributes
@callback
def update_current_price(self, now):
"""Update the sensor state, by selecting the current price for this hour."""
self._pvpc_data.process_state_and_attributes(now)
self.async_write_ha_state()
async def async_update_prices(self, now):
"""Update electricity prices from the ESIOS API."""
prices = await self._pvpc_data.async_update_prices(now)
if not prices and self._pvpc_data.source_available:
self._num_retries += 1
if self._num_retries > 2:
_LOGGER.warning(
"%s: repeated bad data update, mark component as unavailable source",
self.entity_id,
)
self._pvpc_data.source_available = False
return
retry_delay = 2 * self._num_retries * self._pvpc_data.timeout
_LOGGER.debug(
"%s: Bad update[retry:%d], will try again in %d s",
self.entity_id,
self._num_retries,
retry_delay,
)
async_call_later(self.hass, retry_delay, self.async_update_prices)
return
if not prices:
_LOGGER.debug("%s: data source is not yet available", self.entity_id)
return
self._num_retries = 0
if not self._pvpc_data.source_available:
self._pvpc_data.source_available = True
_LOGGER.warning("%s: component has recovered data access", self.entity_id)
self.update_current_price(now)
<|fim▁end|> | ique_id(s |
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Sensor to collect the reference daily prices of electricity ('PVPC') in Spain."""
import logging
from random import randint
from typing import Optional
from aiopvpc import PVPCData
from homeassistant import config_entries
from homeassistant.const import CONF_NAME, ENERGY_KILO_WATT_HOUR
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.event import async_call_later, async_track_time_change
from homeassistant.helpers.restore_state import RestoreEntity
import homeassistant.util.dt as dt_util
from .const import ATTR_TARIFF
_LOGGER = logging.getLogger(__name__)
ATTR_PRICE = "price"
ICON = "mdi:currency-eur"
UNIT = f"€/{ENERGY_KILO_WATT_HOUR}"
_DEFAULT_TIMEOUT = 10
async def async_setup_entry(
hass: HomeAssistant, config_entry: config_entries.ConfigEntry, async_add_entities
):
"""Set up the electricity price sensor from config_entry."""
name = config_entry.data[CONF_NAME]
pvpc_data_handler = PVPCData(
tariff=config_entry.data[ATTR_TARIFF],
local_timezone=hass.config.time_zone,
websession=async_get_clientsession(hass),
logger=_LOGGER,
timeout=_DEFAULT_TIMEOUT,
)
async_add_entities(
[ElecPriceSensor(name, config_entry.unique_id, pvpc_data_handler)], False
)
class ElecPriceSensor(RestoreEntity):
"""Class to hold the prices of electricity as a sensor."""
unit_of_measurement = UNIT
icon = ICON
should_poll = False
def __init__(self, name, unique_id, pvpc_data_handler):
"""Initialize the sensor object."""
self._name = name
self._unique_id = unique_id
self._pvpc_data = pvpc_data_handler
self._num_retries = 0
self._hourly_tracker = None
self._price_tracker = None
async def async_will_remove_from_hass(self) -> None:
"""Cancel listeners for sensor updates."""
self._hourly_tracker()
self._price_tracker()
async def async_added_to_hass(self):
"""Handle entity which will be added."""
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._pvpc_data.state = state.state
# Update 'state' value in hour changes
self._hourly_tracker = async_track_time_change(
self.hass, self.update_current_price, second=[0], minute=[0]
)
# Update prices at random time, 2 times/hour (don't want to upset API)
random_minute = randint(1, 29)
mins_update = [random_minute, random_minute + 30]
self._price_tracker = async_track_time_change(
self.hass, self.async_update_prices, second=[0], minute=mins_update
)
_LOGGER.debug(
"Setup of price sensor %s (%s) with tariff '%s', "
"updating prices each hour at %s min",
self.name,
self.entity_id,
self._pvpc_data.tariff,
mins_update,
)
await self.async_update_prices(dt_util.utcnow())
self.update_current_price(dt_util.utcnow())
@property
def unique_id(self) -> Optional[str]:
"""Return a unique ID."""
return self._unique_id
@property
def na<|fim_middle|>elf):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the sensor."""
return self._pvpc_data.state
@property
def available(self) -> bool:
"""Return True if entity is available."""
return self._pvpc_data.state_available
@property
def device_state_attributes(self):
"""Return the state attributes."""
return self._pvpc_data.attributes
@callback
def update_current_price(self, now):
"""Update the sensor state, by selecting the current price for this hour."""
self._pvpc_data.process_state_and_attributes(now)
self.async_write_ha_state()
async def async_update_prices(self, now):
"""Update electricity prices from the ESIOS API."""
prices = await self._pvpc_data.async_update_prices(now)
if not prices and self._pvpc_data.source_available:
self._num_retries += 1
if self._num_retries > 2:
_LOGGER.warning(
"%s: repeated bad data update, mark component as unavailable source",
self.entity_id,
)
self._pvpc_data.source_available = False
return
retry_delay = 2 * self._num_retries * self._pvpc_data.timeout
_LOGGER.debug(
"%s: Bad update[retry:%d], will try again in %d s",
self.entity_id,
self._num_retries,
retry_delay,
)
async_call_later(self.hass, retry_delay, self.async_update_prices)
return
if not prices:
_LOGGER.debug("%s: data source is not yet available", self.entity_id)
return
self._num_retries = 0
if not self._pvpc_data.source_available:
self._pvpc_data.source_available = True
_LOGGER.warning("%s: component has recovered data access", self.entity_id)
self.update_current_price(now)
<|fim▁end|> | me(s |
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Sensor to collect the reference daily prices of electricity ('PVPC') in Spain."""
import logging
from random import randint
from typing import Optional
from aiopvpc import PVPCData
from homeassistant import config_entries
from homeassistant.const import CONF_NAME, ENERGY_KILO_WATT_HOUR
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.event import async_call_later, async_track_time_change
from homeassistant.helpers.restore_state import RestoreEntity
import homeassistant.util.dt as dt_util
from .const import ATTR_TARIFF
_LOGGER = logging.getLogger(__name__)
ATTR_PRICE = "price"
ICON = "mdi:currency-eur"
UNIT = f"€/{ENERGY_KILO_WATT_HOUR}"
_DEFAULT_TIMEOUT = 10
async def async_setup_entry(
hass: HomeAssistant, config_entry: config_entries.ConfigEntry, async_add_entities
):
"""Set up the electricity price sensor from config_entry."""
name = config_entry.data[CONF_NAME]
pvpc_data_handler = PVPCData(
tariff=config_entry.data[ATTR_TARIFF],
local_timezone=hass.config.time_zone,
websession=async_get_clientsession(hass),
logger=_LOGGER,
timeout=_DEFAULT_TIMEOUT,
)
async_add_entities(
[ElecPriceSensor(name, config_entry.unique_id, pvpc_data_handler)], False
)
class ElecPriceSensor(RestoreEntity):
"""Class to hold the prices of electricity as a sensor."""
unit_of_measurement = UNIT
icon = ICON
should_poll = False
def __init__(self, name, unique_id, pvpc_data_handler):
"""Initialize the sensor object."""
self._name = name
self._unique_id = unique_id
self._pvpc_data = pvpc_data_handler
self._num_retries = 0
self._hourly_tracker = None
self._price_tracker = None
async def async_will_remove_from_hass(self) -> None:
"""Cancel listeners for sensor updates."""
self._hourly_tracker()
self._price_tracker()
async def async_added_to_hass(self):
"""Handle entity which will be added."""
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._pvpc_data.state = state.state
# Update 'state' value in hour changes
self._hourly_tracker = async_track_time_change(
self.hass, self.update_current_price, second=[0], minute=[0]
)
# Update prices at random time, 2 times/hour (don't want to upset API)
random_minute = randint(1, 29)
mins_update = [random_minute, random_minute + 30]
self._price_tracker = async_track_time_change(
self.hass, self.async_update_prices, second=[0], minute=mins_update
)
_LOGGER.debug(
"Setup of price sensor %s (%s) with tariff '%s', "
"updating prices each hour at %s min",
self.name,
self.entity_id,
self._pvpc_data.tariff,
mins_update,
)
await self.async_update_prices(dt_util.utcnow())
self.update_current_price(dt_util.utcnow())
@property
def unique_id(self) -> Optional[str]:
"""Return a unique ID."""
return self._unique_id
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def st<|fim_middle|>elf):
"""Return the state of the sensor."""
return self._pvpc_data.state
@property
def available(self) -> bool:
"""Return True if entity is available."""
return self._pvpc_data.state_available
@property
def device_state_attributes(self):
"""Return the state attributes."""
return self._pvpc_data.attributes
@callback
def update_current_price(self, now):
"""Update the sensor state, by selecting the current price for this hour."""
self._pvpc_data.process_state_and_attributes(now)
self.async_write_ha_state()
async def async_update_prices(self, now):
"""Update electricity prices from the ESIOS API."""
prices = await self._pvpc_data.async_update_prices(now)
if not prices and self._pvpc_data.source_available:
self._num_retries += 1
if self._num_retries > 2:
_LOGGER.warning(
"%s: repeated bad data update, mark component as unavailable source",
self.entity_id,
)
self._pvpc_data.source_available = False
return
retry_delay = 2 * self._num_retries * self._pvpc_data.timeout
_LOGGER.debug(
"%s: Bad update[retry:%d], will try again in %d s",
self.entity_id,
self._num_retries,
retry_delay,
)
async_call_later(self.hass, retry_delay, self.async_update_prices)
return
if not prices:
_LOGGER.debug("%s: data source is not yet available", self.entity_id)
return
self._num_retries = 0
if not self._pvpc_data.source_available:
self._pvpc_data.source_available = True
_LOGGER.warning("%s: component has recovered data access", self.entity_id)
self.update_current_price(now)
<|fim▁end|> | ate(s |
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Sensor to collect the reference daily prices of electricity ('PVPC') in Spain."""
import logging
from random import randint
from typing import Optional
from aiopvpc import PVPCData
from homeassistant import config_entries
from homeassistant.const import CONF_NAME, ENERGY_KILO_WATT_HOUR
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.event import async_call_later, async_track_time_change
from homeassistant.helpers.restore_state import RestoreEntity
import homeassistant.util.dt as dt_util
from .const import ATTR_TARIFF
_LOGGER = logging.getLogger(__name__)
ATTR_PRICE = "price"
ICON = "mdi:currency-eur"
UNIT = f"€/{ENERGY_KILO_WATT_HOUR}"
_DEFAULT_TIMEOUT = 10
async def async_setup_entry(
hass: HomeAssistant, config_entry: config_entries.ConfigEntry, async_add_entities
):
"""Set up the electricity price sensor from config_entry."""
name = config_entry.data[CONF_NAME]
pvpc_data_handler = PVPCData(
tariff=config_entry.data[ATTR_TARIFF],
local_timezone=hass.config.time_zone,
websession=async_get_clientsession(hass),
logger=_LOGGER,
timeout=_DEFAULT_TIMEOUT,
)
async_add_entities(
[ElecPriceSensor(name, config_entry.unique_id, pvpc_data_handler)], False
)
class ElecPriceSensor(RestoreEntity):
"""Class to hold the prices of electricity as a sensor."""
unit_of_measurement = UNIT
icon = ICON
should_poll = False
def __init__(self, name, unique_id, pvpc_data_handler):
"""Initialize the sensor object."""
self._name = name
self._unique_id = unique_id
self._pvpc_data = pvpc_data_handler
self._num_retries = 0
self._hourly_tracker = None
self._price_tracker = None
async def async_will_remove_from_hass(self) -> None:
"""Cancel listeners for sensor updates."""
self._hourly_tracker()
self._price_tracker()
async def async_added_to_hass(self):
"""Handle entity which will be added."""
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._pvpc_data.state = state.state
# Update 'state' value in hour changes
self._hourly_tracker = async_track_time_change(
self.hass, self.update_current_price, second=[0], minute=[0]
)
# Update prices at random time, 2 times/hour (don't want to upset API)
random_minute = randint(1, 29)
mins_update = [random_minute, random_minute + 30]
self._price_tracker = async_track_time_change(
self.hass, self.async_update_prices, second=[0], minute=mins_update
)
_LOGGER.debug(
"Setup of price sensor %s (%s) with tariff '%s', "
"updating prices each hour at %s min",
self.name,
self.entity_id,
self._pvpc_data.tariff,
mins_update,
)
await self.async_update_prices(dt_util.utcnow())
self.update_current_price(dt_util.utcnow())
@property
def unique_id(self) -> Optional[str]:
"""Return a unique ID."""
return self._unique_id
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the sensor."""
return self._pvpc_data.state
@property
def av<|fim_middle|>elf) -> bool:
"""Return True if entity is available."""
return self._pvpc_data.state_available
@property
def device_state_attributes(self):
"""Return the state attributes."""
return self._pvpc_data.attributes
@callback
def update_current_price(self, now):
"""Update the sensor state, by selecting the current price for this hour."""
self._pvpc_data.process_state_and_attributes(now)
self.async_write_ha_state()
async def async_update_prices(self, now):
"""Update electricity prices from the ESIOS API."""
prices = await self._pvpc_data.async_update_prices(now)
if not prices and self._pvpc_data.source_available:
self._num_retries += 1
if self._num_retries > 2:
_LOGGER.warning(
"%s: repeated bad data update, mark component as unavailable source",
self.entity_id,
)
self._pvpc_data.source_available = False
return
retry_delay = 2 * self._num_retries * self._pvpc_data.timeout
_LOGGER.debug(
"%s: Bad update[retry:%d], will try again in %d s",
self.entity_id,
self._num_retries,
retry_delay,
)
async_call_later(self.hass, retry_delay, self.async_update_prices)
return
if not prices:
_LOGGER.debug("%s: data source is not yet available", self.entity_id)
return
self._num_retries = 0
if not self._pvpc_data.source_available:
self._pvpc_data.source_available = True
_LOGGER.warning("%s: component has recovered data access", self.entity_id)
self.update_current_price(now)
<|fim▁end|> | ailable(s |
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Sensor to collect the reference daily prices of electricity ('PVPC') in Spain."""
import logging
from random import randint
from typing import Optional
from aiopvpc import PVPCData
from homeassistant import config_entries
from homeassistant.const import CONF_NAME, ENERGY_KILO_WATT_HOUR
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.event import async_call_later, async_track_time_change
from homeassistant.helpers.restore_state import RestoreEntity
import homeassistant.util.dt as dt_util
from .const import ATTR_TARIFF
_LOGGER = logging.getLogger(__name__)
ATTR_PRICE = "price"
ICON = "mdi:currency-eur"
UNIT = f"€/{ENERGY_KILO_WATT_HOUR}"
_DEFAULT_TIMEOUT = 10
async def async_setup_entry(
hass: HomeAssistant, config_entry: config_entries.ConfigEntry, async_add_entities
):
"""Set up the electricity price sensor from config_entry."""
name = config_entry.data[CONF_NAME]
pvpc_data_handler = PVPCData(
tariff=config_entry.data[ATTR_TARIFF],
local_timezone=hass.config.time_zone,
websession=async_get_clientsession(hass),
logger=_LOGGER,
timeout=_DEFAULT_TIMEOUT,
)
async_add_entities(
[ElecPriceSensor(name, config_entry.unique_id, pvpc_data_handler)], False
)
class ElecPriceSensor(RestoreEntity):
"""Class to hold the prices of electricity as a sensor."""
unit_of_measurement = UNIT
icon = ICON
should_poll = False
def __init__(self, name, unique_id, pvpc_data_handler):
"""Initialize the sensor object."""
self._name = name
self._unique_id = unique_id
self._pvpc_data = pvpc_data_handler
self._num_retries = 0
self._hourly_tracker = None
self._price_tracker = None
async def async_will_remove_from_hass(self) -> None:
"""Cancel listeners for sensor updates."""
self._hourly_tracker()
self._price_tracker()
async def async_added_to_hass(self):
"""Handle entity which will be added."""
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._pvpc_data.state = state.state
# Update 'state' value in hour changes
self._hourly_tracker = async_track_time_change(
self.hass, self.update_current_price, second=[0], minute=[0]
)
# Update prices at random time, 2 times/hour (don't want to upset API)
random_minute = randint(1, 29)
mins_update = [random_minute, random_minute + 30]
self._price_tracker = async_track_time_change(
self.hass, self.async_update_prices, second=[0], minute=mins_update
)
_LOGGER.debug(
"Setup of price sensor %s (%s) with tariff '%s', "
"updating prices each hour at %s min",
self.name,
self.entity_id,
self._pvpc_data.tariff,
mins_update,
)
await self.async_update_prices(dt_util.utcnow())
self.update_current_price(dt_util.utcnow())
@property
def unique_id(self) -> Optional[str]:
"""Return a unique ID."""
return self._unique_id
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the sensor."""
return self._pvpc_data.state
@property
def available(self) -> bool:
"""Return True if entity is available."""
return self._pvpc_data.state_available
@property
def de<|fim_middle|>elf):
"""Return the state attributes."""
return self._pvpc_data.attributes
@callback
def update_current_price(self, now):
"""Update the sensor state, by selecting the current price for this hour."""
self._pvpc_data.process_state_and_attributes(now)
self.async_write_ha_state()
async def async_update_prices(self, now):
"""Update electricity prices from the ESIOS API."""
prices = await self._pvpc_data.async_update_prices(now)
if not prices and self._pvpc_data.source_available:
self._num_retries += 1
if self._num_retries > 2:
_LOGGER.warning(
"%s: repeated bad data update, mark component as unavailable source",
self.entity_id,
)
self._pvpc_data.source_available = False
return
retry_delay = 2 * self._num_retries * self._pvpc_data.timeout
_LOGGER.debug(
"%s: Bad update[retry:%d], will try again in %d s",
self.entity_id,
self._num_retries,
retry_delay,
)
async_call_later(self.hass, retry_delay, self.async_update_prices)
return
if not prices:
_LOGGER.debug("%s: data source is not yet available", self.entity_id)
return
self._num_retries = 0
if not self._pvpc_data.source_available:
self._pvpc_data.source_available = True
_LOGGER.warning("%s: component has recovered data access", self.entity_id)
self.update_current_price(now)
<|fim▁end|> | vice_state_attributes(s |
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Sensor to collect the reference daily prices of electricity ('PVPC') in Spain."""
import logging
from random import randint
from typing import Optional
from aiopvpc import PVPCData
from homeassistant import config_entries
from homeassistant.const import CONF_NAME, ENERGY_KILO_WATT_HOUR
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.event import async_call_later, async_track_time_change
from homeassistant.helpers.restore_state import RestoreEntity
import homeassistant.util.dt as dt_util
from .const import ATTR_TARIFF
_LOGGER = logging.getLogger(__name__)
ATTR_PRICE = "price"
ICON = "mdi:currency-eur"
UNIT = f"€/{ENERGY_KILO_WATT_HOUR}"
_DEFAULT_TIMEOUT = 10
async def async_setup_entry(
hass: HomeAssistant, config_entry: config_entries.ConfigEntry, async_add_entities
):
"""Set up the electricity price sensor from config_entry."""
name = config_entry.data[CONF_NAME]
pvpc_data_handler = PVPCData(
tariff=config_entry.data[ATTR_TARIFF],
local_timezone=hass.config.time_zone,
websession=async_get_clientsession(hass),
logger=_LOGGER,
timeout=_DEFAULT_TIMEOUT,
)
async_add_entities(
[ElecPriceSensor(name, config_entry.unique_id, pvpc_data_handler)], False
)
class ElecPriceSensor(RestoreEntity):
"""Class to hold the prices of electricity as a sensor."""
unit_of_measurement = UNIT
icon = ICON
should_poll = False
def __init__(self, name, unique_id, pvpc_data_handler):
"""Initialize the sensor object."""
self._name = name
self._unique_id = unique_id
self._pvpc_data = pvpc_data_handler
self._num_retries = 0
self._hourly_tracker = None
self._price_tracker = None
async def async_will_remove_from_hass(self) -> None:
"""Cancel listeners for sensor updates."""
self._hourly_tracker()
self._price_tracker()
async def async_added_to_hass(self):
"""Handle entity which will be added."""
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._pvpc_data.state = state.state
# Update 'state' value in hour changes
self._hourly_tracker = async_track_time_change(
self.hass, self.update_current_price, second=[0], minute=[0]
)
# Update prices at random time, 2 times/hour (don't want to upset API)
random_minute = randint(1, 29)
mins_update = [random_minute, random_minute + 30]
self._price_tracker = async_track_time_change(
self.hass, self.async_update_prices, second=[0], minute=mins_update
)
_LOGGER.debug(
"Setup of price sensor %s (%s) with tariff '%s', "
"updating prices each hour at %s min",
self.name,
self.entity_id,
self._pvpc_data.tariff,
mins_update,
)
await self.async_update_prices(dt_util.utcnow())
self.update_current_price(dt_util.utcnow())
@property
def unique_id(self) -> Optional[str]:
"""Return a unique ID."""
return self._unique_id
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the sensor."""
return self._pvpc_data.state
@property
def available(self) -> bool:
"""Return True if entity is available."""
return self._pvpc_data.state_available
@property
def device_state_attributes(self):
"""Return the state attributes."""
return self._pvpc_data.attributes
@callback
def up<|fim_middle|>elf, now):
"""Update the sensor state, by selecting the current price for this hour."""
self._pvpc_data.process_state_and_attributes(now)
self.async_write_ha_state()
async def async_update_prices(self, now):
"""Update electricity prices from the ESIOS API."""
prices = await self._pvpc_data.async_update_prices(now)
if not prices and self._pvpc_data.source_available:
self._num_retries += 1
if self._num_retries > 2:
_LOGGER.warning(
"%s: repeated bad data update, mark component as unavailable source",
self.entity_id,
)
self._pvpc_data.source_available = False
return
retry_delay = 2 * self._num_retries * self._pvpc_data.timeout
_LOGGER.debug(
"%s: Bad update[retry:%d], will try again in %d s",
self.entity_id,
self._num_retries,
retry_delay,
)
async_call_later(self.hass, retry_delay, self.async_update_prices)
return
if not prices:
_LOGGER.debug("%s: data source is not yet available", self.entity_id)
return
self._num_retries = 0
if not self._pvpc_data.source_available:
self._pvpc_data.source_available = True
_LOGGER.warning("%s: component has recovered data access", self.entity_id)
self.update_current_price(now)
<|fim▁end|> | date_current_price(s |
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Sensor to collect the reference daily prices of electricity ('PVPC') in Spain."""
import logging
from random import randint
from typing import Optional
from aiopvpc import PVPCData
from homeassistant import config_entries
from homeassistant.const import CONF_NAME, ENERGY_KILO_WATT_HOUR
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.event import async_call_later, async_track_time_change
from homeassistant.helpers.restore_state import RestoreEntity
import homeassistant.util.dt as dt_util
from .const import ATTR_TARIFF
_LOGGER = logging.getLogger(__name__)
ATTR_PRICE = "price"
ICON = "mdi:currency-eur"
UNIT = f"€/{ENERGY_KILO_WATT_HOUR}"
_DEFAULT_TIMEOUT = 10
async def async_setup_entry(
hass: HomeAssistant, config_entry: config_entries.ConfigEntry, async_add_entities
):
"""Set up the electricity price sensor from config_entry."""
name = config_entry.data[CONF_NAME]
pvpc_data_handler = PVPCData(
tariff=config_entry.data[ATTR_TARIFF],
local_timezone=hass.config.time_zone,
websession=async_get_clientsession(hass),
logger=_LOGGER,
timeout=_DEFAULT_TIMEOUT,
)
async_add_entities(
[ElecPriceSensor(name, config_entry.unique_id, pvpc_data_handler)], False
)
class ElecPriceSensor(RestoreEntity):
"""Class to hold the prices of electricity as a sensor."""
unit_of_measurement = UNIT
icon = ICON
should_poll = False
def __init__(self, name, unique_id, pvpc_data_handler):
"""Initialize the sensor object."""
self._name = name
self._unique_id = unique_id
self._pvpc_data = pvpc_data_handler
self._num_retries = 0
self._hourly_tracker = None
self._price_tracker = None
async def async_will_remove_from_hass(self) -> None:
"""Cancel listeners for sensor updates."""
self._hourly_tracker()
self._price_tracker()
async def async_added_to_hass(self):
"""Handle entity which will be added."""
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._pvpc_data.state = state.state
# Update 'state' value in hour changes
self._hourly_tracker = async_track_time_change(
self.hass, self.update_current_price, second=[0], minute=[0]
)
# Update prices at random time, 2 times/hour (don't want to upset API)
random_minute = randint(1, 29)
mins_update = [random_minute, random_minute + 30]
self._price_tracker = async_track_time_change(
self.hass, self.async_update_prices, second=[0], minute=mins_update
)
_LOGGER.debug(
"Setup of price sensor %s (%s) with tariff '%s', "
"updating prices each hour at %s min",
self.name,
self.entity_id,
self._pvpc_data.tariff,
mins_update,
)
await self.async_update_prices(dt_util.utcnow())
self.update_current_price(dt_util.utcnow())
@property
def unique_id(self) -> Optional[str]:
"""Return a unique ID."""
return self._unique_id
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the sensor."""
return self._pvpc_data.state
@property
def available(self) -> bool:
"""Return True if entity is available."""
return self._pvpc_data.state_available
@property
def device_state_attributes(self):
"""Return the state attributes."""
return self._pvpc_data.attributes
@callback
def update_current_price(self, now):
"""Update the sensor state, by selecting the current price for this hour."""
self._pvpc_data.process_state_and_attributes(now)
self.async_write_ha_state()
async def as<|fim_middle|>elf, now):
"""Update electricity prices from the ESIOS API."""
prices = await self._pvpc_data.async_update_prices(now)
if not prices and self._pvpc_data.source_available:
self._num_retries += 1
if self._num_retries > 2:
_LOGGER.warning(
"%s: repeated bad data update, mark component as unavailable source",
self.entity_id,
)
self._pvpc_data.source_available = False
return
retry_delay = 2 * self._num_retries * self._pvpc_data.timeout
_LOGGER.debug(
"%s: Bad update[retry:%d], will try again in %d s",
self.entity_id,
self._num_retries,
retry_delay,
)
async_call_later(self.hass, retry_delay, self.async_update_prices)
return
if not prices:
_LOGGER.debug("%s: data source is not yet available", self.entity_id)
return
self._num_retries = 0
if not self._pvpc_data.source_available:
self._pvpc_data.source_available = True
_LOGGER.warning("%s: component has recovered data access", self.entity_id)
self.update_current_price(now)
<|fim▁end|> | ync_update_prices(s |
<|file_name|>drivertasks.py<|end_file_name|><|fim▁begin|># Copyright 2014, Red Hat, Inc.
#
# Licensed 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.
import logging<|fim▁hole|>import threading
import time
from oslo_messaging._drivers.protocols.amqp import controller
from oslo_messaging._i18n import _LW
from oslo_messaging import exceptions
from six import moves
LOG = logging.getLogger(__name__)
class SendTask(controller.Task):
"""A task that sends a message to a target, and optionally waits for a
reply message. The caller may block until the remote confirms receipt or
the reply message has arrived.
"""
def __init__(self, target, request, wait_for_reply, deadline):
super(SendTask, self).__init__()
self._target = target
self._request = request
self._deadline = deadline
self._wait_for_reply = wait_for_reply
self._results_queue = moves.queue.Queue()
def wait(self, timeout):
"""Wait for the send to complete, and, optionally, a reply message from
the remote. Will raise MessagingTimeout if the send does not complete
or no reply is received within timeout seconds. If the request has
failed for any other reason, a MessagingException is raised.
"""
try:
result = self._results_queue.get(timeout=timeout)
except moves.queue.Empty:
if self._wait_for_reply:
reason = "Timed out waiting for a reply."
else:
reason = "Timed out waiting for send to complete."
raise exceptions.MessagingTimeout(reason)
if result["status"] == "OK":
return result.get("response", None)
raise result["error"]
def execute(self, controller):
"""Runs on eventloop thread - sends request."""
if not self._deadline or self._deadline > time.time():
controller.request(self._target, self._request,
self._results_queue, self._wait_for_reply)
else:
LOG.warning(_LW("Send request to %s aborted: TTL expired."),
self._target)
class ListenTask(controller.Task):
"""A task that creates a subscription to the given target. Messages
arriving from the target are given to the listener.
"""
def __init__(self, target, listener, notifications=False):
"""Create a subscription to the target."""
super(ListenTask, self).__init__()
self._target = target
self._listener = listener
self._notifications = notifications
def execute(self, controller):
"""Run on the eventloop thread - subscribes to target. Inbound messages
are queued to the listener's incoming queue.
"""
if self._notifications:
controller.subscribe_notifications(self._target,
self._listener.incoming)
else:
controller.subscribe(self._target, self._listener.incoming)
class ReplyTask(controller.Task):
"""A task that sends 'response' message to 'address'.
"""
def __init__(self, address, response, log_failure):
super(ReplyTask, self).__init__()
self._address = address
self._response = response
self._log_failure = log_failure
self._wakeup = threading.Event()
def wait(self):
"""Wait for the controller to send the message.
"""
self._wakeup.wait()
def execute(self, controller):
"""Run on the eventloop thread - send the response message."""
controller.response(self._address, self._response)
self._wakeup.set()<|fim▁end|> | |
<|file_name|>drivertasks.py<|end_file_name|><|fim▁begin|># Copyright 2014, Red Hat, Inc.
#
# Licensed 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.
import logging
import threading
import time
from oslo_messaging._drivers.protocols.amqp import controller
from oslo_messaging._i18n import _LW
from oslo_messaging import exceptions
from six import moves
LOG = logging.getLogger(__name__)
class SendTask(controller.Task):
<|fim_middle|>
class ListenTask(controller.Task):
"""A task that creates a subscription to the given target. Messages
arriving from the target are given to the listener.
"""
def __init__(self, target, listener, notifications=False):
"""Create a subscription to the target."""
super(ListenTask, self).__init__()
self._target = target
self._listener = listener
self._notifications = notifications
def execute(self, controller):
"""Run on the eventloop thread - subscribes to target. Inbound messages
are queued to the listener's incoming queue.
"""
if self._notifications:
controller.subscribe_notifications(self._target,
self._listener.incoming)
else:
controller.subscribe(self._target, self._listener.incoming)
class ReplyTask(controller.Task):
"""A task that sends 'response' message to 'address'.
"""
def __init__(self, address, response, log_failure):
super(ReplyTask, self).__init__()
self._address = address
self._response = response
self._log_failure = log_failure
self._wakeup = threading.Event()
def wait(self):
"""Wait for the controller to send the message.
"""
self._wakeup.wait()
def execute(self, controller):
"""Run on the eventloop thread - send the response message."""
controller.response(self._address, self._response)
self._wakeup.set()
<|fim▁end|> | """A task that sends a message to a target, and optionally waits for a
reply message. The caller may block until the remote confirms receipt or
the reply message has arrived.
"""
def __init__(self, target, request, wait_for_reply, deadline):
super(SendTask, self).__init__()
self._target = target
self._request = request
self._deadline = deadline
self._wait_for_reply = wait_for_reply
self._results_queue = moves.queue.Queue()
def wait(self, timeout):
"""Wait for the send to complete, and, optionally, a reply message from
the remote. Will raise MessagingTimeout if the send does not complete
or no reply is received within timeout seconds. If the request has
failed for any other reason, a MessagingException is raised.
"""
try:
result = self._results_queue.get(timeout=timeout)
except moves.queue.Empty:
if self._wait_for_reply:
reason = "Timed out waiting for a reply."
else:
reason = "Timed out waiting for send to complete."
raise exceptions.MessagingTimeout(reason)
if result["status"] == "OK":
return result.get("response", None)
raise result["error"]
def execute(self, controller):
"""Runs on eventloop thread - sends request."""
if not self._deadline or self._deadline > time.time():
controller.request(self._target, self._request,
self._results_queue, self._wait_for_reply)
else:
LOG.warning(_LW("Send request to %s aborted: TTL expired."),
self._target) |
<|file_name|>drivertasks.py<|end_file_name|><|fim▁begin|># Copyright 2014, Red Hat, Inc.
#
# Licensed 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.
import logging
import threading
import time
from oslo_messaging._drivers.protocols.amqp import controller
from oslo_messaging._i18n import _LW
from oslo_messaging import exceptions
from six import moves
LOG = logging.getLogger(__name__)
class SendTask(controller.Task):
"""A task that sends a message to a target, and optionally waits for a
reply message. The caller may block until the remote confirms receipt or
the reply message has arrived.
"""
def __init__(self, target, request, wait_for_reply, deadline):
<|fim_middle|>
def wait(self, timeout):
"""Wait for the send to complete, and, optionally, a reply message from
the remote. Will raise MessagingTimeout if the send does not complete
or no reply is received within timeout seconds. If the request has
failed for any other reason, a MessagingException is raised.
"""
try:
result = self._results_queue.get(timeout=timeout)
except moves.queue.Empty:
if self._wait_for_reply:
reason = "Timed out waiting for a reply."
else:
reason = "Timed out waiting for send to complete."
raise exceptions.MessagingTimeout(reason)
if result["status"] == "OK":
return result.get("response", None)
raise result["error"]
def execute(self, controller):
"""Runs on eventloop thread - sends request."""
if not self._deadline or self._deadline > time.time():
controller.request(self._target, self._request,
self._results_queue, self._wait_for_reply)
else:
LOG.warning(_LW("Send request to %s aborted: TTL expired."),
self._target)
class ListenTask(controller.Task):
"""A task that creates a subscription to the given target. Messages
arriving from the target are given to the listener.
"""
def __init__(self, target, listener, notifications=False):
"""Create a subscription to the target."""
super(ListenTask, self).__init__()
self._target = target
self._listener = listener
self._notifications = notifications
def execute(self, controller):
"""Run on the eventloop thread - subscribes to target. Inbound messages
are queued to the listener's incoming queue.
"""
if self._notifications:
controller.subscribe_notifications(self._target,
self._listener.incoming)
else:
controller.subscribe(self._target, self._listener.incoming)
class ReplyTask(controller.Task):
"""A task that sends 'response' message to 'address'.
"""
def __init__(self, address, response, log_failure):
super(ReplyTask, self).__init__()
self._address = address
self._response = response
self._log_failure = log_failure
self._wakeup = threading.Event()
def wait(self):
"""Wait for the controller to send the message.
"""
self._wakeup.wait()
def execute(self, controller):
"""Run on the eventloop thread - send the response message."""
controller.response(self._address, self._response)
self._wakeup.set()
<|fim▁end|> | super(SendTask, self).__init__()
self._target = target
self._request = request
self._deadline = deadline
self._wait_for_reply = wait_for_reply
self._results_queue = moves.queue.Queue() |
<|file_name|>drivertasks.py<|end_file_name|><|fim▁begin|># Copyright 2014, Red Hat, Inc.
#
# Licensed 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.
import logging
import threading
import time
from oslo_messaging._drivers.protocols.amqp import controller
from oslo_messaging._i18n import _LW
from oslo_messaging import exceptions
from six import moves
LOG = logging.getLogger(__name__)
class SendTask(controller.Task):
"""A task that sends a message to a target, and optionally waits for a
reply message. The caller may block until the remote confirms receipt or
the reply message has arrived.
"""
def __init__(self, target, request, wait_for_reply, deadline):
super(SendTask, self).__init__()
self._target = target
self._request = request
self._deadline = deadline
self._wait_for_reply = wait_for_reply
self._results_queue = moves.queue.Queue()
def wait(self, timeout):
<|fim_middle|>
def execute(self, controller):
"""Runs on eventloop thread - sends request."""
if not self._deadline or self._deadline > time.time():
controller.request(self._target, self._request,
self._results_queue, self._wait_for_reply)
else:
LOG.warning(_LW("Send request to %s aborted: TTL expired."),
self._target)
class ListenTask(controller.Task):
"""A task that creates a subscription to the given target. Messages
arriving from the target are given to the listener.
"""
def __init__(self, target, listener, notifications=False):
"""Create a subscription to the target."""
super(ListenTask, self).__init__()
self._target = target
self._listener = listener
self._notifications = notifications
def execute(self, controller):
"""Run on the eventloop thread - subscribes to target. Inbound messages
are queued to the listener's incoming queue.
"""
if self._notifications:
controller.subscribe_notifications(self._target,
self._listener.incoming)
else:
controller.subscribe(self._target, self._listener.incoming)
class ReplyTask(controller.Task):
"""A task that sends 'response' message to 'address'.
"""
def __init__(self, address, response, log_failure):
super(ReplyTask, self).__init__()
self._address = address
self._response = response
self._log_failure = log_failure
self._wakeup = threading.Event()
def wait(self):
"""Wait for the controller to send the message.
"""
self._wakeup.wait()
def execute(self, controller):
"""Run on the eventloop thread - send the response message."""
controller.response(self._address, self._response)
self._wakeup.set()
<|fim▁end|> | """Wait for the send to complete, and, optionally, a reply message from
the remote. Will raise MessagingTimeout if the send does not complete
or no reply is received within timeout seconds. If the request has
failed for any other reason, a MessagingException is raised.
"""
try:
result = self._results_queue.get(timeout=timeout)
except moves.queue.Empty:
if self._wait_for_reply:
reason = "Timed out waiting for a reply."
else:
reason = "Timed out waiting for send to complete."
raise exceptions.MessagingTimeout(reason)
if result["status"] == "OK":
return result.get("response", None)
raise result["error"] |
<|file_name|>drivertasks.py<|end_file_name|><|fim▁begin|># Copyright 2014, Red Hat, Inc.
#
# Licensed 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.
import logging
import threading
import time
from oslo_messaging._drivers.protocols.amqp import controller
from oslo_messaging._i18n import _LW
from oslo_messaging import exceptions
from six import moves
LOG = logging.getLogger(__name__)
class SendTask(controller.Task):
"""A task that sends a message to a target, and optionally waits for a
reply message. The caller may block until the remote confirms receipt or
the reply message has arrived.
"""
def __init__(self, target, request, wait_for_reply, deadline):
super(SendTask, self).__init__()
self._target = target
self._request = request
self._deadline = deadline
self._wait_for_reply = wait_for_reply
self._results_queue = moves.queue.Queue()
def wait(self, timeout):
"""Wait for the send to complete, and, optionally, a reply message from
the remote. Will raise MessagingTimeout if the send does not complete
or no reply is received within timeout seconds. If the request has
failed for any other reason, a MessagingException is raised.
"""
try:
result = self._results_queue.get(timeout=timeout)
except moves.queue.Empty:
if self._wait_for_reply:
reason = "Timed out waiting for a reply."
else:
reason = "Timed out waiting for send to complete."
raise exceptions.MessagingTimeout(reason)
if result["status"] == "OK":
return result.get("response", None)
raise result["error"]
def execute(self, controller):
<|fim_middle|>
class ListenTask(controller.Task):
"""A task that creates a subscription to the given target. Messages
arriving from the target are given to the listener.
"""
def __init__(self, target, listener, notifications=False):
"""Create a subscription to the target."""
super(ListenTask, self).__init__()
self._target = target
self._listener = listener
self._notifications = notifications
def execute(self, controller):
"""Run on the eventloop thread - subscribes to target. Inbound messages
are queued to the listener's incoming queue.
"""
if self._notifications:
controller.subscribe_notifications(self._target,
self._listener.incoming)
else:
controller.subscribe(self._target, self._listener.incoming)
class ReplyTask(controller.Task):
"""A task that sends 'response' message to 'address'.
"""
def __init__(self, address, response, log_failure):
super(ReplyTask, self).__init__()
self._address = address
self._response = response
self._log_failure = log_failure
self._wakeup = threading.Event()
def wait(self):
"""Wait for the controller to send the message.
"""
self._wakeup.wait()
def execute(self, controller):
"""Run on the eventloop thread - send the response message."""
controller.response(self._address, self._response)
self._wakeup.set()
<|fim▁end|> | """Runs on eventloop thread - sends request."""
if not self._deadline or self._deadline > time.time():
controller.request(self._target, self._request,
self._results_queue, self._wait_for_reply)
else:
LOG.warning(_LW("Send request to %s aborted: TTL expired."),
self._target) |
<|file_name|>drivertasks.py<|end_file_name|><|fim▁begin|># Copyright 2014, Red Hat, Inc.
#
# Licensed 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.
import logging
import threading
import time
from oslo_messaging._drivers.protocols.amqp import controller
from oslo_messaging._i18n import _LW
from oslo_messaging import exceptions
from six import moves
LOG = logging.getLogger(__name__)
class SendTask(controller.Task):
"""A task that sends a message to a target, and optionally waits for a
reply message. The caller may block until the remote confirms receipt or
the reply message has arrived.
"""
def __init__(self, target, request, wait_for_reply, deadline):
super(SendTask, self).__init__()
self._target = target
self._request = request
self._deadline = deadline
self._wait_for_reply = wait_for_reply
self._results_queue = moves.queue.Queue()
def wait(self, timeout):
"""Wait for the send to complete, and, optionally, a reply message from
the remote. Will raise MessagingTimeout if the send does not complete
or no reply is received within timeout seconds. If the request has
failed for any other reason, a MessagingException is raised.
"""
try:
result = self._results_queue.get(timeout=timeout)
except moves.queue.Empty:
if self._wait_for_reply:
reason = "Timed out waiting for a reply."
else:
reason = "Timed out waiting for send to complete."
raise exceptions.MessagingTimeout(reason)
if result["status"] == "OK":
return result.get("response", None)
raise result["error"]
def execute(self, controller):
"""Runs on eventloop thread - sends request."""
if not self._deadline or self._deadline > time.time():
controller.request(self._target, self._request,
self._results_queue, self._wait_for_reply)
else:
LOG.warning(_LW("Send request to %s aborted: TTL expired."),
self._target)
class ListenTask(controller.Task):
<|fim_middle|>
class ReplyTask(controller.Task):
"""A task that sends 'response' message to 'address'.
"""
def __init__(self, address, response, log_failure):
super(ReplyTask, self).__init__()
self._address = address
self._response = response
self._log_failure = log_failure
self._wakeup = threading.Event()
def wait(self):
"""Wait for the controller to send the message.
"""
self._wakeup.wait()
def execute(self, controller):
"""Run on the eventloop thread - send the response message."""
controller.response(self._address, self._response)
self._wakeup.set()
<|fim▁end|> | """A task that creates a subscription to the given target. Messages
arriving from the target are given to the listener.
"""
def __init__(self, target, listener, notifications=False):
"""Create a subscription to the target."""
super(ListenTask, self).__init__()
self._target = target
self._listener = listener
self._notifications = notifications
def execute(self, controller):
"""Run on the eventloop thread - subscribes to target. Inbound messages
are queued to the listener's incoming queue.
"""
if self._notifications:
controller.subscribe_notifications(self._target,
self._listener.incoming)
else:
controller.subscribe(self._target, self._listener.incoming) |
<|file_name|>drivertasks.py<|end_file_name|><|fim▁begin|># Copyright 2014, Red Hat, Inc.
#
# Licensed 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.
import logging
import threading
import time
from oslo_messaging._drivers.protocols.amqp import controller
from oslo_messaging._i18n import _LW
from oslo_messaging import exceptions
from six import moves
LOG = logging.getLogger(__name__)
class SendTask(controller.Task):
"""A task that sends a message to a target, and optionally waits for a
reply message. The caller may block until the remote confirms receipt or
the reply message has arrived.
"""
def __init__(self, target, request, wait_for_reply, deadline):
super(SendTask, self).__init__()
self._target = target
self._request = request
self._deadline = deadline
self._wait_for_reply = wait_for_reply
self._results_queue = moves.queue.Queue()
def wait(self, timeout):
"""Wait for the send to complete, and, optionally, a reply message from
the remote. Will raise MessagingTimeout if the send does not complete
or no reply is received within timeout seconds. If the request has
failed for any other reason, a MessagingException is raised.
"""
try:
result = self._results_queue.get(timeout=timeout)
except moves.queue.Empty:
if self._wait_for_reply:
reason = "Timed out waiting for a reply."
else:
reason = "Timed out waiting for send to complete."
raise exceptions.MessagingTimeout(reason)
if result["status"] == "OK":
return result.get("response", None)
raise result["error"]
def execute(self, controller):
"""Runs on eventloop thread - sends request."""
if not self._deadline or self._deadline > time.time():
controller.request(self._target, self._request,
self._results_queue, self._wait_for_reply)
else:
LOG.warning(_LW("Send request to %s aborted: TTL expired."),
self._target)
class ListenTask(controller.Task):
"""A task that creates a subscription to the given target. Messages
arriving from the target are given to the listener.
"""
def __init__(self, target, listener, notifications=False):
<|fim_middle|>
def execute(self, controller):
"""Run on the eventloop thread - subscribes to target. Inbound messages
are queued to the listener's incoming queue.
"""
if self._notifications:
controller.subscribe_notifications(self._target,
self._listener.incoming)
else:
controller.subscribe(self._target, self._listener.incoming)
class ReplyTask(controller.Task):
"""A task that sends 'response' message to 'address'.
"""
def __init__(self, address, response, log_failure):
super(ReplyTask, self).__init__()
self._address = address
self._response = response
self._log_failure = log_failure
self._wakeup = threading.Event()
def wait(self):
"""Wait for the controller to send the message.
"""
self._wakeup.wait()
def execute(self, controller):
"""Run on the eventloop thread - send the response message."""
controller.response(self._address, self._response)
self._wakeup.set()
<|fim▁end|> | """Create a subscription to the target."""
super(ListenTask, self).__init__()
self._target = target
self._listener = listener
self._notifications = notifications |
<|file_name|>drivertasks.py<|end_file_name|><|fim▁begin|># Copyright 2014, Red Hat, Inc.
#
# Licensed 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.
import logging
import threading
import time
from oslo_messaging._drivers.protocols.amqp import controller
from oslo_messaging._i18n import _LW
from oslo_messaging import exceptions
from six import moves
LOG = logging.getLogger(__name__)
class SendTask(controller.Task):
"""A task that sends a message to a target, and optionally waits for a
reply message. The caller may block until the remote confirms receipt or
the reply message has arrived.
"""
def __init__(self, target, request, wait_for_reply, deadline):
super(SendTask, self).__init__()
self._target = target
self._request = request
self._deadline = deadline
self._wait_for_reply = wait_for_reply
self._results_queue = moves.queue.Queue()
def wait(self, timeout):
"""Wait for the send to complete, and, optionally, a reply message from
the remote. Will raise MessagingTimeout if the send does not complete
or no reply is received within timeout seconds. If the request has
failed for any other reason, a MessagingException is raised.
"""
try:
result = self._results_queue.get(timeout=timeout)
except moves.queue.Empty:
if self._wait_for_reply:
reason = "Timed out waiting for a reply."
else:
reason = "Timed out waiting for send to complete."
raise exceptions.MessagingTimeout(reason)
if result["status"] == "OK":
return result.get("response", None)
raise result["error"]
def execute(self, controller):
"""Runs on eventloop thread - sends request."""
if not self._deadline or self._deadline > time.time():
controller.request(self._target, self._request,
self._results_queue, self._wait_for_reply)
else:
LOG.warning(_LW("Send request to %s aborted: TTL expired."),
self._target)
class ListenTask(controller.Task):
"""A task that creates a subscription to the given target. Messages
arriving from the target are given to the listener.
"""
def __init__(self, target, listener, notifications=False):
"""Create a subscription to the target."""
super(ListenTask, self).__init__()
self._target = target
self._listener = listener
self._notifications = notifications
def execute(self, controller):
<|fim_middle|>
class ReplyTask(controller.Task):
"""A task that sends 'response' message to 'address'.
"""
def __init__(self, address, response, log_failure):
super(ReplyTask, self).__init__()
self._address = address
self._response = response
self._log_failure = log_failure
self._wakeup = threading.Event()
def wait(self):
"""Wait for the controller to send the message.
"""
self._wakeup.wait()
def execute(self, controller):
"""Run on the eventloop thread - send the response message."""
controller.response(self._address, self._response)
self._wakeup.set()
<|fim▁end|> | """Run on the eventloop thread - subscribes to target. Inbound messages
are queued to the listener's incoming queue.
"""
if self._notifications:
controller.subscribe_notifications(self._target,
self._listener.incoming)
else:
controller.subscribe(self._target, self._listener.incoming) |
<|file_name|>drivertasks.py<|end_file_name|><|fim▁begin|># Copyright 2014, Red Hat, Inc.
#
# Licensed 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.
import logging
import threading
import time
from oslo_messaging._drivers.protocols.amqp import controller
from oslo_messaging._i18n import _LW
from oslo_messaging import exceptions
from six import moves
LOG = logging.getLogger(__name__)
class SendTask(controller.Task):
"""A task that sends a message to a target, and optionally waits for a
reply message. The caller may block until the remote confirms receipt or
the reply message has arrived.
"""
def __init__(self, target, request, wait_for_reply, deadline):
super(SendTask, self).__init__()
self._target = target
self._request = request
self._deadline = deadline
self._wait_for_reply = wait_for_reply
self._results_queue = moves.queue.Queue()
def wait(self, timeout):
"""Wait for the send to complete, and, optionally, a reply message from
the remote. Will raise MessagingTimeout if the send does not complete
or no reply is received within timeout seconds. If the request has
failed for any other reason, a MessagingException is raised.
"""
try:
result = self._results_queue.get(timeout=timeout)
except moves.queue.Empty:
if self._wait_for_reply:
reason = "Timed out waiting for a reply."
else:
reason = "Timed out waiting for send to complete."
raise exceptions.MessagingTimeout(reason)
if result["status"] == "OK":
return result.get("response", None)
raise result["error"]
def execute(self, controller):
"""Runs on eventloop thread - sends request."""
if not self._deadline or self._deadline > time.time():
controller.request(self._target, self._request,
self._results_queue, self._wait_for_reply)
else:
LOG.warning(_LW("Send request to %s aborted: TTL expired."),
self._target)
class ListenTask(controller.Task):
"""A task that creates a subscription to the given target. Messages
arriving from the target are given to the listener.
"""
def __init__(self, target, listener, notifications=False):
"""Create a subscription to the target."""
super(ListenTask, self).__init__()
self._target = target
self._listener = listener
self._notifications = notifications
def execute(self, controller):
"""Run on the eventloop thread - subscribes to target. Inbound messages
are queued to the listener's incoming queue.
"""
if self._notifications:
controller.subscribe_notifications(self._target,
self._listener.incoming)
else:
controller.subscribe(self._target, self._listener.incoming)
class ReplyTask(controller.Task):
<|fim_middle|>
<|fim▁end|> | """A task that sends 'response' message to 'address'.
"""
def __init__(self, address, response, log_failure):
super(ReplyTask, self).__init__()
self._address = address
self._response = response
self._log_failure = log_failure
self._wakeup = threading.Event()
def wait(self):
"""Wait for the controller to send the message.
"""
self._wakeup.wait()
def execute(self, controller):
"""Run on the eventloop thread - send the response message."""
controller.response(self._address, self._response)
self._wakeup.set() |
<|file_name|>drivertasks.py<|end_file_name|><|fim▁begin|># Copyright 2014, Red Hat, Inc.
#
# Licensed 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.
import logging
import threading
import time
from oslo_messaging._drivers.protocols.amqp import controller
from oslo_messaging._i18n import _LW
from oslo_messaging import exceptions
from six import moves
LOG = logging.getLogger(__name__)
class SendTask(controller.Task):
"""A task that sends a message to a target, and optionally waits for a
reply message. The caller may block until the remote confirms receipt or
the reply message has arrived.
"""
def __init__(self, target, request, wait_for_reply, deadline):
super(SendTask, self).__init__()
self._target = target
self._request = request
self._deadline = deadline
self._wait_for_reply = wait_for_reply
self._results_queue = moves.queue.Queue()
def wait(self, timeout):
"""Wait for the send to complete, and, optionally, a reply message from
the remote. Will raise MessagingTimeout if the send does not complete
or no reply is received within timeout seconds. If the request has
failed for any other reason, a MessagingException is raised.
"""
try:
result = self._results_queue.get(timeout=timeout)
except moves.queue.Empty:
if self._wait_for_reply:
reason = "Timed out waiting for a reply."
else:
reason = "Timed out waiting for send to complete."
raise exceptions.MessagingTimeout(reason)
if result["status"] == "OK":
return result.get("response", None)
raise result["error"]
def execute(self, controller):
"""Runs on eventloop thread - sends request."""
if not self._deadline or self._deadline > time.time():
controller.request(self._target, self._request,
self._results_queue, self._wait_for_reply)
else:
LOG.warning(_LW("Send request to %s aborted: TTL expired."),
self._target)
class ListenTask(controller.Task):
"""A task that creates a subscription to the given target. Messages
arriving from the target are given to the listener.
"""
def __init__(self, target, listener, notifications=False):
"""Create a subscription to the target."""
super(ListenTask, self).__init__()
self._target = target
self._listener = listener
self._notifications = notifications
def execute(self, controller):
"""Run on the eventloop thread - subscribes to target. Inbound messages
are queued to the listener's incoming queue.
"""
if self._notifications:
controller.subscribe_notifications(self._target,
self._listener.incoming)
else:
controller.subscribe(self._target, self._listener.incoming)
class ReplyTask(controller.Task):
"""A task that sends 'response' message to 'address'.
"""
def __init__(self, address, response, log_failure):
<|fim_middle|>
def wait(self):
"""Wait for the controller to send the message.
"""
self._wakeup.wait()
def execute(self, controller):
"""Run on the eventloop thread - send the response message."""
controller.response(self._address, self._response)
self._wakeup.set()
<|fim▁end|> | super(ReplyTask, self).__init__()
self._address = address
self._response = response
self._log_failure = log_failure
self._wakeup = threading.Event() |
<|file_name|>drivertasks.py<|end_file_name|><|fim▁begin|># Copyright 2014, Red Hat, Inc.
#
# Licensed 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.
import logging
import threading
import time
from oslo_messaging._drivers.protocols.amqp import controller
from oslo_messaging._i18n import _LW
from oslo_messaging import exceptions
from six import moves
LOG = logging.getLogger(__name__)
class SendTask(controller.Task):
"""A task that sends a message to a target, and optionally waits for a
reply message. The caller may block until the remote confirms receipt or
the reply message has arrived.
"""
def __init__(self, target, request, wait_for_reply, deadline):
super(SendTask, self).__init__()
self._target = target
self._request = request
self._deadline = deadline
self._wait_for_reply = wait_for_reply
self._results_queue = moves.queue.Queue()
def wait(self, timeout):
"""Wait for the send to complete, and, optionally, a reply message from
the remote. Will raise MessagingTimeout if the send does not complete
or no reply is received within timeout seconds. If the request has
failed for any other reason, a MessagingException is raised.
"""
try:
result = self._results_queue.get(timeout=timeout)
except moves.queue.Empty:
if self._wait_for_reply:
reason = "Timed out waiting for a reply."
else:
reason = "Timed out waiting for send to complete."
raise exceptions.MessagingTimeout(reason)
if result["status"] == "OK":
return result.get("response", None)
raise result["error"]
def execute(self, controller):
"""Runs on eventloop thread - sends request."""
if not self._deadline or self._deadline > time.time():
controller.request(self._target, self._request,
self._results_queue, self._wait_for_reply)
else:
LOG.warning(_LW("Send request to %s aborted: TTL expired."),
self._target)
class ListenTask(controller.Task):
"""A task that creates a subscription to the given target. Messages
arriving from the target are given to the listener.
"""
def __init__(self, target, listener, notifications=False):
"""Create a subscription to the target."""
super(ListenTask, self).__init__()
self._target = target
self._listener = listener
self._notifications = notifications
def execute(self, controller):
"""Run on the eventloop thread - subscribes to target. Inbound messages
are queued to the listener's incoming queue.
"""
if self._notifications:
controller.subscribe_notifications(self._target,
self._listener.incoming)
else:
controller.subscribe(self._target, self._listener.incoming)
class ReplyTask(controller.Task):
"""A task that sends 'response' message to 'address'.
"""
def __init__(self, address, response, log_failure):
super(ReplyTask, self).__init__()
self._address = address
self._response = response
self._log_failure = log_failure
self._wakeup = threading.Event()
def wait(self):
<|fim_middle|>
def execute(self, controller):
"""Run on the eventloop thread - send the response message."""
controller.response(self._address, self._response)
self._wakeup.set()
<|fim▁end|> | """Wait for the controller to send the message.
"""
self._wakeup.wait() |
<|file_name|>drivertasks.py<|end_file_name|><|fim▁begin|># Copyright 2014, Red Hat, Inc.
#
# Licensed 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.
import logging
import threading
import time
from oslo_messaging._drivers.protocols.amqp import controller
from oslo_messaging._i18n import _LW
from oslo_messaging import exceptions
from six import moves
LOG = logging.getLogger(__name__)
class SendTask(controller.Task):
"""A task that sends a message to a target, and optionally waits for a
reply message. The caller may block until the remote confirms receipt or
the reply message has arrived.
"""
def __init__(self, target, request, wait_for_reply, deadline):
super(SendTask, self).__init__()
self._target = target
self._request = request
self._deadline = deadline
self._wait_for_reply = wait_for_reply
self._results_queue = moves.queue.Queue()
def wait(self, timeout):
"""Wait for the send to complete, and, optionally, a reply message from
the remote. Will raise MessagingTimeout if the send does not complete
or no reply is received within timeout seconds. If the request has
failed for any other reason, a MessagingException is raised.
"""
try:
result = self._results_queue.get(timeout=timeout)
except moves.queue.Empty:
if self._wait_for_reply:
reason = "Timed out waiting for a reply."
else:
reason = "Timed out waiting for send to complete."
raise exceptions.MessagingTimeout(reason)
if result["status"] == "OK":
return result.get("response", None)
raise result["error"]
def execute(self, controller):
"""Runs on eventloop thread - sends request."""
if not self._deadline or self._deadline > time.time():
controller.request(self._target, self._request,
self._results_queue, self._wait_for_reply)
else:
LOG.warning(_LW("Send request to %s aborted: TTL expired."),
self._target)
class ListenTask(controller.Task):
"""A task that creates a subscription to the given target. Messages
arriving from the target are given to the listener.
"""
def __init__(self, target, listener, notifications=False):
"""Create a subscription to the target."""
super(ListenTask, self).__init__()
self._target = target
self._listener = listener
self._notifications = notifications
def execute(self, controller):
"""Run on the eventloop thread - subscribes to target. Inbound messages
are queued to the listener's incoming queue.
"""
if self._notifications:
controller.subscribe_notifications(self._target,
self._listener.incoming)
else:
controller.subscribe(self._target, self._listener.incoming)
class ReplyTask(controller.Task):
"""A task that sends 'response' message to 'address'.
"""
def __init__(self, address, response, log_failure):
super(ReplyTask, self).__init__()
self._address = address
self._response = response
self._log_failure = log_failure
self._wakeup = threading.Event()
def wait(self):
"""Wait for the controller to send the message.
"""
self._wakeup.wait()
def execute(self, controller):
<|fim_middle|>
<|fim▁end|> | """Run on the eventloop thread - send the response message."""
controller.response(self._address, self._response)
self._wakeup.set() |
<|file_name|>drivertasks.py<|end_file_name|><|fim▁begin|># Copyright 2014, Red Hat, Inc.
#
# Licensed 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.
import logging
import threading
import time
from oslo_messaging._drivers.protocols.amqp import controller
from oslo_messaging._i18n import _LW
from oslo_messaging import exceptions
from six import moves
LOG = logging.getLogger(__name__)
class SendTask(controller.Task):
"""A task that sends a message to a target, and optionally waits for a
reply message. The caller may block until the remote confirms receipt or
the reply message has arrived.
"""
def __init__(self, target, request, wait_for_reply, deadline):
super(SendTask, self).__init__()
self._target = target
self._request = request
self._deadline = deadline
self._wait_for_reply = wait_for_reply
self._results_queue = moves.queue.Queue()
def wait(self, timeout):
"""Wait for the send to complete, and, optionally, a reply message from
the remote. Will raise MessagingTimeout if the send does not complete
or no reply is received within timeout seconds. If the request has
failed for any other reason, a MessagingException is raised.
"""
try:
result = self._results_queue.get(timeout=timeout)
except moves.queue.Empty:
if self._wait_for_reply:
<|fim_middle|>
else:
reason = "Timed out waiting for send to complete."
raise exceptions.MessagingTimeout(reason)
if result["status"] == "OK":
return result.get("response", None)
raise result["error"]
def execute(self, controller):
"""Runs on eventloop thread - sends request."""
if not self._deadline or self._deadline > time.time():
controller.request(self._target, self._request,
self._results_queue, self._wait_for_reply)
else:
LOG.warning(_LW("Send request to %s aborted: TTL expired."),
self._target)
class ListenTask(controller.Task):
"""A task that creates a subscription to the given target. Messages
arriving from the target are given to the listener.
"""
def __init__(self, target, listener, notifications=False):
"""Create a subscription to the target."""
super(ListenTask, self).__init__()
self._target = target
self._listener = listener
self._notifications = notifications
def execute(self, controller):
"""Run on the eventloop thread - subscribes to target. Inbound messages
are queued to the listener's incoming queue.
"""
if self._notifications:
controller.subscribe_notifications(self._target,
self._listener.incoming)
else:
controller.subscribe(self._target, self._listener.incoming)
class ReplyTask(controller.Task):
"""A task that sends 'response' message to 'address'.
"""
def __init__(self, address, response, log_failure):
super(ReplyTask, self).__init__()
self._address = address
self._response = response
self._log_failure = log_failure
self._wakeup = threading.Event()
def wait(self):
"""Wait for the controller to send the message.
"""
self._wakeup.wait()
def execute(self, controller):
"""Run on the eventloop thread - send the response message."""
controller.response(self._address, self._response)
self._wakeup.set()
<|fim▁end|> | reason = "Timed out waiting for a reply." |
<|file_name|>drivertasks.py<|end_file_name|><|fim▁begin|># Copyright 2014, Red Hat, Inc.
#
# Licensed 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.
import logging
import threading
import time
from oslo_messaging._drivers.protocols.amqp import controller
from oslo_messaging._i18n import _LW
from oslo_messaging import exceptions
from six import moves
LOG = logging.getLogger(__name__)
class SendTask(controller.Task):
"""A task that sends a message to a target, and optionally waits for a
reply message. The caller may block until the remote confirms receipt or
the reply message has arrived.
"""
def __init__(self, target, request, wait_for_reply, deadline):
super(SendTask, self).__init__()
self._target = target
self._request = request
self._deadline = deadline
self._wait_for_reply = wait_for_reply
self._results_queue = moves.queue.Queue()
def wait(self, timeout):
"""Wait for the send to complete, and, optionally, a reply message from
the remote. Will raise MessagingTimeout if the send does not complete
or no reply is received within timeout seconds. If the request has
failed for any other reason, a MessagingException is raised.
"""
try:
result = self._results_queue.get(timeout=timeout)
except moves.queue.Empty:
if self._wait_for_reply:
reason = "Timed out waiting for a reply."
else:
<|fim_middle|>
raise exceptions.MessagingTimeout(reason)
if result["status"] == "OK":
return result.get("response", None)
raise result["error"]
def execute(self, controller):
"""Runs on eventloop thread - sends request."""
if not self._deadline or self._deadline > time.time():
controller.request(self._target, self._request,
self._results_queue, self._wait_for_reply)
else:
LOG.warning(_LW("Send request to %s aborted: TTL expired."),
self._target)
class ListenTask(controller.Task):
"""A task that creates a subscription to the given target. Messages
arriving from the target are given to the listener.
"""
def __init__(self, target, listener, notifications=False):
"""Create a subscription to the target."""
super(ListenTask, self).__init__()
self._target = target
self._listener = listener
self._notifications = notifications
def execute(self, controller):
"""Run on the eventloop thread - subscribes to target. Inbound messages
are queued to the listener's incoming queue.
"""
if self._notifications:
controller.subscribe_notifications(self._target,
self._listener.incoming)
else:
controller.subscribe(self._target, self._listener.incoming)
class ReplyTask(controller.Task):
"""A task that sends 'response' message to 'address'.
"""
def __init__(self, address, response, log_failure):
super(ReplyTask, self).__init__()
self._address = address
self._response = response
self._log_failure = log_failure
self._wakeup = threading.Event()
def wait(self):
"""Wait for the controller to send the message.
"""
self._wakeup.wait()
def execute(self, controller):
"""Run on the eventloop thread - send the response message."""
controller.response(self._address, self._response)
self._wakeup.set()
<|fim▁end|> | reason = "Timed out waiting for send to complete." |
<|file_name|>drivertasks.py<|end_file_name|><|fim▁begin|># Copyright 2014, Red Hat, Inc.
#
# Licensed 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.
import logging
import threading
import time
from oslo_messaging._drivers.protocols.amqp import controller
from oslo_messaging._i18n import _LW
from oslo_messaging import exceptions
from six import moves
LOG = logging.getLogger(__name__)
class SendTask(controller.Task):
"""A task that sends a message to a target, and optionally waits for a
reply message. The caller may block until the remote confirms receipt or
the reply message has arrived.
"""
def __init__(self, target, request, wait_for_reply, deadline):
super(SendTask, self).__init__()
self._target = target
self._request = request
self._deadline = deadline
self._wait_for_reply = wait_for_reply
self._results_queue = moves.queue.Queue()
def wait(self, timeout):
"""Wait for the send to complete, and, optionally, a reply message from
the remote. Will raise MessagingTimeout if the send does not complete
or no reply is received within timeout seconds. If the request has
failed for any other reason, a MessagingException is raised.
"""
try:
result = self._results_queue.get(timeout=timeout)
except moves.queue.Empty:
if self._wait_for_reply:
reason = "Timed out waiting for a reply."
else:
reason = "Timed out waiting for send to complete."
raise exceptions.MessagingTimeout(reason)
if result["status"] == "OK":
<|fim_middle|>
raise result["error"]
def execute(self, controller):
"""Runs on eventloop thread - sends request."""
if not self._deadline or self._deadline > time.time():
controller.request(self._target, self._request,
self._results_queue, self._wait_for_reply)
else:
LOG.warning(_LW("Send request to %s aborted: TTL expired."),
self._target)
class ListenTask(controller.Task):
"""A task that creates a subscription to the given target. Messages
arriving from the target are given to the listener.
"""
def __init__(self, target, listener, notifications=False):
"""Create a subscription to the target."""
super(ListenTask, self).__init__()
self._target = target
self._listener = listener
self._notifications = notifications
def execute(self, controller):
"""Run on the eventloop thread - subscribes to target. Inbound messages
are queued to the listener's incoming queue.
"""
if self._notifications:
controller.subscribe_notifications(self._target,
self._listener.incoming)
else:
controller.subscribe(self._target, self._listener.incoming)
class ReplyTask(controller.Task):
"""A task that sends 'response' message to 'address'.
"""
def __init__(self, address, response, log_failure):
super(ReplyTask, self).__init__()
self._address = address
self._response = response
self._log_failure = log_failure
self._wakeup = threading.Event()
def wait(self):
"""Wait for the controller to send the message.
"""
self._wakeup.wait()
def execute(self, controller):
"""Run on the eventloop thread - send the response message."""
controller.response(self._address, self._response)
self._wakeup.set()
<|fim▁end|> | return result.get("response", None) |
<|file_name|>drivertasks.py<|end_file_name|><|fim▁begin|># Copyright 2014, Red Hat, Inc.
#
# Licensed 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.
import logging
import threading
import time
from oslo_messaging._drivers.protocols.amqp import controller
from oslo_messaging._i18n import _LW
from oslo_messaging import exceptions
from six import moves
LOG = logging.getLogger(__name__)
class SendTask(controller.Task):
"""A task that sends a message to a target, and optionally waits for a
reply message. The caller may block until the remote confirms receipt or
the reply message has arrived.
"""
def __init__(self, target, request, wait_for_reply, deadline):
super(SendTask, self).__init__()
self._target = target
self._request = request
self._deadline = deadline
self._wait_for_reply = wait_for_reply
self._results_queue = moves.queue.Queue()
def wait(self, timeout):
"""Wait for the send to complete, and, optionally, a reply message from
the remote. Will raise MessagingTimeout if the send does not complete
or no reply is received within timeout seconds. If the request has
failed for any other reason, a MessagingException is raised.
"""
try:
result = self._results_queue.get(timeout=timeout)
except moves.queue.Empty:
if self._wait_for_reply:
reason = "Timed out waiting for a reply."
else:
reason = "Timed out waiting for send to complete."
raise exceptions.MessagingTimeout(reason)
if result["status"] == "OK":
return result.get("response", None)
raise result["error"]
def execute(self, controller):
"""Runs on eventloop thread - sends request."""
if not self._deadline or self._deadline > time.time():
<|fim_middle|>
else:
LOG.warning(_LW("Send request to %s aborted: TTL expired."),
self._target)
class ListenTask(controller.Task):
"""A task that creates a subscription to the given target. Messages
arriving from the target are given to the listener.
"""
def __init__(self, target, listener, notifications=False):
"""Create a subscription to the target."""
super(ListenTask, self).__init__()
self._target = target
self._listener = listener
self._notifications = notifications
def execute(self, controller):
"""Run on the eventloop thread - subscribes to target. Inbound messages
are queued to the listener's incoming queue.
"""
if self._notifications:
controller.subscribe_notifications(self._target,
self._listener.incoming)
else:
controller.subscribe(self._target, self._listener.incoming)
class ReplyTask(controller.Task):
"""A task that sends 'response' message to 'address'.
"""
def __init__(self, address, response, log_failure):
super(ReplyTask, self).__init__()
self._address = address
self._response = response
self._log_failure = log_failure
self._wakeup = threading.Event()
def wait(self):
"""Wait for the controller to send the message.
"""
self._wakeup.wait()
def execute(self, controller):
"""Run on the eventloop thread - send the response message."""
controller.response(self._address, self._response)
self._wakeup.set()
<|fim▁end|> | controller.request(self._target, self._request,
self._results_queue, self._wait_for_reply) |
<|file_name|>drivertasks.py<|end_file_name|><|fim▁begin|># Copyright 2014, Red Hat, Inc.
#
# Licensed 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.
import logging
import threading
import time
from oslo_messaging._drivers.protocols.amqp import controller
from oslo_messaging._i18n import _LW
from oslo_messaging import exceptions
from six import moves
LOG = logging.getLogger(__name__)
class SendTask(controller.Task):
"""A task that sends a message to a target, and optionally waits for a
reply message. The caller may block until the remote confirms receipt or
the reply message has arrived.
"""
def __init__(self, target, request, wait_for_reply, deadline):
super(SendTask, self).__init__()
self._target = target
self._request = request
self._deadline = deadline
self._wait_for_reply = wait_for_reply
self._results_queue = moves.queue.Queue()
def wait(self, timeout):
"""Wait for the send to complete, and, optionally, a reply message from
the remote. Will raise MessagingTimeout if the send does not complete
or no reply is received within timeout seconds. If the request has
failed for any other reason, a MessagingException is raised.
"""
try:
result = self._results_queue.get(timeout=timeout)
except moves.queue.Empty:
if self._wait_for_reply:
reason = "Timed out waiting for a reply."
else:
reason = "Timed out waiting for send to complete."
raise exceptions.MessagingTimeout(reason)
if result["status"] == "OK":
return result.get("response", None)
raise result["error"]
def execute(self, controller):
"""Runs on eventloop thread - sends request."""
if not self._deadline or self._deadline > time.time():
controller.request(self._target, self._request,
self._results_queue, self._wait_for_reply)
else:
<|fim_middle|>
class ListenTask(controller.Task):
"""A task that creates a subscription to the given target. Messages
arriving from the target are given to the listener.
"""
def __init__(self, target, listener, notifications=False):
"""Create a subscription to the target."""
super(ListenTask, self).__init__()
self._target = target
self._listener = listener
self._notifications = notifications
def execute(self, controller):
"""Run on the eventloop thread - subscribes to target. Inbound messages
are queued to the listener's incoming queue.
"""
if self._notifications:
controller.subscribe_notifications(self._target,
self._listener.incoming)
else:
controller.subscribe(self._target, self._listener.incoming)
class ReplyTask(controller.Task):
"""A task that sends 'response' message to 'address'.
"""
def __init__(self, address, response, log_failure):
super(ReplyTask, self).__init__()
self._address = address
self._response = response
self._log_failure = log_failure
self._wakeup = threading.Event()
def wait(self):
"""Wait for the controller to send the message.
"""
self._wakeup.wait()
def execute(self, controller):
"""Run on the eventloop thread - send the response message."""
controller.response(self._address, self._response)
self._wakeup.set()
<|fim▁end|> | LOG.warning(_LW("Send request to %s aborted: TTL expired."),
self._target) |
<|file_name|>drivertasks.py<|end_file_name|><|fim▁begin|># Copyright 2014, Red Hat, Inc.
#
# Licensed 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.
import logging
import threading
import time
from oslo_messaging._drivers.protocols.amqp import controller
from oslo_messaging._i18n import _LW
from oslo_messaging import exceptions
from six import moves
LOG = logging.getLogger(__name__)
class SendTask(controller.Task):
"""A task that sends a message to a target, and optionally waits for a
reply message. The caller may block until the remote confirms receipt or
the reply message has arrived.
"""
def __init__(self, target, request, wait_for_reply, deadline):
super(SendTask, self).__init__()
self._target = target
self._request = request
self._deadline = deadline
self._wait_for_reply = wait_for_reply
self._results_queue = moves.queue.Queue()
def wait(self, timeout):
"""Wait for the send to complete, and, optionally, a reply message from
the remote. Will raise MessagingTimeout if the send does not complete
or no reply is received within timeout seconds. If the request has
failed for any other reason, a MessagingException is raised.
"""
try:
result = self._results_queue.get(timeout=timeout)
except moves.queue.Empty:
if self._wait_for_reply:
reason = "Timed out waiting for a reply."
else:
reason = "Timed out waiting for send to complete."
raise exceptions.MessagingTimeout(reason)
if result["status"] == "OK":
return result.get("response", None)
raise result["error"]
def execute(self, controller):
"""Runs on eventloop thread - sends request."""
if not self._deadline or self._deadline > time.time():
controller.request(self._target, self._request,
self._results_queue, self._wait_for_reply)
else:
LOG.warning(_LW("Send request to %s aborted: TTL expired."),
self._target)
class ListenTask(controller.Task):
"""A task that creates a subscription to the given target. Messages
arriving from the target are given to the listener.
"""
def __init__(self, target, listener, notifications=False):
"""Create a subscription to the target."""
super(ListenTask, self).__init__()
self._target = target
self._listener = listener
self._notifications = notifications
def execute(self, controller):
"""Run on the eventloop thread - subscribes to target. Inbound messages
are queued to the listener's incoming queue.
"""
if self._notifications:
<|fim_middle|>
else:
controller.subscribe(self._target, self._listener.incoming)
class ReplyTask(controller.Task):
"""A task that sends 'response' message to 'address'.
"""
def __init__(self, address, response, log_failure):
super(ReplyTask, self).__init__()
self._address = address
self._response = response
self._log_failure = log_failure
self._wakeup = threading.Event()
def wait(self):
"""Wait for the controller to send the message.
"""
self._wakeup.wait()
def execute(self, controller):
"""Run on the eventloop thread - send the response message."""
controller.response(self._address, self._response)
self._wakeup.set()
<|fim▁end|> | controller.subscribe_notifications(self._target,
self._listener.incoming) |
<|file_name|>drivertasks.py<|end_file_name|><|fim▁begin|># Copyright 2014, Red Hat, Inc.
#
# Licensed 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.
import logging
import threading
import time
from oslo_messaging._drivers.protocols.amqp import controller
from oslo_messaging._i18n import _LW
from oslo_messaging import exceptions
from six import moves
LOG = logging.getLogger(__name__)
class SendTask(controller.Task):
"""A task that sends a message to a target, and optionally waits for a
reply message. The caller may block until the remote confirms receipt or
the reply message has arrived.
"""
def __init__(self, target, request, wait_for_reply, deadline):
super(SendTask, self).__init__()
self._target = target
self._request = request
self._deadline = deadline
self._wait_for_reply = wait_for_reply
self._results_queue = moves.queue.Queue()
def wait(self, timeout):
"""Wait for the send to complete, and, optionally, a reply message from
the remote. Will raise MessagingTimeout if the send does not complete
or no reply is received within timeout seconds. If the request has
failed for any other reason, a MessagingException is raised.
"""
try:
result = self._results_queue.get(timeout=timeout)
except moves.queue.Empty:
if self._wait_for_reply:
reason = "Timed out waiting for a reply."
else:
reason = "Timed out waiting for send to complete."
raise exceptions.MessagingTimeout(reason)
if result["status"] == "OK":
return result.get("response", None)
raise result["error"]
def execute(self, controller):
"""Runs on eventloop thread - sends request."""
if not self._deadline or self._deadline > time.time():
controller.request(self._target, self._request,
self._results_queue, self._wait_for_reply)
else:
LOG.warning(_LW("Send request to %s aborted: TTL expired."),
self._target)
class ListenTask(controller.Task):
"""A task that creates a subscription to the given target. Messages
arriving from the target are given to the listener.
"""
def __init__(self, target, listener, notifications=False):
"""Create a subscription to the target."""
super(ListenTask, self).__init__()
self._target = target
self._listener = listener
self._notifications = notifications
def execute(self, controller):
"""Run on the eventloop thread - subscribes to target. Inbound messages
are queued to the listener's incoming queue.
"""
if self._notifications:
controller.subscribe_notifications(self._target,
self._listener.incoming)
else:
<|fim_middle|>
class ReplyTask(controller.Task):
"""A task that sends 'response' message to 'address'.
"""
def __init__(self, address, response, log_failure):
super(ReplyTask, self).__init__()
self._address = address
self._response = response
self._log_failure = log_failure
self._wakeup = threading.Event()
def wait(self):
"""Wait for the controller to send the message.
"""
self._wakeup.wait()
def execute(self, controller):
"""Run on the eventloop thread - send the response message."""
controller.response(self._address, self._response)
self._wakeup.set()
<|fim▁end|> | controller.subscribe(self._target, self._listener.incoming) |
<|file_name|>drivertasks.py<|end_file_name|><|fim▁begin|># Copyright 2014, Red Hat, Inc.
#
# Licensed 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.
import logging
import threading
import time
from oslo_messaging._drivers.protocols.amqp import controller
from oslo_messaging._i18n import _LW
from oslo_messaging import exceptions
from six import moves
LOG = logging.getLogger(__name__)
class SendTask(controller.Task):
"""A task that sends a message to a target, and optionally waits for a
reply message. The caller may block until the remote confirms receipt or
the reply message has arrived.
"""
def <|fim_middle|>(self, target, request, wait_for_reply, deadline):
super(SendTask, self).__init__()
self._target = target
self._request = request
self._deadline = deadline
self._wait_for_reply = wait_for_reply
self._results_queue = moves.queue.Queue()
def wait(self, timeout):
"""Wait for the send to complete, and, optionally, a reply message from
the remote. Will raise MessagingTimeout if the send does not complete
or no reply is received within timeout seconds. If the request has
failed for any other reason, a MessagingException is raised.
"""
try:
result = self._results_queue.get(timeout=timeout)
except moves.queue.Empty:
if self._wait_for_reply:
reason = "Timed out waiting for a reply."
else:
reason = "Timed out waiting for send to complete."
raise exceptions.MessagingTimeout(reason)
if result["status"] == "OK":
return result.get("response", None)
raise result["error"]
def execute(self, controller):
"""Runs on eventloop thread - sends request."""
if not self._deadline or self._deadline > time.time():
controller.request(self._target, self._request,
self._results_queue, self._wait_for_reply)
else:
LOG.warning(_LW("Send request to %s aborted: TTL expired."),
self._target)
class ListenTask(controller.Task):
"""A task that creates a subscription to the given target. Messages
arriving from the target are given to the listener.
"""
def __init__(self, target, listener, notifications=False):
"""Create a subscription to the target."""
super(ListenTask, self).__init__()
self._target = target
self._listener = listener
self._notifications = notifications
def execute(self, controller):
"""Run on the eventloop thread - subscribes to target. Inbound messages
are queued to the listener's incoming queue.
"""
if self._notifications:
controller.subscribe_notifications(self._target,
self._listener.incoming)
else:
controller.subscribe(self._target, self._listener.incoming)
class ReplyTask(controller.Task):
"""A task that sends 'response' message to 'address'.
"""
def __init__(self, address, response, log_failure):
super(ReplyTask, self).__init__()
self._address = address
self._response = response
self._log_failure = log_failure
self._wakeup = threading.Event()
def wait(self):
"""Wait for the controller to send the message.
"""
self._wakeup.wait()
def execute(self, controller):
"""Run on the eventloop thread - send the response message."""
controller.response(self._address, self._response)
self._wakeup.set()
<|fim▁end|> | __init__ |
<|file_name|>drivertasks.py<|end_file_name|><|fim▁begin|># Copyright 2014, Red Hat, Inc.
#
# Licensed 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.
import logging
import threading
import time
from oslo_messaging._drivers.protocols.amqp import controller
from oslo_messaging._i18n import _LW
from oslo_messaging import exceptions
from six import moves
LOG = logging.getLogger(__name__)
class SendTask(controller.Task):
"""A task that sends a message to a target, and optionally waits for a
reply message. The caller may block until the remote confirms receipt or
the reply message has arrived.
"""
def __init__(self, target, request, wait_for_reply, deadline):
super(SendTask, self).__init__()
self._target = target
self._request = request
self._deadline = deadline
self._wait_for_reply = wait_for_reply
self._results_queue = moves.queue.Queue()
def <|fim_middle|>(self, timeout):
"""Wait for the send to complete, and, optionally, a reply message from
the remote. Will raise MessagingTimeout if the send does not complete
or no reply is received within timeout seconds. If the request has
failed for any other reason, a MessagingException is raised.
"""
try:
result = self._results_queue.get(timeout=timeout)
except moves.queue.Empty:
if self._wait_for_reply:
reason = "Timed out waiting for a reply."
else:
reason = "Timed out waiting for send to complete."
raise exceptions.MessagingTimeout(reason)
if result["status"] == "OK":
return result.get("response", None)
raise result["error"]
def execute(self, controller):
"""Runs on eventloop thread - sends request."""
if not self._deadline or self._deadline > time.time():
controller.request(self._target, self._request,
self._results_queue, self._wait_for_reply)
else:
LOG.warning(_LW("Send request to %s aborted: TTL expired."),
self._target)
class ListenTask(controller.Task):
"""A task that creates a subscription to the given target. Messages
arriving from the target are given to the listener.
"""
def __init__(self, target, listener, notifications=False):
"""Create a subscription to the target."""
super(ListenTask, self).__init__()
self._target = target
self._listener = listener
self._notifications = notifications
def execute(self, controller):
"""Run on the eventloop thread - subscribes to target. Inbound messages
are queued to the listener's incoming queue.
"""
if self._notifications:
controller.subscribe_notifications(self._target,
self._listener.incoming)
else:
controller.subscribe(self._target, self._listener.incoming)
class ReplyTask(controller.Task):
"""A task that sends 'response' message to 'address'.
"""
def __init__(self, address, response, log_failure):
super(ReplyTask, self).__init__()
self._address = address
self._response = response
self._log_failure = log_failure
self._wakeup = threading.Event()
def wait(self):
"""Wait for the controller to send the message.
"""
self._wakeup.wait()
def execute(self, controller):
"""Run on the eventloop thread - send the response message."""
controller.response(self._address, self._response)
self._wakeup.set()
<|fim▁end|> | wait |
<|file_name|>drivertasks.py<|end_file_name|><|fim▁begin|># Copyright 2014, Red Hat, Inc.
#
# Licensed 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.
import logging
import threading
import time
from oslo_messaging._drivers.protocols.amqp import controller
from oslo_messaging._i18n import _LW
from oslo_messaging import exceptions
from six import moves
LOG = logging.getLogger(__name__)
class SendTask(controller.Task):
"""A task that sends a message to a target, and optionally waits for a
reply message. The caller may block until the remote confirms receipt or
the reply message has arrived.
"""
def __init__(self, target, request, wait_for_reply, deadline):
super(SendTask, self).__init__()
self._target = target
self._request = request
self._deadline = deadline
self._wait_for_reply = wait_for_reply
self._results_queue = moves.queue.Queue()
def wait(self, timeout):
"""Wait for the send to complete, and, optionally, a reply message from
the remote. Will raise MessagingTimeout if the send does not complete
or no reply is received within timeout seconds. If the request has
failed for any other reason, a MessagingException is raised.
"""
try:
result = self._results_queue.get(timeout=timeout)
except moves.queue.Empty:
if self._wait_for_reply:
reason = "Timed out waiting for a reply."
else:
reason = "Timed out waiting for send to complete."
raise exceptions.MessagingTimeout(reason)
if result["status"] == "OK":
return result.get("response", None)
raise result["error"]
def <|fim_middle|>(self, controller):
"""Runs on eventloop thread - sends request."""
if not self._deadline or self._deadline > time.time():
controller.request(self._target, self._request,
self._results_queue, self._wait_for_reply)
else:
LOG.warning(_LW("Send request to %s aborted: TTL expired."),
self._target)
class ListenTask(controller.Task):
"""A task that creates a subscription to the given target. Messages
arriving from the target are given to the listener.
"""
def __init__(self, target, listener, notifications=False):
"""Create a subscription to the target."""
super(ListenTask, self).__init__()
self._target = target
self._listener = listener
self._notifications = notifications
def execute(self, controller):
"""Run on the eventloop thread - subscribes to target. Inbound messages
are queued to the listener's incoming queue.
"""
if self._notifications:
controller.subscribe_notifications(self._target,
self._listener.incoming)
else:
controller.subscribe(self._target, self._listener.incoming)
class ReplyTask(controller.Task):
"""A task that sends 'response' message to 'address'.
"""
def __init__(self, address, response, log_failure):
super(ReplyTask, self).__init__()
self._address = address
self._response = response
self._log_failure = log_failure
self._wakeup = threading.Event()
def wait(self):
"""Wait for the controller to send the message.
"""
self._wakeup.wait()
def execute(self, controller):
"""Run on the eventloop thread - send the response message."""
controller.response(self._address, self._response)
self._wakeup.set()
<|fim▁end|> | execute |
<|file_name|>drivertasks.py<|end_file_name|><|fim▁begin|># Copyright 2014, Red Hat, Inc.
#
# Licensed 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.
import logging
import threading
import time
from oslo_messaging._drivers.protocols.amqp import controller
from oslo_messaging._i18n import _LW
from oslo_messaging import exceptions
from six import moves
LOG = logging.getLogger(__name__)
class SendTask(controller.Task):
"""A task that sends a message to a target, and optionally waits for a
reply message. The caller may block until the remote confirms receipt or
the reply message has arrived.
"""
def __init__(self, target, request, wait_for_reply, deadline):
super(SendTask, self).__init__()
self._target = target
self._request = request
self._deadline = deadline
self._wait_for_reply = wait_for_reply
self._results_queue = moves.queue.Queue()
def wait(self, timeout):
"""Wait for the send to complete, and, optionally, a reply message from
the remote. Will raise MessagingTimeout if the send does not complete
or no reply is received within timeout seconds. If the request has
failed for any other reason, a MessagingException is raised.
"""
try:
result = self._results_queue.get(timeout=timeout)
except moves.queue.Empty:
if self._wait_for_reply:
reason = "Timed out waiting for a reply."
else:
reason = "Timed out waiting for send to complete."
raise exceptions.MessagingTimeout(reason)
if result["status"] == "OK":
return result.get("response", None)
raise result["error"]
def execute(self, controller):
"""Runs on eventloop thread - sends request."""
if not self._deadline or self._deadline > time.time():
controller.request(self._target, self._request,
self._results_queue, self._wait_for_reply)
else:
LOG.warning(_LW("Send request to %s aborted: TTL expired."),
self._target)
class ListenTask(controller.Task):
"""A task that creates a subscription to the given target. Messages
arriving from the target are given to the listener.
"""
def <|fim_middle|>(self, target, listener, notifications=False):
"""Create a subscription to the target."""
super(ListenTask, self).__init__()
self._target = target
self._listener = listener
self._notifications = notifications
def execute(self, controller):
"""Run on the eventloop thread - subscribes to target. Inbound messages
are queued to the listener's incoming queue.
"""
if self._notifications:
controller.subscribe_notifications(self._target,
self._listener.incoming)
else:
controller.subscribe(self._target, self._listener.incoming)
class ReplyTask(controller.Task):
"""A task that sends 'response' message to 'address'.
"""
def __init__(self, address, response, log_failure):
super(ReplyTask, self).__init__()
self._address = address
self._response = response
self._log_failure = log_failure
self._wakeup = threading.Event()
def wait(self):
"""Wait for the controller to send the message.
"""
self._wakeup.wait()
def execute(self, controller):
"""Run on the eventloop thread - send the response message."""
controller.response(self._address, self._response)
self._wakeup.set()
<|fim▁end|> | __init__ |
<|file_name|>drivertasks.py<|end_file_name|><|fim▁begin|># Copyright 2014, Red Hat, Inc.
#
# Licensed 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.
import logging
import threading
import time
from oslo_messaging._drivers.protocols.amqp import controller
from oslo_messaging._i18n import _LW
from oslo_messaging import exceptions
from six import moves
LOG = logging.getLogger(__name__)
class SendTask(controller.Task):
"""A task that sends a message to a target, and optionally waits for a
reply message. The caller may block until the remote confirms receipt or
the reply message has arrived.
"""
def __init__(self, target, request, wait_for_reply, deadline):
super(SendTask, self).__init__()
self._target = target
self._request = request
self._deadline = deadline
self._wait_for_reply = wait_for_reply
self._results_queue = moves.queue.Queue()
def wait(self, timeout):
"""Wait for the send to complete, and, optionally, a reply message from
the remote. Will raise MessagingTimeout if the send does not complete
or no reply is received within timeout seconds. If the request has
failed for any other reason, a MessagingException is raised.
"""
try:
result = self._results_queue.get(timeout=timeout)
except moves.queue.Empty:
if self._wait_for_reply:
reason = "Timed out waiting for a reply."
else:
reason = "Timed out waiting for send to complete."
raise exceptions.MessagingTimeout(reason)
if result["status"] == "OK":
return result.get("response", None)
raise result["error"]
def execute(self, controller):
"""Runs on eventloop thread - sends request."""
if not self._deadline or self._deadline > time.time():
controller.request(self._target, self._request,
self._results_queue, self._wait_for_reply)
else:
LOG.warning(_LW("Send request to %s aborted: TTL expired."),
self._target)
class ListenTask(controller.Task):
"""A task that creates a subscription to the given target. Messages
arriving from the target are given to the listener.
"""
def __init__(self, target, listener, notifications=False):
"""Create a subscription to the target."""
super(ListenTask, self).__init__()
self._target = target
self._listener = listener
self._notifications = notifications
def <|fim_middle|>(self, controller):
"""Run on the eventloop thread - subscribes to target. Inbound messages
are queued to the listener's incoming queue.
"""
if self._notifications:
controller.subscribe_notifications(self._target,
self._listener.incoming)
else:
controller.subscribe(self._target, self._listener.incoming)
class ReplyTask(controller.Task):
"""A task that sends 'response' message to 'address'.
"""
def __init__(self, address, response, log_failure):
super(ReplyTask, self).__init__()
self._address = address
self._response = response
self._log_failure = log_failure
self._wakeup = threading.Event()
def wait(self):
"""Wait for the controller to send the message.
"""
self._wakeup.wait()
def execute(self, controller):
"""Run on the eventloop thread - send the response message."""
controller.response(self._address, self._response)
self._wakeup.set()
<|fim▁end|> | execute |
<|file_name|>drivertasks.py<|end_file_name|><|fim▁begin|># Copyright 2014, Red Hat, Inc.
#
# Licensed 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.
import logging
import threading
import time
from oslo_messaging._drivers.protocols.amqp import controller
from oslo_messaging._i18n import _LW
from oslo_messaging import exceptions
from six import moves
LOG = logging.getLogger(__name__)
class SendTask(controller.Task):
"""A task that sends a message to a target, and optionally waits for a
reply message. The caller may block until the remote confirms receipt or
the reply message has arrived.
"""
def __init__(self, target, request, wait_for_reply, deadline):
super(SendTask, self).__init__()
self._target = target
self._request = request
self._deadline = deadline
self._wait_for_reply = wait_for_reply
self._results_queue = moves.queue.Queue()
def wait(self, timeout):
"""Wait for the send to complete, and, optionally, a reply message from
the remote. Will raise MessagingTimeout if the send does not complete
or no reply is received within timeout seconds. If the request has
failed for any other reason, a MessagingException is raised.
"""
try:
result = self._results_queue.get(timeout=timeout)
except moves.queue.Empty:
if self._wait_for_reply:
reason = "Timed out waiting for a reply."
else:
reason = "Timed out waiting for send to complete."
raise exceptions.MessagingTimeout(reason)
if result["status"] == "OK":
return result.get("response", None)
raise result["error"]
def execute(self, controller):
"""Runs on eventloop thread - sends request."""
if not self._deadline or self._deadline > time.time():
controller.request(self._target, self._request,
self._results_queue, self._wait_for_reply)
else:
LOG.warning(_LW("Send request to %s aborted: TTL expired."),
self._target)
class ListenTask(controller.Task):
"""A task that creates a subscription to the given target. Messages
arriving from the target are given to the listener.
"""
def __init__(self, target, listener, notifications=False):
"""Create a subscription to the target."""
super(ListenTask, self).__init__()
self._target = target
self._listener = listener
self._notifications = notifications
def execute(self, controller):
"""Run on the eventloop thread - subscribes to target. Inbound messages
are queued to the listener's incoming queue.
"""
if self._notifications:
controller.subscribe_notifications(self._target,
self._listener.incoming)
else:
controller.subscribe(self._target, self._listener.incoming)
class ReplyTask(controller.Task):
"""A task that sends 'response' message to 'address'.
"""
def <|fim_middle|>(self, address, response, log_failure):
super(ReplyTask, self).__init__()
self._address = address
self._response = response
self._log_failure = log_failure
self._wakeup = threading.Event()
def wait(self):
"""Wait for the controller to send the message.
"""
self._wakeup.wait()
def execute(self, controller):
"""Run on the eventloop thread - send the response message."""
controller.response(self._address, self._response)
self._wakeup.set()
<|fim▁end|> | __init__ |
<|file_name|>drivertasks.py<|end_file_name|><|fim▁begin|># Copyright 2014, Red Hat, Inc.
#
# Licensed 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.
import logging
import threading
import time
from oslo_messaging._drivers.protocols.amqp import controller
from oslo_messaging._i18n import _LW
from oslo_messaging import exceptions
from six import moves
LOG = logging.getLogger(__name__)
class SendTask(controller.Task):
"""A task that sends a message to a target, and optionally waits for a
reply message. The caller may block until the remote confirms receipt or
the reply message has arrived.
"""
def __init__(self, target, request, wait_for_reply, deadline):
super(SendTask, self).__init__()
self._target = target
self._request = request
self._deadline = deadline
self._wait_for_reply = wait_for_reply
self._results_queue = moves.queue.Queue()
def wait(self, timeout):
"""Wait for the send to complete, and, optionally, a reply message from
the remote. Will raise MessagingTimeout if the send does not complete
or no reply is received within timeout seconds. If the request has
failed for any other reason, a MessagingException is raised.
"""
try:
result = self._results_queue.get(timeout=timeout)
except moves.queue.Empty:
if self._wait_for_reply:
reason = "Timed out waiting for a reply."
else:
reason = "Timed out waiting for send to complete."
raise exceptions.MessagingTimeout(reason)
if result["status"] == "OK":
return result.get("response", None)
raise result["error"]
def execute(self, controller):
"""Runs on eventloop thread - sends request."""
if not self._deadline or self._deadline > time.time():
controller.request(self._target, self._request,
self._results_queue, self._wait_for_reply)
else:
LOG.warning(_LW("Send request to %s aborted: TTL expired."),
self._target)
class ListenTask(controller.Task):
"""A task that creates a subscription to the given target. Messages
arriving from the target are given to the listener.
"""
def __init__(self, target, listener, notifications=False):
"""Create a subscription to the target."""
super(ListenTask, self).__init__()
self._target = target
self._listener = listener
self._notifications = notifications
def execute(self, controller):
"""Run on the eventloop thread - subscribes to target. Inbound messages
are queued to the listener's incoming queue.
"""
if self._notifications:
controller.subscribe_notifications(self._target,
self._listener.incoming)
else:
controller.subscribe(self._target, self._listener.incoming)
class ReplyTask(controller.Task):
"""A task that sends 'response' message to 'address'.
"""
def __init__(self, address, response, log_failure):
super(ReplyTask, self).__init__()
self._address = address
self._response = response
self._log_failure = log_failure
self._wakeup = threading.Event()
def <|fim_middle|>(self):
"""Wait for the controller to send the message.
"""
self._wakeup.wait()
def execute(self, controller):
"""Run on the eventloop thread - send the response message."""
controller.response(self._address, self._response)
self._wakeup.set()
<|fim▁end|> | wait |
<|file_name|>drivertasks.py<|end_file_name|><|fim▁begin|># Copyright 2014, Red Hat, Inc.
#
# Licensed 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.
import logging
import threading
import time
from oslo_messaging._drivers.protocols.amqp import controller
from oslo_messaging._i18n import _LW
from oslo_messaging import exceptions
from six import moves
LOG = logging.getLogger(__name__)
class SendTask(controller.Task):
"""A task that sends a message to a target, and optionally waits for a
reply message. The caller may block until the remote confirms receipt or
the reply message has arrived.
"""
def __init__(self, target, request, wait_for_reply, deadline):
super(SendTask, self).__init__()
self._target = target
self._request = request
self._deadline = deadline
self._wait_for_reply = wait_for_reply
self._results_queue = moves.queue.Queue()
def wait(self, timeout):
"""Wait for the send to complete, and, optionally, a reply message from
the remote. Will raise MessagingTimeout if the send does not complete
or no reply is received within timeout seconds. If the request has
failed for any other reason, a MessagingException is raised.
"""
try:
result = self._results_queue.get(timeout=timeout)
except moves.queue.Empty:
if self._wait_for_reply:
reason = "Timed out waiting for a reply."
else:
reason = "Timed out waiting for send to complete."
raise exceptions.MessagingTimeout(reason)
if result["status"] == "OK":
return result.get("response", None)
raise result["error"]
def execute(self, controller):
"""Runs on eventloop thread - sends request."""
if not self._deadline or self._deadline > time.time():
controller.request(self._target, self._request,
self._results_queue, self._wait_for_reply)
else:
LOG.warning(_LW("Send request to %s aborted: TTL expired."),
self._target)
class ListenTask(controller.Task):
"""A task that creates a subscription to the given target. Messages
arriving from the target are given to the listener.
"""
def __init__(self, target, listener, notifications=False):
"""Create a subscription to the target."""
super(ListenTask, self).__init__()
self._target = target
self._listener = listener
self._notifications = notifications
def execute(self, controller):
"""Run on the eventloop thread - subscribes to target. Inbound messages
are queued to the listener's incoming queue.
"""
if self._notifications:
controller.subscribe_notifications(self._target,
self._listener.incoming)
else:
controller.subscribe(self._target, self._listener.incoming)
class ReplyTask(controller.Task):
"""A task that sends 'response' message to 'address'.
"""
def __init__(self, address, response, log_failure):
super(ReplyTask, self).__init__()
self._address = address
self._response = response
self._log_failure = log_failure
self._wakeup = threading.Event()
def wait(self):
"""Wait for the controller to send the message.
"""
self._wakeup.wait()
def <|fim_middle|>(self, controller):
"""Run on the eventloop thread - send the response message."""
controller.response(self._address, self._response)
self._wakeup.set()
<|fim▁end|> | execute |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|>#__all__ = [ 'search', 'ham_distance', 'lev_distance', 'distance', 'distance_matrix' ]<|fim▁end|> | |
<|file_name|>wechatService.py<|end_file_name|><|fim▁begin|># -*- coding:utf-8 -*-
"""
# Author: Pegasus Wang ([email protected], http://ningning.today)
# Created Time : Fri Feb 20 21:38:57 2015
# File Name: wechatService.py
# Description:
# :copyright: (c) 2015 by Pegasus Wang.
# :license: MIT, see LICENSE for more details.
"""
import json
import time
import urllib
import urllib2
from wechatUtil import MessageUtil
from wechatReply import TextReply
class RobotService(object):
"""Auto reply robot service"""
KEY = 'd92d20bc1d8bb3cff585bf746603b2a9'
url = 'http://www.tuling123.com/openapi/api'
@staticmethod
def auto_reply(req_info):
query = {'key': RobotService.KEY, 'info': req_info.encode('utf-8')}
headers = {'Content-type': 'text/html', 'charset': 'utf-8'}
data = urllib.urlencode(query)
req = urllib2.Request(RobotService.url, data)
f = urllib2.urlopen(req).read()
return json.loads(f).get('text').replace('<br>', '\n')
#return json.loads(f).get('text')
class WechatService(object):
"""process request"""<|fim▁hole|> :param request: post request message
:return: None
"""
requestMap = MessageUtil.parseXml(request)
fromUserName = requestMap.get(u'FromUserName')
toUserName = requestMap.get(u'ToUserName')
createTime = requestMap.get(u'CreateTime')
msgType = requestMap.get(u'MsgType')
msgId = requestMap.get(u'MsgId')
textReply = TextReply()
textReply.setToUserName(fromUserName)
textReply.setFromUserName(toUserName)
textReply.setCreateTime(time.time())
textReply.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT)
if msgType == MessageUtil.REQ_MESSAGE_TYPE_TEXT:
content = requestMap.get('Content').decode('utf-8') # note: decode first
#respContent = u'您发送的是文本消息:' + content
respContent = RobotService.auto_reply(content)
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_IMAGE:
respContent = u'您发送的是图片消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VOICE:
respContent = u'您发送的是语音消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VIDEO:
respContent = u'您发送的是视频消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LOCATION:
respContent = u'您发送的是地理位置消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LINK:
respContent = u'您发送的是链接消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_EVENT:
eventType = requestMap.get(u'Event')
if eventType == MessageUtil.EVENT_TYPE_SUBSCRIBE:
respContent = u'^_^谢谢您的关注,本公众号由王宁宁开发(python2.7+django1.4),如果你有兴趣继续开发,' \
u'可以联系我,就当打发时间了.'
elif eventType == MessageUtil.EVENT_TYPE_UNSUBSCRIBE:
pass
elif eventType == MessageUtil.EVENT_TYPE_SCAN:
# TODO
pass
elif eventType == MessageUtil.EVENT_TYPE_LOCATION:
# TODO
pass
elif eventType == MessageUtil.EVENT_TYPE_CLICK:
# TODO
pass
textReply.setContent(respContent)
respXml = MessageUtil.class2xml(textReply)
return respXml
"""
if msgType == 'text':
content = requestMap.get('Content')
# TODO
elif msgType == 'image':
picUrl = requestMap.get('PicUrl')
# TODO
elif msgType == 'voice':
mediaId = requestMap.get('MediaId')
format = requestMap.get('Format')
# TODO
elif msgType == 'video':
mediaId = requestMap.get('MediaId')
thumbMediaId = requestMap.get('ThumbMediaId')
# TODO
elif msgType == 'location':
lat = requestMap.get('Location_X')
lng = requestMap.get('Location_Y')
label = requestMap.get('Label')
scale = requestMap.get('Scale')
# TODO
elif msgType == 'link':
title = requestMap.get('Title')
description = requestMap.get('Description')
url = requestMap.get('Url')
"""<|fim▁end|> | @staticmethod
def processRequest(request):
"""process different message types.
|
<|file_name|>wechatService.py<|end_file_name|><|fim▁begin|># -*- coding:utf-8 -*-
"""
# Author: Pegasus Wang ([email protected], http://ningning.today)
# Created Time : Fri Feb 20 21:38:57 2015
# File Name: wechatService.py
# Description:
# :copyright: (c) 2015 by Pegasus Wang.
# :license: MIT, see LICENSE for more details.
"""
import json
import time
import urllib
import urllib2
from wechatUtil import MessageUtil
from wechatReply import TextReply
class RobotService(object):
<|fim_middle|>
class WechatService(object):
"""process request"""
@staticmethod
def processRequest(request):
"""process different message types.
:param request: post request message
:return: None
"""
requestMap = MessageUtil.parseXml(request)
fromUserName = requestMap.get(u'FromUserName')
toUserName = requestMap.get(u'ToUserName')
createTime = requestMap.get(u'CreateTime')
msgType = requestMap.get(u'MsgType')
msgId = requestMap.get(u'MsgId')
textReply = TextReply()
textReply.setToUserName(fromUserName)
textReply.setFromUserName(toUserName)
textReply.setCreateTime(time.time())
textReply.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT)
if msgType == MessageUtil.REQ_MESSAGE_TYPE_TEXT:
content = requestMap.get('Content').decode('utf-8') # note: decode first
#respContent = u'您发送的是文本消息:' + content
respContent = RobotService.auto_reply(content)
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_IMAGE:
respContent = u'您发送的是图片消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VOICE:
respContent = u'您发送的是语音消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VIDEO:
respContent = u'您发送的是视频消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LOCATION:
respContent = u'您发送的是地理位置消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LINK:
respContent = u'您发送的是链接消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_EVENT:
eventType = requestMap.get(u'Event')
if eventType == MessageUtil.EVENT_TYPE_SUBSCRIBE:
respContent = u'^_^谢谢您的关注,本公众号由王宁宁开发(python2.7+django1.4),如果你有兴趣继续开发,' \
u'可以联系我,就当打发时间了.'
elif eventType == MessageUtil.EVENT_TYPE_UNSUBSCRIBE:
pass
elif eventType == MessageUtil.EVENT_TYPE_SCAN:
# TODO
pass
elif eventType == MessageUtil.EVENT_TYPE_LOCATION:
# TODO
pass
elif eventType == MessageUtil.EVENT_TYPE_CLICK:
# TODO
pass
textReply.setContent(respContent)
respXml = MessageUtil.class2xml(textReply)
return respXml
"""
if msgType == 'text':
content = requestMap.get('Content')
# TODO
elif msgType == 'image':
picUrl = requestMap.get('PicUrl')
# TODO
elif msgType == 'voice':
mediaId = requestMap.get('MediaId')
format = requestMap.get('Format')
# TODO
elif msgType == 'video':
mediaId = requestMap.get('MediaId')
thumbMediaId = requestMap.get('ThumbMediaId')
# TODO
elif msgType == 'location':
lat = requestMap.get('Location_X')
lng = requestMap.get('Location_Y')
label = requestMap.get('Label')
scale = requestMap.get('Scale')
# TODO
elif msgType == 'link':
title = requestMap.get('Title')
description = requestMap.get('Description')
url = requestMap.get('Url')
"""
<|fim▁end|> | """Auto reply robot service"""
KEY = 'd92d20bc1d8bb3cff585bf746603b2a9'
url = 'http://www.tuling123.com/openapi/api'
@staticmethod
def auto_reply(req_info):
query = {'key': RobotService.KEY, 'info': req_info.encode('utf-8')}
headers = {'Content-type': 'text/html', 'charset': 'utf-8'}
data = urllib.urlencode(query)
req = urllib2.Request(RobotService.url, data)
f = urllib2.urlopen(req).read()
return json.loads(f).get('text').replace('<br>', '\n')
#return json.loads(f).get('text') |
<|file_name|>wechatService.py<|end_file_name|><|fim▁begin|># -*- coding:utf-8 -*-
"""
# Author: Pegasus Wang ([email protected], http://ningning.today)
# Created Time : Fri Feb 20 21:38:57 2015
# File Name: wechatService.py
# Description:
# :copyright: (c) 2015 by Pegasus Wang.
# :license: MIT, see LICENSE for more details.
"""
import json
import time
import urllib
import urllib2
from wechatUtil import MessageUtil
from wechatReply import TextReply
class RobotService(object):
"""Auto reply robot service"""
KEY = 'd92d20bc1d8bb3cff585bf746603b2a9'
url = 'http://www.tuling123.com/openapi/api'
@staticmethod
def auto_reply(req_info):
<|fim_middle|>
class WechatService(object):
"""process request"""
@staticmethod
def processRequest(request):
"""process different message types.
:param request: post request message
:return: None
"""
requestMap = MessageUtil.parseXml(request)
fromUserName = requestMap.get(u'FromUserName')
toUserName = requestMap.get(u'ToUserName')
createTime = requestMap.get(u'CreateTime')
msgType = requestMap.get(u'MsgType')
msgId = requestMap.get(u'MsgId')
textReply = TextReply()
textReply.setToUserName(fromUserName)
textReply.setFromUserName(toUserName)
textReply.setCreateTime(time.time())
textReply.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT)
if msgType == MessageUtil.REQ_MESSAGE_TYPE_TEXT:
content = requestMap.get('Content').decode('utf-8') # note: decode first
#respContent = u'您发送的是文本消息:' + content
respContent = RobotService.auto_reply(content)
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_IMAGE:
respContent = u'您发送的是图片消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VOICE:
respContent = u'您发送的是语音消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VIDEO:
respContent = u'您发送的是视频消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LOCATION:
respContent = u'您发送的是地理位置消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LINK:
respContent = u'您发送的是链接消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_EVENT:
eventType = requestMap.get(u'Event')
if eventType == MessageUtil.EVENT_TYPE_SUBSCRIBE:
respContent = u'^_^谢谢您的关注,本公众号由王宁宁开发(python2.7+django1.4),如果你有兴趣继续开发,' \
u'可以联系我,就当打发时间了.'
elif eventType == MessageUtil.EVENT_TYPE_UNSUBSCRIBE:
pass
elif eventType == MessageUtil.EVENT_TYPE_SCAN:
# TODO
pass
elif eventType == MessageUtil.EVENT_TYPE_LOCATION:
# TODO
pass
elif eventType == MessageUtil.EVENT_TYPE_CLICK:
# TODO
pass
textReply.setContent(respContent)
respXml = MessageUtil.class2xml(textReply)
return respXml
"""
if msgType == 'text':
content = requestMap.get('Content')
# TODO
elif msgType == 'image':
picUrl = requestMap.get('PicUrl')
# TODO
elif msgType == 'voice':
mediaId = requestMap.get('MediaId')
format = requestMap.get('Format')
# TODO
elif msgType == 'video':
mediaId = requestMap.get('MediaId')
thumbMediaId = requestMap.get('ThumbMediaId')
# TODO
elif msgType == 'location':
lat = requestMap.get('Location_X')
lng = requestMap.get('Location_Y')
label = requestMap.get('Label')
scale = requestMap.get('Scale')
# TODO
elif msgType == 'link':
title = requestMap.get('Title')
description = requestMap.get('Description')
url = requestMap.get('Url')
"""
<|fim▁end|> | query = {'key': RobotService.KEY, 'info': req_info.encode('utf-8')}
headers = {'Content-type': 'text/html', 'charset': 'utf-8'}
data = urllib.urlencode(query)
req = urllib2.Request(RobotService.url, data)
f = urllib2.urlopen(req).read()
return json.loads(f).get('text').replace('<br>', '\n')
#return json.loads(f).get('text') |
<|file_name|>wechatService.py<|end_file_name|><|fim▁begin|># -*- coding:utf-8 -*-
"""
# Author: Pegasus Wang ([email protected], http://ningning.today)
# Created Time : Fri Feb 20 21:38:57 2015
# File Name: wechatService.py
# Description:
# :copyright: (c) 2015 by Pegasus Wang.
# :license: MIT, see LICENSE for more details.
"""
import json
import time
import urllib
import urllib2
from wechatUtil import MessageUtil
from wechatReply import TextReply
class RobotService(object):
"""Auto reply robot service"""
KEY = 'd92d20bc1d8bb3cff585bf746603b2a9'
url = 'http://www.tuling123.com/openapi/api'
@staticmethod
def auto_reply(req_info):
query = {'key': RobotService.KEY, 'info': req_info.encode('utf-8')}
headers = {'Content-type': 'text/html', 'charset': 'utf-8'}
data = urllib.urlencode(query)
req = urllib2.Request(RobotService.url, data)
f = urllib2.urlopen(req).read()
return json.loads(f).get('text').replace('<br>', '\n')
#return json.loads(f).get('text')
class WechatService(object):
<|fim_middle|>
<|fim▁end|> | """process request"""
@staticmethod
def processRequest(request):
"""process different message types.
:param request: post request message
:return: None
"""
requestMap = MessageUtil.parseXml(request)
fromUserName = requestMap.get(u'FromUserName')
toUserName = requestMap.get(u'ToUserName')
createTime = requestMap.get(u'CreateTime')
msgType = requestMap.get(u'MsgType')
msgId = requestMap.get(u'MsgId')
textReply = TextReply()
textReply.setToUserName(fromUserName)
textReply.setFromUserName(toUserName)
textReply.setCreateTime(time.time())
textReply.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT)
if msgType == MessageUtil.REQ_MESSAGE_TYPE_TEXT:
content = requestMap.get('Content').decode('utf-8') # note: decode first
#respContent = u'您发送的是文本消息:' + content
respContent = RobotService.auto_reply(content)
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_IMAGE:
respContent = u'您发送的是图片消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VOICE:
respContent = u'您发送的是语音消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VIDEO:
respContent = u'您发送的是视频消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LOCATION:
respContent = u'您发送的是地理位置消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LINK:
respContent = u'您发送的是链接消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_EVENT:
eventType = requestMap.get(u'Event')
if eventType == MessageUtil.EVENT_TYPE_SUBSCRIBE:
respContent = u'^_^谢谢您的关注,本公众号由王宁宁开发(python2.7+django1.4),如果你有兴趣继续开发,' \
u'可以联系我,就当打发时间了.'
elif eventType == MessageUtil.EVENT_TYPE_UNSUBSCRIBE:
pass
elif eventType == MessageUtil.EVENT_TYPE_SCAN:
# TODO
pass
elif eventType == MessageUtil.EVENT_TYPE_LOCATION:
# TODO
pass
elif eventType == MessageUtil.EVENT_TYPE_CLICK:
# TODO
pass
textReply.setContent(respContent)
respXml = MessageUtil.class2xml(textReply)
return respXml
"""
if msgType == 'text':
content = requestMap.get('Content')
# TODO
elif msgType == 'image':
picUrl = requestMap.get('PicUrl')
# TODO
elif msgType == 'voice':
mediaId = requestMap.get('MediaId')
format = requestMap.get('Format')
# TODO
elif msgType == 'video':
mediaId = requestMap.get('MediaId')
thumbMediaId = requestMap.get('ThumbMediaId')
# TODO
elif msgType == 'location':
lat = requestMap.get('Location_X')
lng = requestMap.get('Location_Y')
label = requestMap.get('Label')
scale = requestMap.get('Scale')
# TODO
elif msgType == 'link':
title = requestMap.get('Title')
description = requestMap.get('Description')
url = requestMap.get('Url')
"""
|
<|file_name|>wechatService.py<|end_file_name|><|fim▁begin|># -*- coding:utf-8 -*-
"""
# Author: Pegasus Wang ([email protected], http://ningning.today)
# Created Time : Fri Feb 20 21:38:57 2015
# File Name: wechatService.py
# Description:
# :copyright: (c) 2015 by Pegasus Wang.
# :license: MIT, see LICENSE for more details.
"""
import json
import time
import urllib
import urllib2
from wechatUtil import MessageUtil
from wechatReply import TextReply
class RobotService(object):
"""Auto reply robot service"""
KEY = 'd92d20bc1d8bb3cff585bf746603b2a9'
url = 'http://www.tuling123.com/openapi/api'
@staticmethod
def auto_reply(req_info):
query = {'key': RobotService.KEY, 'info': req_info.encode('utf-8')}
headers = {'Content-type': 'text/html', 'charset': 'utf-8'}
data = urllib.urlencode(query)
req = urllib2.Request(RobotService.url, data)
f = urllib2.urlopen(req).read()
return json.loads(f).get('text').replace('<br>', '\n')
#return json.loads(f).get('text')
class WechatService(object):
"""process request"""
@staticmethod
def processRequest(request):
<|fim_middle|>
<|fim▁end|> | """process different message types.
:param request: post request message
:return: None
"""
requestMap = MessageUtil.parseXml(request)
fromUserName = requestMap.get(u'FromUserName')
toUserName = requestMap.get(u'ToUserName')
createTime = requestMap.get(u'CreateTime')
msgType = requestMap.get(u'MsgType')
msgId = requestMap.get(u'MsgId')
textReply = TextReply()
textReply.setToUserName(fromUserName)
textReply.setFromUserName(toUserName)
textReply.setCreateTime(time.time())
textReply.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT)
if msgType == MessageUtil.REQ_MESSAGE_TYPE_TEXT:
content = requestMap.get('Content').decode('utf-8') # note: decode first
#respContent = u'您发送的是文本消息:' + content
respContent = RobotService.auto_reply(content)
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_IMAGE:
respContent = u'您发送的是图片消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VOICE:
respContent = u'您发送的是语音消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VIDEO:
respContent = u'您发送的是视频消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LOCATION:
respContent = u'您发送的是地理位置消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LINK:
respContent = u'您发送的是链接消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_EVENT:
eventType = requestMap.get(u'Event')
if eventType == MessageUtil.EVENT_TYPE_SUBSCRIBE:
respContent = u'^_^谢谢您的关注,本公众号由王宁宁开发(python2.7+django1.4),如果你有兴趣继续开发,' \
u'可以联系我,就当打发时间了.'
elif eventType == MessageUtil.EVENT_TYPE_UNSUBSCRIBE:
pass
elif eventType == MessageUtil.EVENT_TYPE_SCAN:
# TODO
pass
elif eventType == MessageUtil.EVENT_TYPE_LOCATION:
# TODO
pass
elif eventType == MessageUtil.EVENT_TYPE_CLICK:
# TODO
pass
textReply.setContent(respContent)
respXml = MessageUtil.class2xml(textReply)
return respXml
"""
if msgType == 'text':
content = requestMap.get('Content')
# TODO
elif msgType == 'image':
picUrl = requestMap.get('PicUrl')
# TODO
elif msgType == 'voice':
mediaId = requestMap.get('MediaId')
format = requestMap.get('Format')
# TODO
elif msgType == 'video':
mediaId = requestMap.get('MediaId')
thumbMediaId = requestMap.get('ThumbMediaId')
# TODO
elif msgType == 'location':
lat = requestMap.get('Location_X')
lng = requestMap.get('Location_Y')
label = requestMap.get('Label')
scale = requestMap.get('Scale')
# TODO
elif msgType == 'link':
title = requestMap.get('Title')
description = requestMap.get('Description')
url = requestMap.get('Url')
"""
|
<|file_name|>wechatService.py<|end_file_name|><|fim▁begin|># -*- coding:utf-8 -*-
"""
# Author: Pegasus Wang ([email protected], http://ningning.today)
# Created Time : Fri Feb 20 21:38:57 2015
# File Name: wechatService.py
# Description:
# :copyright: (c) 2015 by Pegasus Wang.
# :license: MIT, see LICENSE for more details.
"""
import json
import time
import urllib
import urllib2
from wechatUtil import MessageUtil
from wechatReply import TextReply
class RobotService(object):
"""Auto reply robot service"""
KEY = 'd92d20bc1d8bb3cff585bf746603b2a9'
url = 'http://www.tuling123.com/openapi/api'
@staticmethod
def auto_reply(req_info):
query = {'key': RobotService.KEY, 'info': req_info.encode('utf-8')}
headers = {'Content-type': 'text/html', 'charset': 'utf-8'}
data = urllib.urlencode(query)
req = urllib2.Request(RobotService.url, data)
f = urllib2.urlopen(req).read()
return json.loads(f).get('text').replace('<br>', '\n')
#return json.loads(f).get('text')
class WechatService(object):
"""process request"""
@staticmethod
def processRequest(request):
"""process different message types.
:param request: post request message
:return: None
"""
requestMap = MessageUtil.parseXml(request)
fromUserName = requestMap.get(u'FromUserName')
toUserName = requestMap.get(u'ToUserName')
createTime = requestMap.get(u'CreateTime')
msgType = requestMap.get(u'MsgType')
msgId = requestMap.get(u'MsgId')
textReply = TextReply()
textReply.setToUserName(fromUserName)
textReply.setFromUserName(toUserName)
textReply.setCreateTime(time.time())
textReply.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT)
if msgType == MessageUtil.REQ_MESSAGE_TYPE_TEXT:
<|fim_middle|>
ype == MessageUtil.REQ_MESSAGE_TYPE_IMAGE:
respContent = u'您发送的是图片消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VOICE:
respContent = u'您发送的是语音消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VIDEO:
respContent = u'您发送的是视频消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LOCATION:
respContent = u'您发送的是地理位置消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LINK:
respContent = u'您发送的是链接消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_EVENT:
eventType = requestMap.get(u'Event')
if eventType == MessageUtil.EVENT_TYPE_SUBSCRIBE:
respContent = u'^_^谢谢您的关注,本公众号由王宁宁开发(python2.7+django1.4),如果你有兴趣继续开发,' \
u'可以联系我,就当打发时间了.'
elif eventType == MessageUtil.EVENT_TYPE_UNSUBSCRIBE:
pass
elif eventType == MessageUtil.EVENT_TYPE_SCAN:
# TODO
pass
elif eventType == MessageUtil.EVENT_TYPE_LOCATION:
# TODO
pass
elif eventType == MessageUtil.EVENT_TYPE_CLICK:
# TODO
pass
textReply.setContent(respContent)
respXml = MessageUtil.class2xml(textReply)
return respXml
"""
if msgType == 'text':
content = requestMap.get('Content')
# TODO
elif msgType == 'image':
picUrl = requestMap.get('PicUrl')
# TODO
elif msgType == 'voice':
mediaId = requestMap.get('MediaId')
format = requestMap.get('Format')
# TODO
elif msgType == 'video':
mediaId = requestMap.get('MediaId')
thumbMediaId = requestMap.get('ThumbMediaId')
# TODO
elif msgType == 'location':
lat = requestMap.get('Location_X')
lng = requestMap.get('Location_Y')
label = requestMap.get('Label')
scale = requestMap.get('Scale')
# TODO
elif msgType == 'link':
title = requestMap.get('Title')
description = requestMap.get('Description')
url = requestMap.get('Url')
"""
<|fim▁end|> | content = requestMap.get('Content').decode('utf-8') # note: decode first
#respContent = u'您发送的是文本消息:' + content
respContent = RobotService.auto_reply(content)
elif msgT |
<|file_name|>wechatService.py<|end_file_name|><|fim▁begin|># -*- coding:utf-8 -*-
"""
# Author: Pegasus Wang ([email protected], http://ningning.today)
# Created Time : Fri Feb 20 21:38:57 2015
# File Name: wechatService.py
# Description:
# :copyright: (c) 2015 by Pegasus Wang.
# :license: MIT, see LICENSE for more details.
"""
import json
import time
import urllib
import urllib2
from wechatUtil import MessageUtil
from wechatReply import TextReply
class RobotService(object):
"""Auto reply robot service"""
KEY = 'd92d20bc1d8bb3cff585bf746603b2a9'
url = 'http://www.tuling123.com/openapi/api'
@staticmethod
def auto_reply(req_info):
query = {'key': RobotService.KEY, 'info': req_info.encode('utf-8')}
headers = {'Content-type': 'text/html', 'charset': 'utf-8'}
data = urllib.urlencode(query)
req = urllib2.Request(RobotService.url, data)
f = urllib2.urlopen(req).read()
return json.loads(f).get('text').replace('<br>', '\n')
#return json.loads(f).get('text')
class WechatService(object):
"""process request"""
@staticmethod
def processRequest(request):
"""process different message types.
:param request: post request message
:return: None
"""
requestMap = MessageUtil.parseXml(request)
fromUserName = requestMap.get(u'FromUserName')
toUserName = requestMap.get(u'ToUserName')
createTime = requestMap.get(u'CreateTime')
msgType = requestMap.get(u'MsgType')
msgId = requestMap.get(u'MsgId')
textReply = TextReply()
textReply.setToUserName(fromUserName)
textReply.setFromUserName(toUserName)
textReply.setCreateTime(time.time())
textReply.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT)
if msgType == MessageUtil.REQ_MESSAGE_TYPE_TEXT:
content = requestMap.get('Content').decode('utf-8') # note: decode first
#respContent = u'您发送的是文本消息:' + content
respContent = RobotService.auto_reply(content)
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_IMAGE:
respContent = u'您发 <|fim_middle|>
EQ_MESSAGE_TYPE_VOICE:
respContent = u'您发送的是语音消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VIDEO:
respContent = u'您发送的是视频消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LOCATION:
respContent = u'您发送的是地理位置消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LINK:
respContent = u'您发送的是链接消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_EVENT:
eventType = requestMap.get(u'Event')
if eventType == MessageUtil.EVENT_TYPE_SUBSCRIBE:
respContent = u'^_^谢谢您的关注,本公众号由王宁宁开发(python2.7+django1.4),如果你有兴趣继续开发,' \
u'可以联系我,就当打发时间了.'
elif eventType == MessageUtil.EVENT_TYPE_UNSUBSCRIBE:
pass
elif eventType == MessageUtil.EVENT_TYPE_SCAN:
# TODO
pass
elif eventType == MessageUtil.EVENT_TYPE_LOCATION:
# TODO
pass
elif eventType == MessageUtil.EVENT_TYPE_CLICK:
# TODO
pass
textReply.setContent(respContent)
respXml = MessageUtil.class2xml(textReply)
return respXml
"""
if msgType == 'text':
content = requestMap.get('Content')
# TODO
elif msgType == 'image':
picUrl = requestMap.get('PicUrl')
# TODO
elif msgType == 'voice':
mediaId = requestMap.get('MediaId')
format = requestMap.get('Format')
# TODO
elif msgType == 'video':
mediaId = requestMap.get('MediaId')
thumbMediaId = requestMap.get('ThumbMediaId')
# TODO
elif msgType == 'location':
lat = requestMap.get('Location_X')
lng = requestMap.get('Location_Y')
label = requestMap.get('Label')
scale = requestMap.get('Scale')
# TODO
elif msgType == 'link':
title = requestMap.get('Title')
description = requestMap.get('Description')
url = requestMap.get('Url')
"""
<|fim▁end|> | 送的是图片消息!'
elif msgType == MessageUtil.R |
<|file_name|>wechatService.py<|end_file_name|><|fim▁begin|># -*- coding:utf-8 -*-
"""
# Author: Pegasus Wang ([email protected], http://ningning.today)
# Created Time : Fri Feb 20 21:38:57 2015
# File Name: wechatService.py
# Description:
# :copyright: (c) 2015 by Pegasus Wang.
# :license: MIT, see LICENSE for more details.
"""
import json
import time
import urllib
import urllib2
from wechatUtil import MessageUtil
from wechatReply import TextReply
class RobotService(object):
"""Auto reply robot service"""
KEY = 'd92d20bc1d8bb3cff585bf746603b2a9'
url = 'http://www.tuling123.com/openapi/api'
@staticmethod
def auto_reply(req_info):
query = {'key': RobotService.KEY, 'info': req_info.encode('utf-8')}
headers = {'Content-type': 'text/html', 'charset': 'utf-8'}
data = urllib.urlencode(query)
req = urllib2.Request(RobotService.url, data)
f = urllib2.urlopen(req).read()
return json.loads(f).get('text').replace('<br>', '\n')
#return json.loads(f).get('text')
class WechatService(object):
"""process request"""
@staticmethod
def processRequest(request):
"""process different message types.
:param request: post request message
:return: None
"""
requestMap = MessageUtil.parseXml(request)
fromUserName = requestMap.get(u'FromUserName')
toUserName = requestMap.get(u'ToUserName')
createTime = requestMap.get(u'CreateTime')
msgType = requestMap.get(u'MsgType')
msgId = requestMap.get(u'MsgId')
textReply = TextReply()
textReply.setToUserName(fromUserName)
textReply.setFromUserName(toUserName)
textReply.setCreateTime(time.time())
textReply.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT)
if msgType == MessageUtil.REQ_MESSAGE_TYPE_TEXT:
content = requestMap.get('Content').decode('utf-8') # note: decode first
#respContent = u'您发送的是文本消息:' + content
respContent = RobotService.auto_reply(content)
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_IMAGE:
respContent = u'您发送的是图片消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VOICE:
respContent = u'您发送的是语音消息!'
el <|fim_middle|>
O:
respContent = u'您发送的是视频消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LOCATION:
respContent = u'您发送的是地理位置消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LINK:
respContent = u'您发送的是链接消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_EVENT:
eventType = requestMap.get(u'Event')
if eventType == MessageUtil.EVENT_TYPE_SUBSCRIBE:
respContent = u'^_^谢谢您的关注,本公众号由王宁宁开发(python2.7+django1.4),如果你有兴趣继续开发,' \
u'可以联系我,就当打发时间了.'
elif eventType == MessageUtil.EVENT_TYPE_UNSUBSCRIBE:
pass
elif eventType == MessageUtil.EVENT_TYPE_SCAN:
# TODO
pass
elif eventType == MessageUtil.EVENT_TYPE_LOCATION:
# TODO
pass
elif eventType == MessageUtil.EVENT_TYPE_CLICK:
# TODO
pass
textReply.setContent(respContent)
respXml = MessageUtil.class2xml(textReply)
return respXml
"""
if msgType == 'text':
content = requestMap.get('Content')
# TODO
elif msgType == 'image':
picUrl = requestMap.get('PicUrl')
# TODO
elif msgType == 'voice':
mediaId = requestMap.get('MediaId')
format = requestMap.get('Format')
# TODO
elif msgType == 'video':
mediaId = requestMap.get('MediaId')
thumbMediaId = requestMap.get('ThumbMediaId')
# TODO
elif msgType == 'location':
lat = requestMap.get('Location_X')
lng = requestMap.get('Location_Y')
label = requestMap.get('Label')
scale = requestMap.get('Scale')
# TODO
elif msgType == 'link':
title = requestMap.get('Title')
description = requestMap.get('Description')
url = requestMap.get('Url')
"""
<|fim▁end|> | if msgType == MessageUtil.REQ_MESSAGE_TYPE_VIDE |
<|file_name|>wechatService.py<|end_file_name|><|fim▁begin|># -*- coding:utf-8 -*-
"""
# Author: Pegasus Wang ([email protected], http://ningning.today)
# Created Time : Fri Feb 20 21:38:57 2015
# File Name: wechatService.py
# Description:
# :copyright: (c) 2015 by Pegasus Wang.
# :license: MIT, see LICENSE for more details.
"""
import json
import time
import urllib
import urllib2
from wechatUtil import MessageUtil
from wechatReply import TextReply
class RobotService(object):
"""Auto reply robot service"""
KEY = 'd92d20bc1d8bb3cff585bf746603b2a9'
url = 'http://www.tuling123.com/openapi/api'
@staticmethod
def auto_reply(req_info):
query = {'key': RobotService.KEY, 'info': req_info.encode('utf-8')}
headers = {'Content-type': 'text/html', 'charset': 'utf-8'}
data = urllib.urlencode(query)
req = urllib2.Request(RobotService.url, data)
f = urllib2.urlopen(req).read()
return json.loads(f).get('text').replace('<br>', '\n')
#return json.loads(f).get('text')
class WechatService(object):
"""process request"""
@staticmethod
def processRequest(request):
"""process different message types.
:param request: post request message
:return: None
"""
requestMap = MessageUtil.parseXml(request)
fromUserName = requestMap.get(u'FromUserName')
toUserName = requestMap.get(u'ToUserName')
createTime = requestMap.get(u'CreateTime')
msgType = requestMap.get(u'MsgType')
msgId = requestMap.get(u'MsgId')
textReply = TextReply()
textReply.setToUserName(fromUserName)
textReply.setFromUserName(toUserName)
textReply.setCreateTime(time.time())
textReply.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT)
if msgType == MessageUtil.REQ_MESSAGE_TYPE_TEXT:
content = requestMap.get('Content').decode('utf-8') # note: decode first
#respContent = u'您发送的是文本消息:' + content
respContent = RobotService.auto_reply(content)
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_IMAGE:
respContent = u'您发送的是图片消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VOICE:
respContent = u'您发送的是语音消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VIDEO:
respContent = u'您发送的是视频消息!'
elif msgType == Messag <|fim_middle|>
spContent = u'您发送的是地理位置消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LINK:
respContent = u'您发送的是链接消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_EVENT:
eventType = requestMap.get(u'Event')
if eventType == MessageUtil.EVENT_TYPE_SUBSCRIBE:
respContent = u'^_^谢谢您的关注,本公众号由王宁宁开发(python2.7+django1.4),如果你有兴趣继续开发,' \
u'可以联系我,就当打发时间了.'
elif eventType == MessageUtil.EVENT_TYPE_UNSUBSCRIBE:
pass
elif eventType == MessageUtil.EVENT_TYPE_SCAN:
# TODO
pass
elif eventType == MessageUtil.EVENT_TYPE_LOCATION:
# TODO
pass
elif eventType == MessageUtil.EVENT_TYPE_CLICK:
# TODO
pass
textReply.setContent(respContent)
respXml = MessageUtil.class2xml(textReply)
return respXml
"""
if msgType == 'text':
content = requestMap.get('Content')
# TODO
elif msgType == 'image':
picUrl = requestMap.get('PicUrl')
# TODO
elif msgType == 'voice':
mediaId = requestMap.get('MediaId')
format = requestMap.get('Format')
# TODO
elif msgType == 'video':
mediaId = requestMap.get('MediaId')
thumbMediaId = requestMap.get('ThumbMediaId')
# TODO
elif msgType == 'location':
lat = requestMap.get('Location_X')
lng = requestMap.get('Location_Y')
label = requestMap.get('Label')
scale = requestMap.get('Scale')
# TODO
elif msgType == 'link':
title = requestMap.get('Title')
description = requestMap.get('Description')
url = requestMap.get('Url')
"""
<|fim▁end|> | eUtil.REQ_MESSAGE_TYPE_LOCATION:
re |
<|file_name|>wechatService.py<|end_file_name|><|fim▁begin|># -*- coding:utf-8 -*-
"""
# Author: Pegasus Wang ([email protected], http://ningning.today)
# Created Time : Fri Feb 20 21:38:57 2015
# File Name: wechatService.py
# Description:
# :copyright: (c) 2015 by Pegasus Wang.
# :license: MIT, see LICENSE for more details.
"""
import json
import time
import urllib
import urllib2
from wechatUtil import MessageUtil
from wechatReply import TextReply
class RobotService(object):
"""Auto reply robot service"""
KEY = 'd92d20bc1d8bb3cff585bf746603b2a9'
url = 'http://www.tuling123.com/openapi/api'
@staticmethod
def auto_reply(req_info):
query = {'key': RobotService.KEY, 'info': req_info.encode('utf-8')}
headers = {'Content-type': 'text/html', 'charset': 'utf-8'}
data = urllib.urlencode(query)
req = urllib2.Request(RobotService.url, data)
f = urllib2.urlopen(req).read()
return json.loads(f).get('text').replace('<br>', '\n')
#return json.loads(f).get('text')
class WechatService(object):
"""process request"""
@staticmethod
def processRequest(request):
"""process different message types.
:param request: post request message
:return: None
"""
requestMap = MessageUtil.parseXml(request)
fromUserName = requestMap.get(u'FromUserName')
toUserName = requestMap.get(u'ToUserName')
createTime = requestMap.get(u'CreateTime')
msgType = requestMap.get(u'MsgType')
msgId = requestMap.get(u'MsgId')
textReply = TextReply()
textReply.setToUserName(fromUserName)
textReply.setFromUserName(toUserName)
textReply.setCreateTime(time.time())
textReply.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT)
if msgType == MessageUtil.REQ_MESSAGE_TYPE_TEXT:
content = requestMap.get('Content').decode('utf-8') # note: decode first
#respContent = u'您发送的是文本消息:' + content
respContent = RobotService.auto_reply(content)
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_IMAGE:
respContent = u'您发送的是图片消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VOICE:
respContent = u'您发送的是语音消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VIDEO:
respContent = u'您发送的是视频消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LOCATION:
respContent = u'您发送的是地理位置消息!'
elif msgType == MessageUtil.REQ_MESSAGE_ <|fim_middle|>
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_EVENT:
eventType = requestMap.get(u'Event')
if eventType == MessageUtil.EVENT_TYPE_SUBSCRIBE:
respContent = u'^_^谢谢您的关注,本公众号由王宁宁开发(python2.7+django1.4),如果你有兴趣继续开发,' \
u'可以联系我,就当打发时间了.'
elif eventType == MessageUtil.EVENT_TYPE_UNSUBSCRIBE:
pass
elif eventType == MessageUtil.EVENT_TYPE_SCAN:
# TODO
pass
elif eventType == MessageUtil.EVENT_TYPE_LOCATION:
# TODO
pass
elif eventType == MessageUtil.EVENT_TYPE_CLICK:
# TODO
pass
textReply.setContent(respContent)
respXml = MessageUtil.class2xml(textReply)
return respXml
"""
if msgType == 'text':
content = requestMap.get('Content')
# TODO
elif msgType == 'image':
picUrl = requestMap.get('PicUrl')
# TODO
elif msgType == 'voice':
mediaId = requestMap.get('MediaId')
format = requestMap.get('Format')
# TODO
elif msgType == 'video':
mediaId = requestMap.get('MediaId')
thumbMediaId = requestMap.get('ThumbMediaId')
# TODO
elif msgType == 'location':
lat = requestMap.get('Location_X')
lng = requestMap.get('Location_Y')
label = requestMap.get('Label')
scale = requestMap.get('Scale')
# TODO
elif msgType == 'link':
title = requestMap.get('Title')
description = requestMap.get('Description')
url = requestMap.get('Url')
"""
<|fim▁end|> | TYPE_LINK:
respContent = u'您发送的是链接消息!'
|
<|file_name|>wechatService.py<|end_file_name|><|fim▁begin|># -*- coding:utf-8 -*-
"""
# Author: Pegasus Wang ([email protected], http://ningning.today)
# Created Time : Fri Feb 20 21:38:57 2015
# File Name: wechatService.py
# Description:
# :copyright: (c) 2015 by Pegasus Wang.
# :license: MIT, see LICENSE for more details.
"""
import json
import time
import urllib
import urllib2
from wechatUtil import MessageUtil
from wechatReply import TextReply
class RobotService(object):
"""Auto reply robot service"""
KEY = 'd92d20bc1d8bb3cff585bf746603b2a9'
url = 'http://www.tuling123.com/openapi/api'
@staticmethod
def auto_reply(req_info):
query = {'key': RobotService.KEY, 'info': req_info.encode('utf-8')}
headers = {'Content-type': 'text/html', 'charset': 'utf-8'}
data = urllib.urlencode(query)
req = urllib2.Request(RobotService.url, data)
f = urllib2.urlopen(req).read()
return json.loads(f).get('text').replace('<br>', '\n')
#return json.loads(f).get('text')
class WechatService(object):
"""process request"""
@staticmethod
def processRequest(request):
"""process different message types.
:param request: post request message
:return: None
"""
requestMap = MessageUtil.parseXml(request)
fromUserName = requestMap.get(u'FromUserName')
toUserName = requestMap.get(u'ToUserName')
createTime = requestMap.get(u'CreateTime')
msgType = requestMap.get(u'MsgType')
msgId = requestMap.get(u'MsgId')
textReply = TextReply()
textReply.setToUserName(fromUserName)
textReply.setFromUserName(toUserName)
textReply.setCreateTime(time.time())
textReply.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT)
if msgType == MessageUtil.REQ_MESSAGE_TYPE_TEXT:
content = requestMap.get('Content').decode('utf-8') # note: decode first
#respContent = u'您发送的是文本消息:' + content
respContent = RobotService.auto_reply(content)
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_IMAGE:
respContent = u'您发送的是图片消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VOICE:
respContent = u'您发送的是语音消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VIDEO:
respContent = u'您发送的是视频消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LOCATION:
respContent = u'您发送的是地理位置消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LINK:
respContent = u'您发送的是链接消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_EVENT:
ev <|fim_middle|>
if eventType == MessageUtil.EVENT_TYPE_SUBSCRIBE:
respContent = u'^_^谢谢您的关注,本公众号由王宁宁开发(python2.7+django1.4),如果你有兴趣继续开发,' \
u'可以联系我,就当打发时间了.'
elif eventType == MessageUtil.EVENT_TYPE_UNSUBSCRIBE:
pass
elif eventType == MessageUtil.EVENT_TYPE_SCAN:
# TODO
pass
elif eventType == MessageUtil.EVENT_TYPE_LOCATION:
# TODO
pass
elif eventType == MessageUtil.EVENT_TYPE_CLICK:
# TODO
pass
textReply.setContent(respContent)
respXml = MessageUtil.class2xml(textReply)
return respXml
"""
if msgType == 'text':
content = requestMap.get('Content')
# TODO
elif msgType == 'image':
picUrl = requestMap.get('PicUrl')
# TODO
elif msgType == 'voice':
mediaId = requestMap.get('MediaId')
format = requestMap.get('Format')
# TODO
elif msgType == 'video':
mediaId = requestMap.get('MediaId')
thumbMediaId = requestMap.get('ThumbMediaId')
# TODO
elif msgType == 'location':
lat = requestMap.get('Location_X')
lng = requestMap.get('Location_Y')
label = requestMap.get('Label')
scale = requestMap.get('Scale')
# TODO
elif msgType == 'link':
title = requestMap.get('Title')
description = requestMap.get('Description')
url = requestMap.get('Url')
"""
<|fim▁end|> | entType = requestMap.get(u'Event')
|
<|file_name|>wechatService.py<|end_file_name|><|fim▁begin|># -*- coding:utf-8 -*-
"""
# Author: Pegasus Wang ([email protected], http://ningning.today)
# Created Time : Fri Feb 20 21:38:57 2015
# File Name: wechatService.py
# Description:
# :copyright: (c) 2015 by Pegasus Wang.
# :license: MIT, see LICENSE for more details.
"""
import json
import time
import urllib
import urllib2
from wechatUtil import MessageUtil
from wechatReply import TextReply
class RobotService(object):
"""Auto reply robot service"""
KEY = 'd92d20bc1d8bb3cff585bf746603b2a9'
url = 'http://www.tuling123.com/openapi/api'
@staticmethod
def auto_reply(req_info):
query = {'key': RobotService.KEY, 'info': req_info.encode('utf-8')}
headers = {'Content-type': 'text/html', 'charset': 'utf-8'}
data = urllib.urlencode(query)
req = urllib2.Request(RobotService.url, data)
f = urllib2.urlopen(req).read()
return json.loads(f).get('text').replace('<br>', '\n')
#return json.loads(f).get('text')
class WechatService(object):
"""process request"""
@staticmethod
def processRequest(request):
"""process different message types.
:param request: post request message
:return: None
"""
requestMap = MessageUtil.parseXml(request)
fromUserName = requestMap.get(u'FromUserName')
toUserName = requestMap.get(u'ToUserName')
createTime = requestMap.get(u'CreateTime')
msgType = requestMap.get(u'MsgType')
msgId = requestMap.get(u'MsgId')
textReply = TextReply()
textReply.setToUserName(fromUserName)
textReply.setFromUserName(toUserName)
textReply.setCreateTime(time.time())
textReply.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT)
if msgType == MessageUtil.REQ_MESSAGE_TYPE_TEXT:
content = requestMap.get('Content').decode('utf-8') # note: decode first
#respContent = u'您发送的是文本消息:' + content
respContent = RobotService.auto_reply(content)
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_IMAGE:
respContent = u'您发送的是图片消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VOICE:
respContent = u'您发送的是语音消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VIDEO:
respContent = u'您发送的是视频消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LOCATION:
respContent = u'您发送的是地理位置消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LINK:
respContent = u'您发送的是链接消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_EVENT:
eventType = requestMap.get(u'Event')
if eventType == MessageUtil.EVENT_TYPE_SUBSCRIBE:
respCon <|fim_middle|>
ntent')
# TODO
elif msgType == 'image':
picUrl = requestMap.get('PicUrl')
# TODO
elif msgType == 'voice':
mediaId = requestMap.get('MediaId')
format = requestMap.get('Format')
# TODO
elif msgType == 'video':
mediaId = requestMap.get('MediaId')
thumbMediaId = requestMap.get('ThumbMediaId')
# TODO
elif msgType == 'location':
lat = requestMap.get('Location_X')
lng = requestMap.get('Location_Y')
label = requestMap.get('Label')
scale = requestMap.get('Scale')
# TODO
elif msgType == 'link':
title = requestMap.get('Title')
description = requestMap.get('Description')
url = requestMap.get('Url')
"""
<|fim▁end|> | tent = u'^_^谢谢您的关注,本公众号由王宁宁开发(python2.7+django1.4),如果你有兴趣继续开发,' \
u'可以联系我,就当打发时间了.'
elif eventType == MessageUtil.EVENT_TYPE_UNSUBSCRIBE:
pass
elif eventType == MessageUtil.EVENT_TYPE_SCAN:
# TODO
pass
elif eventType == MessageUtil.EVENT_TYPE_LOCATION:
# TODO
pass
elif eventType == MessageUtil.EVENT_TYPE_CLICK:
# TODO
pass
textReply.setContent(respContent)
respXml = MessageUtil.class2xml(textReply)
return respXml
"""
if msgType == 'text':
content = requestMap.get('Co |
<|file_name|>wechatService.py<|end_file_name|><|fim▁begin|># -*- coding:utf-8 -*-
"""
# Author: Pegasus Wang ([email protected], http://ningning.today)
# Created Time : Fri Feb 20 21:38:57 2015
# File Name: wechatService.py
# Description:
# :copyright: (c) 2015 by Pegasus Wang.
# :license: MIT, see LICENSE for more details.
"""
import json
import time
import urllib
import urllib2
from wechatUtil import MessageUtil
from wechatReply import TextReply
class RobotService(object):
"""Auto reply robot service"""
KEY = 'd92d20bc1d8bb3cff585bf746603b2a9'
url = 'http://www.tuling123.com/openapi/api'
@staticmethod
def auto_reply(req_info):
query = {'key': RobotService.KEY, 'info': req_info.encode('utf-8')}
headers = {'Content-type': 'text/html', 'charset': 'utf-8'}
data = urllib.urlencode(query)
req = urllib2.Request(RobotService.url, data)
f = urllib2.urlopen(req).read()
return json.loads(f).get('text').replace('<br>', '\n')
#return json.loads(f).get('text')
class WechatService(object):
"""process request"""
@staticmethod
def processRequest(request):
"""process different message types.
:param request: post request message
:return: None
"""
requestMap = MessageUtil.parseXml(request)
fromUserName = requestMap.get(u'FromUserName')
toUserName = requestMap.get(u'ToUserName')
createTime = requestMap.get(u'CreateTime')
msgType = requestMap.get(u'MsgType')
msgId = requestMap.get(u'MsgId')
textReply = TextReply()
textReply.setToUserName(fromUserName)
textReply.setFromUserName(toUserName)
textReply.setCreateTime(time.time())
textReply.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT)
if msgType == MessageUtil.REQ_MESSAGE_TYPE_TEXT:
content = requestMap.get('Content').decode('utf-8') # note: decode first
#respContent = u'您发送的是文本消息:' + content
respContent = RobotService.auto_reply(content)
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_IMAGE:
respContent = u'您发送的是图片消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VOICE:
respContent = u'您发送的是语音消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VIDEO:
respContent = u'您发送的是视频消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LOCATION:
respContent = u'您发送的是地理位置消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LINK:
respContent = u'您发送的是链接消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_EVENT:
eventType = requestMap.get(u'Event')
if eventType == MessageUtil.EVENT_TYPE_SUBSCRIBE:
respContent = u'^_^谢谢您的关注,本公众号由王宁宁开发(python2.7+django1.4),如果你有兴趣继续开发,' \
u'可以联系我,就当打发时间了.'
<|fim_middle|>
lif eventType == MessageUtil.EVENT_TYPE_LOCATION:
# TODO
pass
elif eventType == MessageUtil.EVENT_TYPE_CLICK:
# TODO
pass
textReply.setContent(respContent)
respXml = MessageUtil.class2xml(textReply)
return respXml
"""
if msgType == 'text':
content = requestMap.get('Content')
# TODO
elif msgType == 'image':
picUrl = requestMap.get('PicUrl')
# TODO
elif msgType == 'voice':
mediaId = requestMap.get('MediaId')
format = requestMap.get('Format')
# TODO
elif msgType == 'video':
mediaId = requestMap.get('MediaId')
thumbMediaId = requestMap.get('ThumbMediaId')
# TODO
elif msgType == 'location':
lat = requestMap.get('Location_X')
lng = requestMap.get('Location_Y')
label = requestMap.get('Label')
scale = requestMap.get('Scale')
# TODO
elif msgType == 'link':
title = requestMap.get('Title')
description = requestMap.get('Description')
url = requestMap.get('Url')
"""
<|fim▁end|> | elif eventType == MessageUtil.EVENT_TYPE_UNSUBSCRIBE:
pass
elif eventType == MessageUtil.EVENT_TYPE_SCAN:
# TODO
pass
e |
<|file_name|>wechatService.py<|end_file_name|><|fim▁begin|># -*- coding:utf-8 -*-
"""
# Author: Pegasus Wang ([email protected], http://ningning.today)
# Created Time : Fri Feb 20 21:38:57 2015
# File Name: wechatService.py
# Description:
# :copyright: (c) 2015 by Pegasus Wang.
# :license: MIT, see LICENSE for more details.
"""
import json
import time
import urllib
import urllib2
from wechatUtil import MessageUtil
from wechatReply import TextReply
class RobotService(object):
"""Auto reply robot service"""
KEY = 'd92d20bc1d8bb3cff585bf746603b2a9'
url = 'http://www.tuling123.com/openapi/api'
@staticmethod
def auto_reply(req_info):
query = {'key': RobotService.KEY, 'info': req_info.encode('utf-8')}
headers = {'Content-type': 'text/html', 'charset': 'utf-8'}
data = urllib.urlencode(query)
req = urllib2.Request(RobotService.url, data)
f = urllib2.urlopen(req).read()
return json.loads(f).get('text').replace('<br>', '\n')
#return json.loads(f).get('text')
class WechatService(object):
"""process request"""
@staticmethod
def processRequest(request):
"""process different message types.
:param request: post request message
:return: None
"""
requestMap = MessageUtil.parseXml(request)
fromUserName = requestMap.get(u'FromUserName')
toUserName = requestMap.get(u'ToUserName')
createTime = requestMap.get(u'CreateTime')
msgType = requestMap.get(u'MsgType')
msgId = requestMap.get(u'MsgId')
textReply = TextReply()
textReply.setToUserName(fromUserName)
textReply.setFromUserName(toUserName)
textReply.setCreateTime(time.time())
textReply.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT)
if msgType == MessageUtil.REQ_MESSAGE_TYPE_TEXT:
content = requestMap.get('Content').decode('utf-8') # note: decode first
#respContent = u'您发送的是文本消息:' + content
respContent = RobotService.auto_reply(content)
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_IMAGE:
respContent = u'您发送的是图片消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VOICE:
respContent = u'您发送的是语音消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VIDEO:
respContent = u'您发送的是视频消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LOCATION:
respContent = u'您发送的是地理位置消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LINK:
respContent = u'您发送的是链接消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_EVENT:
eventType = requestMap.get(u'Event')
if eventType == MessageUtil.EVENT_TYPE_SUBSCRIBE:
respContent = u'^_^谢谢您的关注,本公众号由王宁宁开发(python2.7+django1.4),如果你有兴趣继续开发,' \
u'可以联系我,就当打发时间了.'
elif eventType == MessageUtil.EVENT_TYPE_UNSUBSCRIBE:
pass
elif eventType == MessageUtil.EVENT_TYPE_SCAN:
# TODO
pass
elif eventType == MessageUtil.EVENT_TYPE_LOCATION:
# TODO
<|fim_middle|>
pass
elif eventType == MessageUtil.EVENT_TYPE_CLICK:
# TODO
pass
textReply.setContent(respContent)
respXml = MessageUtil.class2xml(textReply)
return respXml
"""
if msgType == 'text':
content = requestMap.get('Content')
# TODO
elif msgType == 'image':
picUrl = requestMap.get('PicUrl')
# TODO
elif msgType == 'voice':
mediaId = requestMap.get('MediaId')
format = requestMap.get('Format')
# TODO
elif msgType == 'video':
mediaId = requestMap.get('MediaId')
thumbMediaId = requestMap.get('ThumbMediaId')
# TODO
elif msgType == 'location':
lat = requestMap.get('Location_X')
lng = requestMap.get('Location_Y')
label = requestMap.get('Label')
scale = requestMap.get('Scale')
# TODO
elif msgType == 'link':
title = requestMap.get('Title')
description = requestMap.get('Description')
url = requestMap.get('Url')
"""
<|fim▁end|> | |
<|file_name|>wechatService.py<|end_file_name|><|fim▁begin|># -*- coding:utf-8 -*-
"""
# Author: Pegasus Wang ([email protected], http://ningning.today)
# Created Time : Fri Feb 20 21:38:57 2015
# File Name: wechatService.py
# Description:
# :copyright: (c) 2015 by Pegasus Wang.
# :license: MIT, see LICENSE for more details.
"""
import json
import time
import urllib
import urllib2
from wechatUtil import MessageUtil
from wechatReply import TextReply
class RobotService(object):
"""Auto reply robot service"""
KEY = 'd92d20bc1d8bb3cff585bf746603b2a9'
url = 'http://www.tuling123.com/openapi/api'
@staticmethod
def auto_reply(req_info):
query = {'key': RobotService.KEY, 'info': req_info.encode('utf-8')}
headers = {'Content-type': 'text/html', 'charset': 'utf-8'}
data = urllib.urlencode(query)
req = urllib2.Request(RobotService.url, data)
f = urllib2.urlopen(req).read()
return json.loads(f).get('text').replace('<br>', '\n')
#return json.loads(f).get('text')
class WechatService(object):
"""process request"""
@staticmethod
def processRequest(request):
"""process different message types.
:param request: post request message
:return: None
"""
requestMap = MessageUtil.parseXml(request)
fromUserName = requestMap.get(u'FromUserName')
toUserName = requestMap.get(u'ToUserName')
createTime = requestMap.get(u'CreateTime')
msgType = requestMap.get(u'MsgType')
msgId = requestMap.get(u'MsgId')
textReply = TextReply()
textReply.setToUserName(fromUserName)
textReply.setFromUserName(toUserName)
textReply.setCreateTime(time.time())
textReply.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT)
if msgType == MessageUtil.REQ_MESSAGE_TYPE_TEXT:
content = requestMap.get('Content').decode('utf-8') # note: decode first
#respContent = u'您发送的是文本消息:' + content
respContent = RobotService.auto_reply(content)
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_IMAGE:
respContent = u'您发送的是图片消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VOICE:
respContent = u'您发送的是语音消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VIDEO:
respContent = u'您发送的是视频消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LOCATION:
respContent = u'您发送的是地理位置消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LINK:
respContent = u'您发送的是链接消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_EVENT:
eventType = requestMap.get(u'Event')
if eventType == MessageUtil.EVENT_TYPE_SUBSCRIBE:
respContent = u'^_^谢谢您的关注,本公众号由王宁宁开发(python2.7+django1.4),如果你有兴趣继续开发,' \
u'可以联系我,就当打发时间了.'
elif eventType == MessageUtil.EVENT_TYPE_UNSUBSCRIBE:
pass
elif eventType == MessageUtil.EVENT_TYPE_SCAN:
# TODO
pass
elif eventType == MessageUtil.EVENT_TYPE_LOCATION:
# TODO
pass
elif eventType == MessageUtil.EVENT_TYPE_CLICK:
# TODO
<|fim_middle|>
pass
textReply.setContent(respContent)
respXml = MessageUtil.class2xml(textReply)
return respXml
"""
if msgType == 'text':
content = requestMap.get('Content')
# TODO
elif msgType == 'image':
picUrl = requestMap.get('PicUrl')
# TODO
elif msgType == 'voice':
mediaId = requestMap.get('MediaId')
format = requestMap.get('Format')
# TODO
elif msgType == 'video':
mediaId = requestMap.get('MediaId')
thumbMediaId = requestMap.get('ThumbMediaId')
# TODO
elif msgType == 'location':
lat = requestMap.get('Location_X')
lng = requestMap.get('Location_Y')
label = requestMap.get('Label')
scale = requestMap.get('Scale')
# TODO
elif msgType == 'link':
title = requestMap.get('Title')
description = requestMap.get('Description')
url = requestMap.get('Url')
"""
<|fim▁end|> | |
<|file_name|>wechatService.py<|end_file_name|><|fim▁begin|># -*- coding:utf-8 -*-
"""
# Author: Pegasus Wang ([email protected], http://ningning.today)
# Created Time : Fri Feb 20 21:38:57 2015
# File Name: wechatService.py
# Description:
# :copyright: (c) 2015 by Pegasus Wang.
# :license: MIT, see LICENSE for more details.
"""
import json
import time
import urllib
import urllib2
from wechatUtil import MessageUtil
from wechatReply import TextReply
class RobotService(object):
"""Auto reply robot service"""
KEY = 'd92d20bc1d8bb3cff585bf746603b2a9'
url = 'http://www.tuling123.com/openapi/api'
@staticmethod
def auto_reply(req_info):
query = {'key': RobotService.KEY, 'info': req_info.encode('utf-8')}
headers = {'Content-type': 'text/html', 'charset': 'utf-8'}
data = urllib.urlencode(query)
req = urllib2.Request(RobotService.url, data)
f = urllib2.urlopen(req).read()
return json.loads(f).get('text').replace('<br>', '\n')
#return json.loads(f).get('text')
class WechatService(object):
"""process request"""
@staticmethod
def processRequest(request):
"""process different message types.
:param request: post request message
:return: None
"""
requestMap = MessageUtil.parseXml(request)
fromUserName = requestMap.get(u'FromUserName')
toUserName = requestMap.get(u'ToUserName')
createTime = requestMap.get(u'CreateTime')
msgType = requestMap.get(u'MsgType')
msgId = requestMap.get(u'MsgId')
textReply = TextReply()
textReply.setToUserName(fromUserName)
textReply.setFromUserName(toUserName)
textReply.setCreateTime(time.time())
textReply.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT)
if msgType == MessageUtil.REQ_MESSAGE_TYPE_TEXT:
content = requestMap.get('Content').decode('utf-8') # note: decode first
#respContent = u'您发送的是文本消息:' + content
respContent = RobotService.auto_reply(content)
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_IMAGE:
respContent = u'您发送的是图片消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VOICE:
respContent = u'您发送的是语音消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VIDEO:
respContent = u'您发送的是视频消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LOCATION:
respContent = u'您发送的是地理位置消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LINK:
respContent = u'您发送的是链接消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_EVENT:
eventType = requestMap.get(u'Event')
if eventType == MessageUtil.EVENT_TYPE_SUBSCRIBE:
respContent = u'^_^谢谢您的关注,本公众号由王宁宁开发(python2.7+django1.4),如果你有兴趣继续开发,' \
u'可以联系我,就当打发时间了.'
elif eventType == MessageUtil.EVENT_TYPE_UNSUBSCRIBE:
pass
elif eventType == MessageUtil.EVENT_TYPE_SCAN:
# TODO
pass
elif eventType == MessageUtil.EVENT_TYPE_LOCATION:
# TODO
pass
elif eventType == MessageUtil.EVENT_TYPE_CLICK:
# TODO
pass
textReply.setContent(respContent)
respXml = MessageUtil.class2xml(textReply)
<|fim_middle|>
return respXml
"""
if msgType == 'text':
content = requestMap.get('Content')
# TODO
elif msgType == 'image':
picUrl = requestMap.get('PicUrl')
# TODO
elif msgType == 'voice':
mediaId = requestMap.get('MediaId')
format = requestMap.get('Format')
# TODO
elif msgType == 'video':
mediaId = requestMap.get('MediaId')
thumbMediaId = requestMap.get('ThumbMediaId')
# TODO
elif msgType == 'location':
lat = requestMap.get('Location_X')
lng = requestMap.get('Location_Y')
label = requestMap.get('Label')
scale = requestMap.get('Scale')
# TODO
elif msgType == 'link':
title = requestMap.get('Title')
description = requestMap.get('Description')
url = requestMap.get('Url')
"""
<|fim▁end|> | |
<|file_name|>wechatService.py<|end_file_name|><|fim▁begin|># -*- coding:utf-8 -*-
"""
# Author: Pegasus Wang ([email protected], http://ningning.today)
# Created Time : Fri Feb 20 21:38:57 2015
# File Name: wechatService.py
# Description:
# :copyright: (c) 2015 by Pegasus Wang.
# :license: MIT, see LICENSE for more details.
"""
import json
import time
import urllib
import urllib2
from wechatUtil import MessageUtil
from wechatReply import TextReply
class RobotService(object):
"""Auto reply robot service"""
KEY = 'd92d20bc1d8bb3cff585bf746603b2a9'
url = 'http://www.tuling123.com/openapi/api'
@staticmethod
def auto_reply(req_info):
query = {'key': RobotService.KEY, 'info': req_info.encode('utf-8')}
headers = {'Content-type': 'text/html', 'charset': 'utf-8'}
data = urllib.urlencode(query)
req = urllib2.Request(RobotService.url, data)
f = urllib2.urlopen(req).read()
return json.loads(f).get('text').replace('<br>', '\n')
#return json.loads(f).get('text')
class WechatService(object):
"""process request"""
@staticmethod
def processRequest(request):
"""process different message types.
:param request: post request message
:return: None
"""
requestMap = MessageUtil.parseXml(request)
fromUserName = requestMap.get(u'FromUserName')
toUserName = requestMap.get(u'ToUserName')
createTime = requestMap.get(u'CreateTime')
msgType = requestMap.get(u'MsgType')
msgId = requestMap.get(u'MsgId')
textReply = TextReply()
textReply.setToUserName(fromUserName)
textReply.setFromUserName(toUserName)
textReply.setCreateTime(time.time())
textReply.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT)
if msgType == MessageUtil.REQ_MESSAGE_TYPE_TEXT:
content = requestMap.get('Content').decode('utf-8') # note: decode first
#respContent = u'您发送的是文本消息:' + content
respContent = RobotService.auto_reply(content)
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_IMAGE:
respContent = u'您发送的是图片消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VOICE:
respContent = u'您发送的是语音消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VIDEO:
respContent = u'您发送的是视频消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LOCATION:
respContent = u'您发送的是地理位置消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LINK:
respContent = u'您发送的是链接消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_EVENT:
eventType = requestMap.get(u'Event')
if eventType == MessageUtil.EVENT_TYPE_SUBSCRIBE:
respContent = u'^_^谢谢您的关注,本公众号由王宁宁开发(python2.7+django1.4),如果你有兴趣继续开发,' \
u'可以联系我,就当打发时间了.'
elif eventType == MessageUtil.EVENT_TYPE_UNSUBSCRIBE:
pass
elif eventType == MessageUtil.EVENT_TYPE_SCAN:
# TODO
pass
elif eventType == MessageUtil.EVENT_TYPE_LOCATION:
# TODO
pass
elif eventType == MessageUtil.EVENT_TYPE_CLICK:
# TODO
pass
textReply.setContent(respContent)
respXml = MessageUtil.class2xml(textReply)
return respXml
"""
if msgType == 'text':
content = requestMap.get <|fim_middle|>
ntent')
# TODO
elif msgType == 'image':
picUrl = requestMap.get('PicUrl')
# TODO
elif msgType == 'voice':
mediaId = requestMap.get('MediaId')
format = requestMap.get('Format')
# TODO
elif msgType == 'video':
mediaId = requestMap.get('MediaId')
thumbMediaId = requestMap.get('ThumbMediaId')
# TODO
elif msgType == 'location':
lat = requestMap.get('Location_X')
lng = requestMap.get('Location_Y')
label = requestMap.get('Label')
scale = requestMap.get('Scale')
# TODO
elif msgType == 'link':
title = requestMap.get('Title')
description = requestMap.get('Description')
url = requestMap.get('Url')
"""
<|fim▁end|> | ('Co |
<|file_name|>wechatService.py<|end_file_name|><|fim▁begin|># -*- coding:utf-8 -*-
"""
# Author: Pegasus Wang ([email protected], http://ningning.today)
# Created Time : Fri Feb 20 21:38:57 2015
# File Name: wechatService.py
# Description:
# :copyright: (c) 2015 by Pegasus Wang.
# :license: MIT, see LICENSE for more details.
"""
import json
import time
import urllib
import urllib2
from wechatUtil import MessageUtil
from wechatReply import TextReply
class RobotService(object):
"""Auto reply robot service"""
KEY = 'd92d20bc1d8bb3cff585bf746603b2a9'
url = 'http://www.tuling123.com/openapi/api'
@staticmethod
def <|fim_middle|>(req_info):
query = {'key': RobotService.KEY, 'info': req_info.encode('utf-8')}
headers = {'Content-type': 'text/html', 'charset': 'utf-8'}
data = urllib.urlencode(query)
req = urllib2.Request(RobotService.url, data)
f = urllib2.urlopen(req).read()
return json.loads(f).get('text').replace('<br>', '\n')
#return json.loads(f).get('text')
class WechatService(object):
"""process request"""
@staticmethod
def processRequest(request):
"""process different message types.
:param request: post request message
:return: None
"""
requestMap = MessageUtil.parseXml(request)
fromUserName = requestMap.get(u'FromUserName')
toUserName = requestMap.get(u'ToUserName')
createTime = requestMap.get(u'CreateTime')
msgType = requestMap.get(u'MsgType')
msgId = requestMap.get(u'MsgId')
textReply = TextReply()
textReply.setToUserName(fromUserName)
textReply.setFromUserName(toUserName)
textReply.setCreateTime(time.time())
textReply.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT)
if msgType == MessageUtil.REQ_MESSAGE_TYPE_TEXT:
content = requestMap.get('Content').decode('utf-8') # note: decode first
#respContent = u'您发送的是文本消息:' + content
respContent = RobotService.auto_reply(content)
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_IMAGE:
respContent = u'您发送的是图片消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VOICE:
respContent = u'您发送的是语音消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VIDEO:
respContent = u'您发送的是视频消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LOCATION:
respContent = u'您发送的是地理位置消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LINK:
respContent = u'您发送的是链接消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_EVENT:
eventType = requestMap.get(u'Event')
if eventType == MessageUtil.EVENT_TYPE_SUBSCRIBE:
respContent = u'^_^谢谢您的关注,本公众号由王宁宁开发(python2.7+django1.4),如果你有兴趣继续开发,' \
u'可以联系我,就当打发时间了.'
elif eventType == MessageUtil.EVENT_TYPE_UNSUBSCRIBE:
pass
elif eventType == MessageUtil.EVENT_TYPE_SCAN:
# TODO
pass
elif eventType == MessageUtil.EVENT_TYPE_LOCATION:
# TODO
pass
elif eventType == MessageUtil.EVENT_TYPE_CLICK:
# TODO
pass
textReply.setContent(respContent)
respXml = MessageUtil.class2xml(textReply)
return respXml
"""
if msgType == 'text':
content = requestMap.get('Content')
# TODO
elif msgType == 'image':
picUrl = requestMap.get('PicUrl')
# TODO
elif msgType == 'voice':
mediaId = requestMap.get('MediaId')
format = requestMap.get('Format')
# TODO
elif msgType == 'video':
mediaId = requestMap.get('MediaId')
thumbMediaId = requestMap.get('ThumbMediaId')
# TODO
elif msgType == 'location':
lat = requestMap.get('Location_X')
lng = requestMap.get('Location_Y')
label = requestMap.get('Label')
scale = requestMap.get('Scale')
# TODO
elif msgType == 'link':
title = requestMap.get('Title')
description = requestMap.get('Description')
url = requestMap.get('Url')
"""
<|fim▁end|> | auto_reply |
<|file_name|>wechatService.py<|end_file_name|><|fim▁begin|># -*- coding:utf-8 -*-
"""
# Author: Pegasus Wang ([email protected], http://ningning.today)
# Created Time : Fri Feb 20 21:38:57 2015
# File Name: wechatService.py
# Description:
# :copyright: (c) 2015 by Pegasus Wang.
# :license: MIT, see LICENSE for more details.
"""
import json
import time
import urllib
import urllib2
from wechatUtil import MessageUtil
from wechatReply import TextReply
class RobotService(object):
"""Auto reply robot service"""
KEY = 'd92d20bc1d8bb3cff585bf746603b2a9'
url = 'http://www.tuling123.com/openapi/api'
@staticmethod
def auto_reply(req_info):
query = {'key': RobotService.KEY, 'info': req_info.encode('utf-8')}
headers = {'Content-type': 'text/html', 'charset': 'utf-8'}
data = urllib.urlencode(query)
req = urllib2.Request(RobotService.url, data)
f = urllib2.urlopen(req).read()
return json.loads(f).get('text').replace('<br>', '\n')
#return json.loads(f).get('text')
class WechatService(object):
"""process request"""
@staticmethod
def <|fim_middle|>(request):
"""process different message types.
:param request: post request message
:return: None
"""
requestMap = MessageUtil.parseXml(request)
fromUserName = requestMap.get(u'FromUserName')
toUserName = requestMap.get(u'ToUserName')
createTime = requestMap.get(u'CreateTime')
msgType = requestMap.get(u'MsgType')
msgId = requestMap.get(u'MsgId')
textReply = TextReply()
textReply.setToUserName(fromUserName)
textReply.setFromUserName(toUserName)
textReply.setCreateTime(time.time())
textReply.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT)
if msgType == MessageUtil.REQ_MESSAGE_TYPE_TEXT:
content = requestMap.get('Content').decode('utf-8') # note: decode first
#respContent = u'您发送的是文本消息:' + content
respContent = RobotService.auto_reply(content)
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_IMAGE:
respContent = u'您发送的是图片消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VOICE:
respContent = u'您发送的是语音消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VIDEO:
respContent = u'您发送的是视频消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LOCATION:
respContent = u'您发送的是地理位置消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LINK:
respContent = u'您发送的是链接消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_EVENT:
eventType = requestMap.get(u'Event')
if eventType == MessageUtil.EVENT_TYPE_SUBSCRIBE:
respContent = u'^_^谢谢您的关注,本公众号由王宁宁开发(python2.7+django1.4),如果你有兴趣继续开发,' \
u'可以联系我,就当打发时间了.'
elif eventType == MessageUtil.EVENT_TYPE_UNSUBSCRIBE:
pass
elif eventType == MessageUtil.EVENT_TYPE_SCAN:
# TODO
pass
elif eventType == MessageUtil.EVENT_TYPE_LOCATION:
# TODO
pass
elif eventType == MessageUtil.EVENT_TYPE_CLICK:
# TODO
pass
textReply.setContent(respContent)
respXml = MessageUtil.class2xml(textReply)
return respXml
"""
if msgType == 'text':
content = requestMap.get('Content')
# TODO
elif msgType == 'image':
picUrl = requestMap.get('PicUrl')
# TODO
elif msgType == 'voice':
mediaId = requestMap.get('MediaId')
format = requestMap.get('Format')
# TODO
elif msgType == 'video':
mediaId = requestMap.get('MediaId')
thumbMediaId = requestMap.get('ThumbMediaId')
# TODO
elif msgType == 'location':
lat = requestMap.get('Location_X')
lng = requestMap.get('Location_Y')
label = requestMap.get('Label')
scale = requestMap.get('Scale')
# TODO
elif msgType == 'link':
title = requestMap.get('Title')
description = requestMap.get('Description')
url = requestMap.get('Url')
"""
<|fim▁end|> | processRequest |
<|file_name|>htmls2csvs.py<|end_file_name|><|fim▁begin|># pylint: disable = C0301
from bs4 import BeautifulSoup
from urllib2 import urlopen
import pandas as pd
pos_idx_map = {
'qb': 2,
'rb': 3,
'wr': 4,
'te': 5,
}
def make_url(pos, wk):
ii = pos_idx_map[pos]
fstr = "http://fantasydata.com/nfl-stats/nfl-fantasy-football-stats.aspx?fs=1&stype=0&sn=1&w=%s&s=&t=0&p=%s&st=FantasyPointsPPR&d=1&ls=&live=false" \
% (wk, ii)
return fstr
def html2df(soup):
table = soup.find('table')
headers = [header.text.lower() for header in table.find_all('th')]
rows = []
for row in table.find_all('tr'):
rows.append([val.text.encode('utf8') for val in row.find_all('td')])
rows = [rr for rr in rows if len(rr) > 0]
df = pd.DataFrame.from_records(rows)
df.columns = headers
return df
def position_html_local(posn):
dflist = []
for ii in range(1, 17):
fname = '%s%s.html' % (posn, ii)
with open(fname) as f:
df = html2df(BeautifulSoup(f))
df['wk'] = ii<|fim▁hole|>def position_html(posn):
dflist = []
for ii in range(1, 17):
fname = make_url(posn, ii)
df = html2df(BeautifulSoup(urlopen(fname)))
df['wk'] = ii
df.columns = header_clean(df.columns, posn)
dflist.append(df)
return pd.concat(dflist)
pos_header_suffixes = {
'qb': ['_pass', '_rush'],
'rb': ['_rush', '_recv'],
'wr': ['_recv'],
'te': ['_recv'],
}
exclude_cols = ['rk', 'player', 'team', 'pos', 'fantasy points',
'wk', 'fum', 'lost', 'qb rating']
def header_clean(header, posn):
res = []
if posn in pos_header_suffixes:
suffixes = pos_header_suffixes[posn]
seen_dict = {hh: 0 for hh in header}
for hh in header:
if not hh in exclude_cols:
hres = hh + suffixes[seen_dict[hh]]
seen_dict[hh] += 1
res.append(hres)
else:
res.append(hh)
else:
res = header
return res
if __name__ == '__main__':
data_all = {}
for pp in ['qb', 'wr', 'rb', 'te']:
data_all[pp] = position_html_local(pp)
data_all[pp].to_pickle('%s.pkl' % pp)<|fim▁end|> | df.columns = header_clean(df.columns, posn)
dflist.append(df)
return pd.concat(dflist)
|
<|file_name|>htmls2csvs.py<|end_file_name|><|fim▁begin|># pylint: disable = C0301
from bs4 import BeautifulSoup
from urllib2 import urlopen
import pandas as pd
pos_idx_map = {
'qb': 2,
'rb': 3,
'wr': 4,
'te': 5,
}
def make_url(pos, wk):
<|fim_middle|>
def html2df(soup):
table = soup.find('table')
headers = [header.text.lower() for header in table.find_all('th')]
rows = []
for row in table.find_all('tr'):
rows.append([val.text.encode('utf8') for val in row.find_all('td')])
rows = [rr for rr in rows if len(rr) > 0]
df = pd.DataFrame.from_records(rows)
df.columns = headers
return df
def position_html_local(posn):
dflist = []
for ii in range(1, 17):
fname = '%s%s.html' % (posn, ii)
with open(fname) as f:
df = html2df(BeautifulSoup(f))
df['wk'] = ii
df.columns = header_clean(df.columns, posn)
dflist.append(df)
return pd.concat(dflist)
def position_html(posn):
dflist = []
for ii in range(1, 17):
fname = make_url(posn, ii)
df = html2df(BeautifulSoup(urlopen(fname)))
df['wk'] = ii
df.columns = header_clean(df.columns, posn)
dflist.append(df)
return pd.concat(dflist)
pos_header_suffixes = {
'qb': ['_pass', '_rush'],
'rb': ['_rush', '_recv'],
'wr': ['_recv'],
'te': ['_recv'],
}
exclude_cols = ['rk', 'player', 'team', 'pos', 'fantasy points',
'wk', 'fum', 'lost', 'qb rating']
def header_clean(header, posn):
res = []
if posn in pos_header_suffixes:
suffixes = pos_header_suffixes[posn]
seen_dict = {hh: 0 for hh in header}
for hh in header:
if not hh in exclude_cols:
hres = hh + suffixes[seen_dict[hh]]
seen_dict[hh] += 1
res.append(hres)
else:
res.append(hh)
else:
res = header
return res
if __name__ == '__main__':
data_all = {}
for pp in ['qb', 'wr', 'rb', 'te']:
data_all[pp] = position_html_local(pp)
data_all[pp].to_pickle('%s.pkl' % pp)
<|fim▁end|> | ii = pos_idx_map[pos]
fstr = "http://fantasydata.com/nfl-stats/nfl-fantasy-football-stats.aspx?fs=1&stype=0&sn=1&w=%s&s=&t=0&p=%s&st=FantasyPointsPPR&d=1&ls=&live=false" \
% (wk, ii)
return fstr |
<|file_name|>htmls2csvs.py<|end_file_name|><|fim▁begin|># pylint: disable = C0301
from bs4 import BeautifulSoup
from urllib2 import urlopen
import pandas as pd
pos_idx_map = {
'qb': 2,
'rb': 3,
'wr': 4,
'te': 5,
}
def make_url(pos, wk):
ii = pos_idx_map[pos]
fstr = "http://fantasydata.com/nfl-stats/nfl-fantasy-football-stats.aspx?fs=1&stype=0&sn=1&w=%s&s=&t=0&p=%s&st=FantasyPointsPPR&d=1&ls=&live=false" \
% (wk, ii)
return fstr
def html2df(soup):
<|fim_middle|>
def position_html_local(posn):
dflist = []
for ii in range(1, 17):
fname = '%s%s.html' % (posn, ii)
with open(fname) as f:
df = html2df(BeautifulSoup(f))
df['wk'] = ii
df.columns = header_clean(df.columns, posn)
dflist.append(df)
return pd.concat(dflist)
def position_html(posn):
dflist = []
for ii in range(1, 17):
fname = make_url(posn, ii)
df = html2df(BeautifulSoup(urlopen(fname)))
df['wk'] = ii
df.columns = header_clean(df.columns, posn)
dflist.append(df)
return pd.concat(dflist)
pos_header_suffixes = {
'qb': ['_pass', '_rush'],
'rb': ['_rush', '_recv'],
'wr': ['_recv'],
'te': ['_recv'],
}
exclude_cols = ['rk', 'player', 'team', 'pos', 'fantasy points',
'wk', 'fum', 'lost', 'qb rating']
def header_clean(header, posn):
res = []
if posn in pos_header_suffixes:
suffixes = pos_header_suffixes[posn]
seen_dict = {hh: 0 for hh in header}
for hh in header:
if not hh in exclude_cols:
hres = hh + suffixes[seen_dict[hh]]
seen_dict[hh] += 1
res.append(hres)
else:
res.append(hh)
else:
res = header
return res
if __name__ == '__main__':
data_all = {}
for pp in ['qb', 'wr', 'rb', 'te']:
data_all[pp] = position_html_local(pp)
data_all[pp].to_pickle('%s.pkl' % pp)
<|fim▁end|> | table = soup.find('table')
headers = [header.text.lower() for header in table.find_all('th')]
rows = []
for row in table.find_all('tr'):
rows.append([val.text.encode('utf8') for val in row.find_all('td')])
rows = [rr for rr in rows if len(rr) > 0]
df = pd.DataFrame.from_records(rows)
df.columns = headers
return df |
<|file_name|>htmls2csvs.py<|end_file_name|><|fim▁begin|># pylint: disable = C0301
from bs4 import BeautifulSoup
from urllib2 import urlopen
import pandas as pd
pos_idx_map = {
'qb': 2,
'rb': 3,
'wr': 4,
'te': 5,
}
def make_url(pos, wk):
ii = pos_idx_map[pos]
fstr = "http://fantasydata.com/nfl-stats/nfl-fantasy-football-stats.aspx?fs=1&stype=0&sn=1&w=%s&s=&t=0&p=%s&st=FantasyPointsPPR&d=1&ls=&live=false" \
% (wk, ii)
return fstr
def html2df(soup):
table = soup.find('table')
headers = [header.text.lower() for header in table.find_all('th')]
rows = []
for row in table.find_all('tr'):
rows.append([val.text.encode('utf8') for val in row.find_all('td')])
rows = [rr for rr in rows if len(rr) > 0]
df = pd.DataFrame.from_records(rows)
df.columns = headers
return df
def position_html_local(posn):
<|fim_middle|>
def position_html(posn):
dflist = []
for ii in range(1, 17):
fname = make_url(posn, ii)
df = html2df(BeautifulSoup(urlopen(fname)))
df['wk'] = ii
df.columns = header_clean(df.columns, posn)
dflist.append(df)
return pd.concat(dflist)
pos_header_suffixes = {
'qb': ['_pass', '_rush'],
'rb': ['_rush', '_recv'],
'wr': ['_recv'],
'te': ['_recv'],
}
exclude_cols = ['rk', 'player', 'team', 'pos', 'fantasy points',
'wk', 'fum', 'lost', 'qb rating']
def header_clean(header, posn):
res = []
if posn in pos_header_suffixes:
suffixes = pos_header_suffixes[posn]
seen_dict = {hh: 0 for hh in header}
for hh in header:
if not hh in exclude_cols:
hres = hh + suffixes[seen_dict[hh]]
seen_dict[hh] += 1
res.append(hres)
else:
res.append(hh)
else:
res = header
return res
if __name__ == '__main__':
data_all = {}
for pp in ['qb', 'wr', 'rb', 'te']:
data_all[pp] = position_html_local(pp)
data_all[pp].to_pickle('%s.pkl' % pp)
<|fim▁end|> | dflist = []
for ii in range(1, 17):
fname = '%s%s.html' % (posn, ii)
with open(fname) as f:
df = html2df(BeautifulSoup(f))
df['wk'] = ii
df.columns = header_clean(df.columns, posn)
dflist.append(df)
return pd.concat(dflist) |
<|file_name|>htmls2csvs.py<|end_file_name|><|fim▁begin|># pylint: disable = C0301
from bs4 import BeautifulSoup
from urllib2 import urlopen
import pandas as pd
pos_idx_map = {
'qb': 2,
'rb': 3,
'wr': 4,
'te': 5,
}
def make_url(pos, wk):
ii = pos_idx_map[pos]
fstr = "http://fantasydata.com/nfl-stats/nfl-fantasy-football-stats.aspx?fs=1&stype=0&sn=1&w=%s&s=&t=0&p=%s&st=FantasyPointsPPR&d=1&ls=&live=false" \
% (wk, ii)
return fstr
def html2df(soup):
table = soup.find('table')
headers = [header.text.lower() for header in table.find_all('th')]
rows = []
for row in table.find_all('tr'):
rows.append([val.text.encode('utf8') for val in row.find_all('td')])
rows = [rr for rr in rows if len(rr) > 0]
df = pd.DataFrame.from_records(rows)
df.columns = headers
return df
def position_html_local(posn):
dflist = []
for ii in range(1, 17):
fname = '%s%s.html' % (posn, ii)
with open(fname) as f:
df = html2df(BeautifulSoup(f))
df['wk'] = ii
df.columns = header_clean(df.columns, posn)
dflist.append(df)
return pd.concat(dflist)
def position_html(posn):
<|fim_middle|>
pos_header_suffixes = {
'qb': ['_pass', '_rush'],
'rb': ['_rush', '_recv'],
'wr': ['_recv'],
'te': ['_recv'],
}
exclude_cols = ['rk', 'player', 'team', 'pos', 'fantasy points',
'wk', 'fum', 'lost', 'qb rating']
def header_clean(header, posn):
res = []
if posn in pos_header_suffixes:
suffixes = pos_header_suffixes[posn]
seen_dict = {hh: 0 for hh in header}
for hh in header:
if not hh in exclude_cols:
hres = hh + suffixes[seen_dict[hh]]
seen_dict[hh] += 1
res.append(hres)
else:
res.append(hh)
else:
res = header
return res
if __name__ == '__main__':
data_all = {}
for pp in ['qb', 'wr', 'rb', 'te']:
data_all[pp] = position_html_local(pp)
data_all[pp].to_pickle('%s.pkl' % pp)
<|fim▁end|> | dflist = []
for ii in range(1, 17):
fname = make_url(posn, ii)
df = html2df(BeautifulSoup(urlopen(fname)))
df['wk'] = ii
df.columns = header_clean(df.columns, posn)
dflist.append(df)
return pd.concat(dflist) |
<|file_name|>htmls2csvs.py<|end_file_name|><|fim▁begin|># pylint: disable = C0301
from bs4 import BeautifulSoup
from urllib2 import urlopen
import pandas as pd
pos_idx_map = {
'qb': 2,
'rb': 3,
'wr': 4,
'te': 5,
}
def make_url(pos, wk):
ii = pos_idx_map[pos]
fstr = "http://fantasydata.com/nfl-stats/nfl-fantasy-football-stats.aspx?fs=1&stype=0&sn=1&w=%s&s=&t=0&p=%s&st=FantasyPointsPPR&d=1&ls=&live=false" \
% (wk, ii)
return fstr
def html2df(soup):
table = soup.find('table')
headers = [header.text.lower() for header in table.find_all('th')]
rows = []
for row in table.find_all('tr'):
rows.append([val.text.encode('utf8') for val in row.find_all('td')])
rows = [rr for rr in rows if len(rr) > 0]
df = pd.DataFrame.from_records(rows)
df.columns = headers
return df
def position_html_local(posn):
dflist = []
for ii in range(1, 17):
fname = '%s%s.html' % (posn, ii)
with open(fname) as f:
df = html2df(BeautifulSoup(f))
df['wk'] = ii
df.columns = header_clean(df.columns, posn)
dflist.append(df)
return pd.concat(dflist)
def position_html(posn):
dflist = []
for ii in range(1, 17):
fname = make_url(posn, ii)
df = html2df(BeautifulSoup(urlopen(fname)))
df['wk'] = ii
df.columns = header_clean(df.columns, posn)
dflist.append(df)
return pd.concat(dflist)
pos_header_suffixes = {
'qb': ['_pass', '_rush'],
'rb': ['_rush', '_recv'],
'wr': ['_recv'],
'te': ['_recv'],
}
exclude_cols = ['rk', 'player', 'team', 'pos', 'fantasy points',
'wk', 'fum', 'lost', 'qb rating']
def header_clean(header, posn):
<|fim_middle|>
if __name__ == '__main__':
data_all = {}
for pp in ['qb', 'wr', 'rb', 'te']:
data_all[pp] = position_html_local(pp)
data_all[pp].to_pickle('%s.pkl' % pp)
<|fim▁end|> | res = []
if posn in pos_header_suffixes:
suffixes = pos_header_suffixes[posn]
seen_dict = {hh: 0 for hh in header}
for hh in header:
if not hh in exclude_cols:
hres = hh + suffixes[seen_dict[hh]]
seen_dict[hh] += 1
res.append(hres)
else:
res.append(hh)
else:
res = header
return res |
<|file_name|>htmls2csvs.py<|end_file_name|><|fim▁begin|># pylint: disable = C0301
from bs4 import BeautifulSoup
from urllib2 import urlopen
import pandas as pd
pos_idx_map = {
'qb': 2,
'rb': 3,
'wr': 4,
'te': 5,
}
def make_url(pos, wk):
ii = pos_idx_map[pos]
fstr = "http://fantasydata.com/nfl-stats/nfl-fantasy-football-stats.aspx?fs=1&stype=0&sn=1&w=%s&s=&t=0&p=%s&st=FantasyPointsPPR&d=1&ls=&live=false" \
% (wk, ii)
return fstr
def html2df(soup):
table = soup.find('table')
headers = [header.text.lower() for header in table.find_all('th')]
rows = []
for row in table.find_all('tr'):
rows.append([val.text.encode('utf8') for val in row.find_all('td')])
rows = [rr for rr in rows if len(rr) > 0]
df = pd.DataFrame.from_records(rows)
df.columns = headers
return df
def position_html_local(posn):
dflist = []
for ii in range(1, 17):
fname = '%s%s.html' % (posn, ii)
with open(fname) as f:
df = html2df(BeautifulSoup(f))
df['wk'] = ii
df.columns = header_clean(df.columns, posn)
dflist.append(df)
return pd.concat(dflist)
def position_html(posn):
dflist = []
for ii in range(1, 17):
fname = make_url(posn, ii)
df = html2df(BeautifulSoup(urlopen(fname)))
df['wk'] = ii
df.columns = header_clean(df.columns, posn)
dflist.append(df)
return pd.concat(dflist)
pos_header_suffixes = {
'qb': ['_pass', '_rush'],
'rb': ['_rush', '_recv'],
'wr': ['_recv'],
'te': ['_recv'],
}
exclude_cols = ['rk', 'player', 'team', 'pos', 'fantasy points',
'wk', 'fum', 'lost', 'qb rating']
def header_clean(header, posn):
res = []
if posn in pos_header_suffixes:
<|fim_middle|>
else:
res = header
return res
if __name__ == '__main__':
data_all = {}
for pp in ['qb', 'wr', 'rb', 'te']:
data_all[pp] = position_html_local(pp)
data_all[pp].to_pickle('%s.pkl' % pp)
<|fim▁end|> | suffixes = pos_header_suffixes[posn]
seen_dict = {hh: 0 for hh in header}
for hh in header:
if not hh in exclude_cols:
hres = hh + suffixes[seen_dict[hh]]
seen_dict[hh] += 1
res.append(hres)
else:
res.append(hh) |
<|file_name|>htmls2csvs.py<|end_file_name|><|fim▁begin|># pylint: disable = C0301
from bs4 import BeautifulSoup
from urllib2 import urlopen
import pandas as pd
pos_idx_map = {
'qb': 2,
'rb': 3,
'wr': 4,
'te': 5,
}
def make_url(pos, wk):
ii = pos_idx_map[pos]
fstr = "http://fantasydata.com/nfl-stats/nfl-fantasy-football-stats.aspx?fs=1&stype=0&sn=1&w=%s&s=&t=0&p=%s&st=FantasyPointsPPR&d=1&ls=&live=false" \
% (wk, ii)
return fstr
def html2df(soup):
table = soup.find('table')
headers = [header.text.lower() for header in table.find_all('th')]
rows = []
for row in table.find_all('tr'):
rows.append([val.text.encode('utf8') for val in row.find_all('td')])
rows = [rr for rr in rows if len(rr) > 0]
df = pd.DataFrame.from_records(rows)
df.columns = headers
return df
def position_html_local(posn):
dflist = []
for ii in range(1, 17):
fname = '%s%s.html' % (posn, ii)
with open(fname) as f:
df = html2df(BeautifulSoup(f))
df['wk'] = ii
df.columns = header_clean(df.columns, posn)
dflist.append(df)
return pd.concat(dflist)
def position_html(posn):
dflist = []
for ii in range(1, 17):
fname = make_url(posn, ii)
df = html2df(BeautifulSoup(urlopen(fname)))
df['wk'] = ii
df.columns = header_clean(df.columns, posn)
dflist.append(df)
return pd.concat(dflist)
pos_header_suffixes = {
'qb': ['_pass', '_rush'],
'rb': ['_rush', '_recv'],
'wr': ['_recv'],
'te': ['_recv'],
}
exclude_cols = ['rk', 'player', 'team', 'pos', 'fantasy points',
'wk', 'fum', 'lost', 'qb rating']
def header_clean(header, posn):
res = []
if posn in pos_header_suffixes:
suffixes = pos_header_suffixes[posn]
seen_dict = {hh: 0 for hh in header}
for hh in header:
if not hh in exclude_cols:
<|fim_middle|>
else:
res.append(hh)
else:
res = header
return res
if __name__ == '__main__':
data_all = {}
for pp in ['qb', 'wr', 'rb', 'te']:
data_all[pp] = position_html_local(pp)
data_all[pp].to_pickle('%s.pkl' % pp)
<|fim▁end|> | hres = hh + suffixes[seen_dict[hh]]
seen_dict[hh] += 1
res.append(hres) |
<|file_name|>htmls2csvs.py<|end_file_name|><|fim▁begin|># pylint: disable = C0301
from bs4 import BeautifulSoup
from urllib2 import urlopen
import pandas as pd
pos_idx_map = {
'qb': 2,
'rb': 3,
'wr': 4,
'te': 5,
}
def make_url(pos, wk):
ii = pos_idx_map[pos]
fstr = "http://fantasydata.com/nfl-stats/nfl-fantasy-football-stats.aspx?fs=1&stype=0&sn=1&w=%s&s=&t=0&p=%s&st=FantasyPointsPPR&d=1&ls=&live=false" \
% (wk, ii)
return fstr
def html2df(soup):
table = soup.find('table')
headers = [header.text.lower() for header in table.find_all('th')]
rows = []
for row in table.find_all('tr'):
rows.append([val.text.encode('utf8') for val in row.find_all('td')])
rows = [rr for rr in rows if len(rr) > 0]
df = pd.DataFrame.from_records(rows)
df.columns = headers
return df
def position_html_local(posn):
dflist = []
for ii in range(1, 17):
fname = '%s%s.html' % (posn, ii)
with open(fname) as f:
df = html2df(BeautifulSoup(f))
df['wk'] = ii
df.columns = header_clean(df.columns, posn)
dflist.append(df)
return pd.concat(dflist)
def position_html(posn):
dflist = []
for ii in range(1, 17):
fname = make_url(posn, ii)
df = html2df(BeautifulSoup(urlopen(fname)))
df['wk'] = ii
df.columns = header_clean(df.columns, posn)
dflist.append(df)
return pd.concat(dflist)
pos_header_suffixes = {
'qb': ['_pass', '_rush'],
'rb': ['_rush', '_recv'],
'wr': ['_recv'],
'te': ['_recv'],
}
exclude_cols = ['rk', 'player', 'team', 'pos', 'fantasy points',
'wk', 'fum', 'lost', 'qb rating']
def header_clean(header, posn):
res = []
if posn in pos_header_suffixes:
suffixes = pos_header_suffixes[posn]
seen_dict = {hh: 0 for hh in header}
for hh in header:
if not hh in exclude_cols:
hres = hh + suffixes[seen_dict[hh]]
seen_dict[hh] += 1
res.append(hres)
else:
<|fim_middle|>
else:
res = header
return res
if __name__ == '__main__':
data_all = {}
for pp in ['qb', 'wr', 'rb', 'te']:
data_all[pp] = position_html_local(pp)
data_all[pp].to_pickle('%s.pkl' % pp)
<|fim▁end|> | res.append(hh) |
<|file_name|>htmls2csvs.py<|end_file_name|><|fim▁begin|># pylint: disable = C0301
from bs4 import BeautifulSoup
from urllib2 import urlopen
import pandas as pd
pos_idx_map = {
'qb': 2,
'rb': 3,
'wr': 4,
'te': 5,
}
def make_url(pos, wk):
ii = pos_idx_map[pos]
fstr = "http://fantasydata.com/nfl-stats/nfl-fantasy-football-stats.aspx?fs=1&stype=0&sn=1&w=%s&s=&t=0&p=%s&st=FantasyPointsPPR&d=1&ls=&live=false" \
% (wk, ii)
return fstr
def html2df(soup):
table = soup.find('table')
headers = [header.text.lower() for header in table.find_all('th')]
rows = []
for row in table.find_all('tr'):
rows.append([val.text.encode('utf8') for val in row.find_all('td')])
rows = [rr for rr in rows if len(rr) > 0]
df = pd.DataFrame.from_records(rows)
df.columns = headers
return df
def position_html_local(posn):
dflist = []
for ii in range(1, 17):
fname = '%s%s.html' % (posn, ii)
with open(fname) as f:
df = html2df(BeautifulSoup(f))
df['wk'] = ii
df.columns = header_clean(df.columns, posn)
dflist.append(df)
return pd.concat(dflist)
def position_html(posn):
dflist = []
for ii in range(1, 17):
fname = make_url(posn, ii)
df = html2df(BeautifulSoup(urlopen(fname)))
df['wk'] = ii
df.columns = header_clean(df.columns, posn)
dflist.append(df)
return pd.concat(dflist)
pos_header_suffixes = {
'qb': ['_pass', '_rush'],
'rb': ['_rush', '_recv'],
'wr': ['_recv'],
'te': ['_recv'],
}
exclude_cols = ['rk', 'player', 'team', 'pos', 'fantasy points',
'wk', 'fum', 'lost', 'qb rating']
def header_clean(header, posn):
res = []
if posn in pos_header_suffixes:
suffixes = pos_header_suffixes[posn]
seen_dict = {hh: 0 for hh in header}
for hh in header:
if not hh in exclude_cols:
hres = hh + suffixes[seen_dict[hh]]
seen_dict[hh] += 1
res.append(hres)
else:
res.append(hh)
else:
<|fim_middle|>
return res
if __name__ == '__main__':
data_all = {}
for pp in ['qb', 'wr', 'rb', 'te']:
data_all[pp] = position_html_local(pp)
data_all[pp].to_pickle('%s.pkl' % pp)
<|fim▁end|> | res = header |
<|file_name|>htmls2csvs.py<|end_file_name|><|fim▁begin|># pylint: disable = C0301
from bs4 import BeautifulSoup
from urllib2 import urlopen
import pandas as pd
pos_idx_map = {
'qb': 2,
'rb': 3,
'wr': 4,
'te': 5,
}
def make_url(pos, wk):
ii = pos_idx_map[pos]
fstr = "http://fantasydata.com/nfl-stats/nfl-fantasy-football-stats.aspx?fs=1&stype=0&sn=1&w=%s&s=&t=0&p=%s&st=FantasyPointsPPR&d=1&ls=&live=false" \
% (wk, ii)
return fstr
def html2df(soup):
table = soup.find('table')
headers = [header.text.lower() for header in table.find_all('th')]
rows = []
for row in table.find_all('tr'):
rows.append([val.text.encode('utf8') for val in row.find_all('td')])
rows = [rr for rr in rows if len(rr) > 0]
df = pd.DataFrame.from_records(rows)
df.columns = headers
return df
def position_html_local(posn):
dflist = []
for ii in range(1, 17):
fname = '%s%s.html' % (posn, ii)
with open(fname) as f:
df = html2df(BeautifulSoup(f))
df['wk'] = ii
df.columns = header_clean(df.columns, posn)
dflist.append(df)
return pd.concat(dflist)
def position_html(posn):
dflist = []
for ii in range(1, 17):
fname = make_url(posn, ii)
df = html2df(BeautifulSoup(urlopen(fname)))
df['wk'] = ii
df.columns = header_clean(df.columns, posn)
dflist.append(df)
return pd.concat(dflist)
pos_header_suffixes = {
'qb': ['_pass', '_rush'],
'rb': ['_rush', '_recv'],
'wr': ['_recv'],
'te': ['_recv'],
}
exclude_cols = ['rk', 'player', 'team', 'pos', 'fantasy points',
'wk', 'fum', 'lost', 'qb rating']
def header_clean(header, posn):
res = []
if posn in pos_header_suffixes:
suffixes = pos_header_suffixes[posn]
seen_dict = {hh: 0 for hh in header}
for hh in header:
if not hh in exclude_cols:
hres = hh + suffixes[seen_dict[hh]]
seen_dict[hh] += 1
res.append(hres)
else:
res.append(hh)
else:
res = header
return res
if __name__ == '__main__':
<|fim_middle|>
<|fim▁end|> | data_all = {}
for pp in ['qb', 'wr', 'rb', 'te']:
data_all[pp] = position_html_local(pp)
data_all[pp].to_pickle('%s.pkl' % pp) |
<|file_name|>htmls2csvs.py<|end_file_name|><|fim▁begin|># pylint: disable = C0301
from bs4 import BeautifulSoup
from urllib2 import urlopen
import pandas as pd
pos_idx_map = {
'qb': 2,
'rb': 3,
'wr': 4,
'te': 5,
}
def <|fim_middle|>(pos, wk):
ii = pos_idx_map[pos]
fstr = "http://fantasydata.com/nfl-stats/nfl-fantasy-football-stats.aspx?fs=1&stype=0&sn=1&w=%s&s=&t=0&p=%s&st=FantasyPointsPPR&d=1&ls=&live=false" \
% (wk, ii)
return fstr
def html2df(soup):
table = soup.find('table')
headers = [header.text.lower() for header in table.find_all('th')]
rows = []
for row in table.find_all('tr'):
rows.append([val.text.encode('utf8') for val in row.find_all('td')])
rows = [rr for rr in rows if len(rr) > 0]
df = pd.DataFrame.from_records(rows)
df.columns = headers
return df
def position_html_local(posn):
dflist = []
for ii in range(1, 17):
fname = '%s%s.html' % (posn, ii)
with open(fname) as f:
df = html2df(BeautifulSoup(f))
df['wk'] = ii
df.columns = header_clean(df.columns, posn)
dflist.append(df)
return pd.concat(dflist)
def position_html(posn):
dflist = []
for ii in range(1, 17):
fname = make_url(posn, ii)
df = html2df(BeautifulSoup(urlopen(fname)))
df['wk'] = ii
df.columns = header_clean(df.columns, posn)
dflist.append(df)
return pd.concat(dflist)
pos_header_suffixes = {
'qb': ['_pass', '_rush'],
'rb': ['_rush', '_recv'],
'wr': ['_recv'],
'te': ['_recv'],
}
exclude_cols = ['rk', 'player', 'team', 'pos', 'fantasy points',
'wk', 'fum', 'lost', 'qb rating']
def header_clean(header, posn):
res = []
if posn in pos_header_suffixes:
suffixes = pos_header_suffixes[posn]
seen_dict = {hh: 0 for hh in header}
for hh in header:
if not hh in exclude_cols:
hres = hh + suffixes[seen_dict[hh]]
seen_dict[hh] += 1
res.append(hres)
else:
res.append(hh)
else:
res = header
return res
if __name__ == '__main__':
data_all = {}
for pp in ['qb', 'wr', 'rb', 'te']:
data_all[pp] = position_html_local(pp)
data_all[pp].to_pickle('%s.pkl' % pp)
<|fim▁end|> | make_url |
<|file_name|>htmls2csvs.py<|end_file_name|><|fim▁begin|># pylint: disable = C0301
from bs4 import BeautifulSoup
from urllib2 import urlopen
import pandas as pd
pos_idx_map = {
'qb': 2,
'rb': 3,
'wr': 4,
'te': 5,
}
def make_url(pos, wk):
ii = pos_idx_map[pos]
fstr = "http://fantasydata.com/nfl-stats/nfl-fantasy-football-stats.aspx?fs=1&stype=0&sn=1&w=%s&s=&t=0&p=%s&st=FantasyPointsPPR&d=1&ls=&live=false" \
% (wk, ii)
return fstr
def <|fim_middle|>(soup):
table = soup.find('table')
headers = [header.text.lower() for header in table.find_all('th')]
rows = []
for row in table.find_all('tr'):
rows.append([val.text.encode('utf8') for val in row.find_all('td')])
rows = [rr for rr in rows if len(rr) > 0]
df = pd.DataFrame.from_records(rows)
df.columns = headers
return df
def position_html_local(posn):
dflist = []
for ii in range(1, 17):
fname = '%s%s.html' % (posn, ii)
with open(fname) as f:
df = html2df(BeautifulSoup(f))
df['wk'] = ii
df.columns = header_clean(df.columns, posn)
dflist.append(df)
return pd.concat(dflist)
def position_html(posn):
dflist = []
for ii in range(1, 17):
fname = make_url(posn, ii)
df = html2df(BeautifulSoup(urlopen(fname)))
df['wk'] = ii
df.columns = header_clean(df.columns, posn)
dflist.append(df)
return pd.concat(dflist)
pos_header_suffixes = {
'qb': ['_pass', '_rush'],
'rb': ['_rush', '_recv'],
'wr': ['_recv'],
'te': ['_recv'],
}
exclude_cols = ['rk', 'player', 'team', 'pos', 'fantasy points',
'wk', 'fum', 'lost', 'qb rating']
def header_clean(header, posn):
res = []
if posn in pos_header_suffixes:
suffixes = pos_header_suffixes[posn]
seen_dict = {hh: 0 for hh in header}
for hh in header:
if not hh in exclude_cols:
hres = hh + suffixes[seen_dict[hh]]
seen_dict[hh] += 1
res.append(hres)
else:
res.append(hh)
else:
res = header
return res
if __name__ == '__main__':
data_all = {}
for pp in ['qb', 'wr', 'rb', 'te']:
data_all[pp] = position_html_local(pp)
data_all[pp].to_pickle('%s.pkl' % pp)
<|fim▁end|> | html2df |
<|file_name|>htmls2csvs.py<|end_file_name|><|fim▁begin|># pylint: disable = C0301
from bs4 import BeautifulSoup
from urllib2 import urlopen
import pandas as pd
pos_idx_map = {
'qb': 2,
'rb': 3,
'wr': 4,
'te': 5,
}
def make_url(pos, wk):
ii = pos_idx_map[pos]
fstr = "http://fantasydata.com/nfl-stats/nfl-fantasy-football-stats.aspx?fs=1&stype=0&sn=1&w=%s&s=&t=0&p=%s&st=FantasyPointsPPR&d=1&ls=&live=false" \
% (wk, ii)
return fstr
def html2df(soup):
table = soup.find('table')
headers = [header.text.lower() for header in table.find_all('th')]
rows = []
for row in table.find_all('tr'):
rows.append([val.text.encode('utf8') for val in row.find_all('td')])
rows = [rr for rr in rows if len(rr) > 0]
df = pd.DataFrame.from_records(rows)
df.columns = headers
return df
def <|fim_middle|>(posn):
dflist = []
for ii in range(1, 17):
fname = '%s%s.html' % (posn, ii)
with open(fname) as f:
df = html2df(BeautifulSoup(f))
df['wk'] = ii
df.columns = header_clean(df.columns, posn)
dflist.append(df)
return pd.concat(dflist)
def position_html(posn):
dflist = []
for ii in range(1, 17):
fname = make_url(posn, ii)
df = html2df(BeautifulSoup(urlopen(fname)))
df['wk'] = ii
df.columns = header_clean(df.columns, posn)
dflist.append(df)
return pd.concat(dflist)
pos_header_suffixes = {
'qb': ['_pass', '_rush'],
'rb': ['_rush', '_recv'],
'wr': ['_recv'],
'te': ['_recv'],
}
exclude_cols = ['rk', 'player', 'team', 'pos', 'fantasy points',
'wk', 'fum', 'lost', 'qb rating']
def header_clean(header, posn):
res = []
if posn in pos_header_suffixes:
suffixes = pos_header_suffixes[posn]
seen_dict = {hh: 0 for hh in header}
for hh in header:
if not hh in exclude_cols:
hres = hh + suffixes[seen_dict[hh]]
seen_dict[hh] += 1
res.append(hres)
else:
res.append(hh)
else:
res = header
return res
if __name__ == '__main__':
data_all = {}
for pp in ['qb', 'wr', 'rb', 'te']:
data_all[pp] = position_html_local(pp)
data_all[pp].to_pickle('%s.pkl' % pp)
<|fim▁end|> | position_html_local |
<|file_name|>htmls2csvs.py<|end_file_name|><|fim▁begin|># pylint: disable = C0301
from bs4 import BeautifulSoup
from urllib2 import urlopen
import pandas as pd
pos_idx_map = {
'qb': 2,
'rb': 3,
'wr': 4,
'te': 5,
}
def make_url(pos, wk):
ii = pos_idx_map[pos]
fstr = "http://fantasydata.com/nfl-stats/nfl-fantasy-football-stats.aspx?fs=1&stype=0&sn=1&w=%s&s=&t=0&p=%s&st=FantasyPointsPPR&d=1&ls=&live=false" \
% (wk, ii)
return fstr
def html2df(soup):
table = soup.find('table')
headers = [header.text.lower() for header in table.find_all('th')]
rows = []
for row in table.find_all('tr'):
rows.append([val.text.encode('utf8') for val in row.find_all('td')])
rows = [rr for rr in rows if len(rr) > 0]
df = pd.DataFrame.from_records(rows)
df.columns = headers
return df
def position_html_local(posn):
dflist = []
for ii in range(1, 17):
fname = '%s%s.html' % (posn, ii)
with open(fname) as f:
df = html2df(BeautifulSoup(f))
df['wk'] = ii
df.columns = header_clean(df.columns, posn)
dflist.append(df)
return pd.concat(dflist)
def <|fim_middle|>(posn):
dflist = []
for ii in range(1, 17):
fname = make_url(posn, ii)
df = html2df(BeautifulSoup(urlopen(fname)))
df['wk'] = ii
df.columns = header_clean(df.columns, posn)
dflist.append(df)
return pd.concat(dflist)
pos_header_suffixes = {
'qb': ['_pass', '_rush'],
'rb': ['_rush', '_recv'],
'wr': ['_recv'],
'te': ['_recv'],
}
exclude_cols = ['rk', 'player', 'team', 'pos', 'fantasy points',
'wk', 'fum', 'lost', 'qb rating']
def header_clean(header, posn):
res = []
if posn in pos_header_suffixes:
suffixes = pos_header_suffixes[posn]
seen_dict = {hh: 0 for hh in header}
for hh in header:
if not hh in exclude_cols:
hres = hh + suffixes[seen_dict[hh]]
seen_dict[hh] += 1
res.append(hres)
else:
res.append(hh)
else:
res = header
return res
if __name__ == '__main__':
data_all = {}
for pp in ['qb', 'wr', 'rb', 'te']:
data_all[pp] = position_html_local(pp)
data_all[pp].to_pickle('%s.pkl' % pp)
<|fim▁end|> | position_html |
<|file_name|>htmls2csvs.py<|end_file_name|><|fim▁begin|># pylint: disable = C0301
from bs4 import BeautifulSoup
from urllib2 import urlopen
import pandas as pd
pos_idx_map = {
'qb': 2,
'rb': 3,
'wr': 4,
'te': 5,
}
def make_url(pos, wk):
ii = pos_idx_map[pos]
fstr = "http://fantasydata.com/nfl-stats/nfl-fantasy-football-stats.aspx?fs=1&stype=0&sn=1&w=%s&s=&t=0&p=%s&st=FantasyPointsPPR&d=1&ls=&live=false" \
% (wk, ii)
return fstr
def html2df(soup):
table = soup.find('table')
headers = [header.text.lower() for header in table.find_all('th')]
rows = []
for row in table.find_all('tr'):
rows.append([val.text.encode('utf8') for val in row.find_all('td')])
rows = [rr for rr in rows if len(rr) > 0]
df = pd.DataFrame.from_records(rows)
df.columns = headers
return df
def position_html_local(posn):
dflist = []
for ii in range(1, 17):
fname = '%s%s.html' % (posn, ii)
with open(fname) as f:
df = html2df(BeautifulSoup(f))
df['wk'] = ii
df.columns = header_clean(df.columns, posn)
dflist.append(df)
return pd.concat(dflist)
def position_html(posn):
dflist = []
for ii in range(1, 17):
fname = make_url(posn, ii)
df = html2df(BeautifulSoup(urlopen(fname)))
df['wk'] = ii
df.columns = header_clean(df.columns, posn)
dflist.append(df)
return pd.concat(dflist)
pos_header_suffixes = {
'qb': ['_pass', '_rush'],
'rb': ['_rush', '_recv'],
'wr': ['_recv'],
'te': ['_recv'],
}
exclude_cols = ['rk', 'player', 'team', 'pos', 'fantasy points',
'wk', 'fum', 'lost', 'qb rating']
def <|fim_middle|>(header, posn):
res = []
if posn in pos_header_suffixes:
suffixes = pos_header_suffixes[posn]
seen_dict = {hh: 0 for hh in header}
for hh in header:
if not hh in exclude_cols:
hres = hh + suffixes[seen_dict[hh]]
seen_dict[hh] += 1
res.append(hres)
else:
res.append(hh)
else:
res = header
return res
if __name__ == '__main__':
data_all = {}
for pp in ['qb', 'wr', 'rb', 'te']:
data_all[pp] = position_html_local(pp)
data_all[pp].to_pickle('%s.pkl' % pp)
<|fim▁end|> | header_clean |
<|file_name|>TutorialTVScenes.py<|end_file_name|><|fim▁begin|># Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.tutorial.TutorialTVScenes
from panda3d.core import Camera
from direct.task.Task import Task
from otp.avatar import Emote
from toontown.television.TVScenes import *
from toontown.television.TVEffects import *
from toontown.suit.Suit import Suit
from toontown.suit.BossCog import BossCog
from toontown.suit.SuitDNA import SuitDNA
from toontown.toon import NPCToons, TTEmote
import random
class CEOScene(ThreeDScene):
CameraPos = [(0, 203.5, 23.5, 0, 350, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'CEOScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BanquetInterior_1')
self.geom.reparentTo(self)
self.ceo = BossCog()
dna = SuitDNA()
dna.newBossCog('c')
self.ceo.setDNA(dna)
self.ceo.reparentTo(self)
self.ceo.setPosHpr(0, 236.5, 0, 180, 0, 0)
self.ceo.loop('Bb_neutral')
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.ceo:
self.ceo.delete()
self.ceo = None
ThreeDScene.delete(self)
return
class HeadHunterScene(ThreeDScene):
CameraPos = [(-22, -12.5, 7, 92, -6, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'HeadHunterScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BossbotEntranceRoom')
self.geom.reparentTo(self)
self.cog = Suit()
dna = SuitDNA()
dna.newSuit('hh')
self.cog.setDNA(dna)
self.cog.reparentTo(self)
self.cog.setPosHpr(-32.5, -12.5, 0.02, 270, 0, 0)
self.cog.nametag3d.removeNode()
self.cog.nametag.destroy()
self.cog.loop('neutral')
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.cog:
self.cog.delete()
self.cog = None
ThreeDScene.delete(self)
return
class ScientistScene(ThreeDScene):
CameraPos = [(-47.5, 0.5, 3.415, 90, 0, 0)]
ToonPos = {2018: (-59, -1.5, 0.02, 270, 0, 0),
2019: (-59, 0.5, 0.02, 270, 0, 0),
2020: (-59, 2.5, 0.02, 270, 0, 0)}
RandomEmotes = ['wave',
'angry',
'applause',
'cringe',
'confused',
'slip-forward',
'slip-backward',
'resistance-salute',
'surprise',
'cry',
'furious',
'laugh',
'idea',
'taunt',
'rage']
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'ScientistScene', effects)
self.geom = loader.loadModel('phase_3.5/models/modules/tt_m_ara_int_toonhall')
self.geom.reparentTo(self)
self.taskStarted = False
self.npcs = []
for id, posHpr in self.ToonPos.iteritems():
npc = NPCToons.createLocalNPC(id)
npc.reparentTo(self.geom)
npc.setPosHpr(*posHpr)
npc.nametag3d.removeNode()
npc.nametag.destroy()
self.npcs.append(npc)
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
npc.delete()
self.npcs = []
self.taskStarted = False
ThreeDScene.delete(self)
return
def startTask(self):
if self.taskStarted:
return
for i, npc in enumerate(self.npcs):
taskMgr.doMethodLater(0.25 * i, lambda task, npc = npc: self.doRandomEmote(npc, task), npc.uniqueName('randomEmote'))
self.taskStarted = True
<|fim▁hole|> taskMgr.remove(npc.uniqueName('randomEmote'))
self.taskStarted = False
def doRandomEmote(self, npc, task):
Emote.globalEmote.doEmote(npc, TTEmote.Emotes.index(random.choice(self.RandomEmotes)), 0)
task.delayTime = npc.emoteTrack.getDuration() + 1.0
return task.again<|fim▁end|> | def stopTask(self):
if not self.taskStarted:
return
for npc in self.npcs:
|
<|file_name|>TutorialTVScenes.py<|end_file_name|><|fim▁begin|># Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.tutorial.TutorialTVScenes
from panda3d.core import Camera
from direct.task.Task import Task
from otp.avatar import Emote
from toontown.television.TVScenes import *
from toontown.television.TVEffects import *
from toontown.suit.Suit import Suit
from toontown.suit.BossCog import BossCog
from toontown.suit.SuitDNA import SuitDNA
from toontown.toon import NPCToons, TTEmote
import random
class CEOScene(ThreeDScene):
<|fim_middle|>
class HeadHunterScene(ThreeDScene):
CameraPos = [(-22, -12.5, 7, 92, -6, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'HeadHunterScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BossbotEntranceRoom')
self.geom.reparentTo(self)
self.cog = Suit()
dna = SuitDNA()
dna.newSuit('hh')
self.cog.setDNA(dna)
self.cog.reparentTo(self)
self.cog.setPosHpr(-32.5, -12.5, 0.02, 270, 0, 0)
self.cog.nametag3d.removeNode()
self.cog.nametag.destroy()
self.cog.loop('neutral')
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.cog:
self.cog.delete()
self.cog = None
ThreeDScene.delete(self)
return
class ScientistScene(ThreeDScene):
CameraPos = [(-47.5, 0.5, 3.415, 90, 0, 0)]
ToonPos = {2018: (-59, -1.5, 0.02, 270, 0, 0),
2019: (-59, 0.5, 0.02, 270, 0, 0),
2020: (-59, 2.5, 0.02, 270, 0, 0)}
RandomEmotes = ['wave',
'angry',
'applause',
'cringe',
'confused',
'slip-forward',
'slip-backward',
'resistance-salute',
'surprise',
'cry',
'furious',
'laugh',
'idea',
'taunt',
'rage']
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'ScientistScene', effects)
self.geom = loader.loadModel('phase_3.5/models/modules/tt_m_ara_int_toonhall')
self.geom.reparentTo(self)
self.taskStarted = False
self.npcs = []
for id, posHpr in self.ToonPos.iteritems():
npc = NPCToons.createLocalNPC(id)
npc.reparentTo(self.geom)
npc.setPosHpr(*posHpr)
npc.nametag3d.removeNode()
npc.nametag.destroy()
self.npcs.append(npc)
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
npc.delete()
self.npcs = []
self.taskStarted = False
ThreeDScene.delete(self)
return
def startTask(self):
if self.taskStarted:
return
for i, npc in enumerate(self.npcs):
taskMgr.doMethodLater(0.25 * i, lambda task, npc = npc: self.doRandomEmote(npc, task), npc.uniqueName('randomEmote'))
self.taskStarted = True
def stopTask(self):
if not self.taskStarted:
return
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
self.taskStarted = False
def doRandomEmote(self, npc, task):
Emote.globalEmote.doEmote(npc, TTEmote.Emotes.index(random.choice(self.RandomEmotes)), 0)
task.delayTime = npc.emoteTrack.getDuration() + 1.0
return task.again<|fim▁end|> | CameraPos = [(0, 203.5, 23.5, 0, 350, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'CEOScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BanquetInterior_1')
self.geom.reparentTo(self)
self.ceo = BossCog()
dna = SuitDNA()
dna.newBossCog('c')
self.ceo.setDNA(dna)
self.ceo.reparentTo(self)
self.ceo.setPosHpr(0, 236.5, 0, 180, 0, 0)
self.ceo.loop('Bb_neutral')
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.ceo:
self.ceo.delete()
self.ceo = None
ThreeDScene.delete(self)
return |
<|file_name|>TutorialTVScenes.py<|end_file_name|><|fim▁begin|># Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.tutorial.TutorialTVScenes
from panda3d.core import Camera
from direct.task.Task import Task
from otp.avatar import Emote
from toontown.television.TVScenes import *
from toontown.television.TVEffects import *
from toontown.suit.Suit import Suit
from toontown.suit.BossCog import BossCog
from toontown.suit.SuitDNA import SuitDNA
from toontown.toon import NPCToons, TTEmote
import random
class CEOScene(ThreeDScene):
CameraPos = [(0, 203.5, 23.5, 0, 350, 0)]
def __init__(self, effects = []):
<|fim_middle|>
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.ceo:
self.ceo.delete()
self.ceo = None
ThreeDScene.delete(self)
return
class HeadHunterScene(ThreeDScene):
CameraPos = [(-22, -12.5, 7, 92, -6, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'HeadHunterScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BossbotEntranceRoom')
self.geom.reparentTo(self)
self.cog = Suit()
dna = SuitDNA()
dna.newSuit('hh')
self.cog.setDNA(dna)
self.cog.reparentTo(self)
self.cog.setPosHpr(-32.5, -12.5, 0.02, 270, 0, 0)
self.cog.nametag3d.removeNode()
self.cog.nametag.destroy()
self.cog.loop('neutral')
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.cog:
self.cog.delete()
self.cog = None
ThreeDScene.delete(self)
return
class ScientistScene(ThreeDScene):
CameraPos = [(-47.5, 0.5, 3.415, 90, 0, 0)]
ToonPos = {2018: (-59, -1.5, 0.02, 270, 0, 0),
2019: (-59, 0.5, 0.02, 270, 0, 0),
2020: (-59, 2.5, 0.02, 270, 0, 0)}
RandomEmotes = ['wave',
'angry',
'applause',
'cringe',
'confused',
'slip-forward',
'slip-backward',
'resistance-salute',
'surprise',
'cry',
'furious',
'laugh',
'idea',
'taunt',
'rage']
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'ScientistScene', effects)
self.geom = loader.loadModel('phase_3.5/models/modules/tt_m_ara_int_toonhall')
self.geom.reparentTo(self)
self.taskStarted = False
self.npcs = []
for id, posHpr in self.ToonPos.iteritems():
npc = NPCToons.createLocalNPC(id)
npc.reparentTo(self.geom)
npc.setPosHpr(*posHpr)
npc.nametag3d.removeNode()
npc.nametag.destroy()
self.npcs.append(npc)
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
npc.delete()
self.npcs = []
self.taskStarted = False
ThreeDScene.delete(self)
return
def startTask(self):
if self.taskStarted:
return
for i, npc in enumerate(self.npcs):
taskMgr.doMethodLater(0.25 * i, lambda task, npc = npc: self.doRandomEmote(npc, task), npc.uniqueName('randomEmote'))
self.taskStarted = True
def stopTask(self):
if not self.taskStarted:
return
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
self.taskStarted = False
def doRandomEmote(self, npc, task):
Emote.globalEmote.doEmote(npc, TTEmote.Emotes.index(random.choice(self.RandomEmotes)), 0)
task.delayTime = npc.emoteTrack.getDuration() + 1.0
return task.again<|fim▁end|> | ThreeDScene.__init__(self, 'CEOScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BanquetInterior_1')
self.geom.reparentTo(self)
self.ceo = BossCog()
dna = SuitDNA()
dna.newBossCog('c')
self.ceo.setDNA(dna)
self.ceo.reparentTo(self)
self.ceo.setPosHpr(0, 236.5, 0, 180, 0, 0)
self.ceo.loop('Bb_neutral') |
<|file_name|>TutorialTVScenes.py<|end_file_name|><|fim▁begin|># Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.tutorial.TutorialTVScenes
from panda3d.core import Camera
from direct.task.Task import Task
from otp.avatar import Emote
from toontown.television.TVScenes import *
from toontown.television.TVEffects import *
from toontown.suit.Suit import Suit
from toontown.suit.BossCog import BossCog
from toontown.suit.SuitDNA import SuitDNA
from toontown.toon import NPCToons, TTEmote
import random
class CEOScene(ThreeDScene):
CameraPos = [(0, 203.5, 23.5, 0, 350, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'CEOScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BanquetInterior_1')
self.geom.reparentTo(self)
self.ceo = BossCog()
dna = SuitDNA()
dna.newBossCog('c')
self.ceo.setDNA(dna)
self.ceo.reparentTo(self)
self.ceo.setPosHpr(0, 236.5, 0, 180, 0, 0)
self.ceo.loop('Bb_neutral')
def delete(self):
<|fim_middle|>
class HeadHunterScene(ThreeDScene):
CameraPos = [(-22, -12.5, 7, 92, -6, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'HeadHunterScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BossbotEntranceRoom')
self.geom.reparentTo(self)
self.cog = Suit()
dna = SuitDNA()
dna.newSuit('hh')
self.cog.setDNA(dna)
self.cog.reparentTo(self)
self.cog.setPosHpr(-32.5, -12.5, 0.02, 270, 0, 0)
self.cog.nametag3d.removeNode()
self.cog.nametag.destroy()
self.cog.loop('neutral')
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.cog:
self.cog.delete()
self.cog = None
ThreeDScene.delete(self)
return
class ScientistScene(ThreeDScene):
CameraPos = [(-47.5, 0.5, 3.415, 90, 0, 0)]
ToonPos = {2018: (-59, -1.5, 0.02, 270, 0, 0),
2019: (-59, 0.5, 0.02, 270, 0, 0),
2020: (-59, 2.5, 0.02, 270, 0, 0)}
RandomEmotes = ['wave',
'angry',
'applause',
'cringe',
'confused',
'slip-forward',
'slip-backward',
'resistance-salute',
'surprise',
'cry',
'furious',
'laugh',
'idea',
'taunt',
'rage']
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'ScientistScene', effects)
self.geom = loader.loadModel('phase_3.5/models/modules/tt_m_ara_int_toonhall')
self.geom.reparentTo(self)
self.taskStarted = False
self.npcs = []
for id, posHpr in self.ToonPos.iteritems():
npc = NPCToons.createLocalNPC(id)
npc.reparentTo(self.geom)
npc.setPosHpr(*posHpr)
npc.nametag3d.removeNode()
npc.nametag.destroy()
self.npcs.append(npc)
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
npc.delete()
self.npcs = []
self.taskStarted = False
ThreeDScene.delete(self)
return
def startTask(self):
if self.taskStarted:
return
for i, npc in enumerate(self.npcs):
taskMgr.doMethodLater(0.25 * i, lambda task, npc = npc: self.doRandomEmote(npc, task), npc.uniqueName('randomEmote'))
self.taskStarted = True
def stopTask(self):
if not self.taskStarted:
return
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
self.taskStarted = False
def doRandomEmote(self, npc, task):
Emote.globalEmote.doEmote(npc, TTEmote.Emotes.index(random.choice(self.RandomEmotes)), 0)
task.delayTime = npc.emoteTrack.getDuration() + 1.0
return task.again<|fim▁end|> | if self.geom:
self.geom.removeNode()
self.geom = None
if self.ceo:
self.ceo.delete()
self.ceo = None
ThreeDScene.delete(self)
return |
<|file_name|>TutorialTVScenes.py<|end_file_name|><|fim▁begin|># Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.tutorial.TutorialTVScenes
from panda3d.core import Camera
from direct.task.Task import Task
from otp.avatar import Emote
from toontown.television.TVScenes import *
from toontown.television.TVEffects import *
from toontown.suit.Suit import Suit
from toontown.suit.BossCog import BossCog
from toontown.suit.SuitDNA import SuitDNA
from toontown.toon import NPCToons, TTEmote
import random
class CEOScene(ThreeDScene):
CameraPos = [(0, 203.5, 23.5, 0, 350, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'CEOScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BanquetInterior_1')
self.geom.reparentTo(self)
self.ceo = BossCog()
dna = SuitDNA()
dna.newBossCog('c')
self.ceo.setDNA(dna)
self.ceo.reparentTo(self)
self.ceo.setPosHpr(0, 236.5, 0, 180, 0, 0)
self.ceo.loop('Bb_neutral')
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.ceo:
self.ceo.delete()
self.ceo = None
ThreeDScene.delete(self)
return
class HeadHunterScene(ThreeDScene):
<|fim_middle|>
class ScientistScene(ThreeDScene):
CameraPos = [(-47.5, 0.5, 3.415, 90, 0, 0)]
ToonPos = {2018: (-59, -1.5, 0.02, 270, 0, 0),
2019: (-59, 0.5, 0.02, 270, 0, 0),
2020: (-59, 2.5, 0.02, 270, 0, 0)}
RandomEmotes = ['wave',
'angry',
'applause',
'cringe',
'confused',
'slip-forward',
'slip-backward',
'resistance-salute',
'surprise',
'cry',
'furious',
'laugh',
'idea',
'taunt',
'rage']
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'ScientistScene', effects)
self.geom = loader.loadModel('phase_3.5/models/modules/tt_m_ara_int_toonhall')
self.geom.reparentTo(self)
self.taskStarted = False
self.npcs = []
for id, posHpr in self.ToonPos.iteritems():
npc = NPCToons.createLocalNPC(id)
npc.reparentTo(self.geom)
npc.setPosHpr(*posHpr)
npc.nametag3d.removeNode()
npc.nametag.destroy()
self.npcs.append(npc)
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
npc.delete()
self.npcs = []
self.taskStarted = False
ThreeDScene.delete(self)
return
def startTask(self):
if self.taskStarted:
return
for i, npc in enumerate(self.npcs):
taskMgr.doMethodLater(0.25 * i, lambda task, npc = npc: self.doRandomEmote(npc, task), npc.uniqueName('randomEmote'))
self.taskStarted = True
def stopTask(self):
if not self.taskStarted:
return
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
self.taskStarted = False
def doRandomEmote(self, npc, task):
Emote.globalEmote.doEmote(npc, TTEmote.Emotes.index(random.choice(self.RandomEmotes)), 0)
task.delayTime = npc.emoteTrack.getDuration() + 1.0
return task.again<|fim▁end|> | CameraPos = [(-22, -12.5, 7, 92, -6, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'HeadHunterScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BossbotEntranceRoom')
self.geom.reparentTo(self)
self.cog = Suit()
dna = SuitDNA()
dna.newSuit('hh')
self.cog.setDNA(dna)
self.cog.reparentTo(self)
self.cog.setPosHpr(-32.5, -12.5, 0.02, 270, 0, 0)
self.cog.nametag3d.removeNode()
self.cog.nametag.destroy()
self.cog.loop('neutral')
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.cog:
self.cog.delete()
self.cog = None
ThreeDScene.delete(self)
return |
<|file_name|>TutorialTVScenes.py<|end_file_name|><|fim▁begin|># Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.tutorial.TutorialTVScenes
from panda3d.core import Camera
from direct.task.Task import Task
from otp.avatar import Emote
from toontown.television.TVScenes import *
from toontown.television.TVEffects import *
from toontown.suit.Suit import Suit
from toontown.suit.BossCog import BossCog
from toontown.suit.SuitDNA import SuitDNA
from toontown.toon import NPCToons, TTEmote
import random
class CEOScene(ThreeDScene):
CameraPos = [(0, 203.5, 23.5, 0, 350, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'CEOScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BanquetInterior_1')
self.geom.reparentTo(self)
self.ceo = BossCog()
dna = SuitDNA()
dna.newBossCog('c')
self.ceo.setDNA(dna)
self.ceo.reparentTo(self)
self.ceo.setPosHpr(0, 236.5, 0, 180, 0, 0)
self.ceo.loop('Bb_neutral')
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.ceo:
self.ceo.delete()
self.ceo = None
ThreeDScene.delete(self)
return
class HeadHunterScene(ThreeDScene):
CameraPos = [(-22, -12.5, 7, 92, -6, 0)]
def __init__(self, effects = []):
<|fim_middle|>
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.cog:
self.cog.delete()
self.cog = None
ThreeDScene.delete(self)
return
class ScientistScene(ThreeDScene):
CameraPos = [(-47.5, 0.5, 3.415, 90, 0, 0)]
ToonPos = {2018: (-59, -1.5, 0.02, 270, 0, 0),
2019: (-59, 0.5, 0.02, 270, 0, 0),
2020: (-59, 2.5, 0.02, 270, 0, 0)}
RandomEmotes = ['wave',
'angry',
'applause',
'cringe',
'confused',
'slip-forward',
'slip-backward',
'resistance-salute',
'surprise',
'cry',
'furious',
'laugh',
'idea',
'taunt',
'rage']
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'ScientistScene', effects)
self.geom = loader.loadModel('phase_3.5/models/modules/tt_m_ara_int_toonhall')
self.geom.reparentTo(self)
self.taskStarted = False
self.npcs = []
for id, posHpr in self.ToonPos.iteritems():
npc = NPCToons.createLocalNPC(id)
npc.reparentTo(self.geom)
npc.setPosHpr(*posHpr)
npc.nametag3d.removeNode()
npc.nametag.destroy()
self.npcs.append(npc)
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
npc.delete()
self.npcs = []
self.taskStarted = False
ThreeDScene.delete(self)
return
def startTask(self):
if self.taskStarted:
return
for i, npc in enumerate(self.npcs):
taskMgr.doMethodLater(0.25 * i, lambda task, npc = npc: self.doRandomEmote(npc, task), npc.uniqueName('randomEmote'))
self.taskStarted = True
def stopTask(self):
if not self.taskStarted:
return
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
self.taskStarted = False
def doRandomEmote(self, npc, task):
Emote.globalEmote.doEmote(npc, TTEmote.Emotes.index(random.choice(self.RandomEmotes)), 0)
task.delayTime = npc.emoteTrack.getDuration() + 1.0
return task.again<|fim▁end|> | ThreeDScene.__init__(self, 'HeadHunterScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BossbotEntranceRoom')
self.geom.reparentTo(self)
self.cog = Suit()
dna = SuitDNA()
dna.newSuit('hh')
self.cog.setDNA(dna)
self.cog.reparentTo(self)
self.cog.setPosHpr(-32.5, -12.5, 0.02, 270, 0, 0)
self.cog.nametag3d.removeNode()
self.cog.nametag.destroy()
self.cog.loop('neutral') |
<|file_name|>TutorialTVScenes.py<|end_file_name|><|fim▁begin|># Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.tutorial.TutorialTVScenes
from panda3d.core import Camera
from direct.task.Task import Task
from otp.avatar import Emote
from toontown.television.TVScenes import *
from toontown.television.TVEffects import *
from toontown.suit.Suit import Suit
from toontown.suit.BossCog import BossCog
from toontown.suit.SuitDNA import SuitDNA
from toontown.toon import NPCToons, TTEmote
import random
class CEOScene(ThreeDScene):
CameraPos = [(0, 203.5, 23.5, 0, 350, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'CEOScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BanquetInterior_1')
self.geom.reparentTo(self)
self.ceo = BossCog()
dna = SuitDNA()
dna.newBossCog('c')
self.ceo.setDNA(dna)
self.ceo.reparentTo(self)
self.ceo.setPosHpr(0, 236.5, 0, 180, 0, 0)
self.ceo.loop('Bb_neutral')
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.ceo:
self.ceo.delete()
self.ceo = None
ThreeDScene.delete(self)
return
class HeadHunterScene(ThreeDScene):
CameraPos = [(-22, -12.5, 7, 92, -6, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'HeadHunterScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BossbotEntranceRoom')
self.geom.reparentTo(self)
self.cog = Suit()
dna = SuitDNA()
dna.newSuit('hh')
self.cog.setDNA(dna)
self.cog.reparentTo(self)
self.cog.setPosHpr(-32.5, -12.5, 0.02, 270, 0, 0)
self.cog.nametag3d.removeNode()
self.cog.nametag.destroy()
self.cog.loop('neutral')
def delete(self):
<|fim_middle|>
class ScientistScene(ThreeDScene):
CameraPos = [(-47.5, 0.5, 3.415, 90, 0, 0)]
ToonPos = {2018: (-59, -1.5, 0.02, 270, 0, 0),
2019: (-59, 0.5, 0.02, 270, 0, 0),
2020: (-59, 2.5, 0.02, 270, 0, 0)}
RandomEmotes = ['wave',
'angry',
'applause',
'cringe',
'confused',
'slip-forward',
'slip-backward',
'resistance-salute',
'surprise',
'cry',
'furious',
'laugh',
'idea',
'taunt',
'rage']
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'ScientistScene', effects)
self.geom = loader.loadModel('phase_3.5/models/modules/tt_m_ara_int_toonhall')
self.geom.reparentTo(self)
self.taskStarted = False
self.npcs = []
for id, posHpr in self.ToonPos.iteritems():
npc = NPCToons.createLocalNPC(id)
npc.reparentTo(self.geom)
npc.setPosHpr(*posHpr)
npc.nametag3d.removeNode()
npc.nametag.destroy()
self.npcs.append(npc)
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
npc.delete()
self.npcs = []
self.taskStarted = False
ThreeDScene.delete(self)
return
def startTask(self):
if self.taskStarted:
return
for i, npc in enumerate(self.npcs):
taskMgr.doMethodLater(0.25 * i, lambda task, npc = npc: self.doRandomEmote(npc, task), npc.uniqueName('randomEmote'))
self.taskStarted = True
def stopTask(self):
if not self.taskStarted:
return
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
self.taskStarted = False
def doRandomEmote(self, npc, task):
Emote.globalEmote.doEmote(npc, TTEmote.Emotes.index(random.choice(self.RandomEmotes)), 0)
task.delayTime = npc.emoteTrack.getDuration() + 1.0
return task.again<|fim▁end|> | if self.geom:
self.geom.removeNode()
self.geom = None
if self.cog:
self.cog.delete()
self.cog = None
ThreeDScene.delete(self)
return |
<|file_name|>TutorialTVScenes.py<|end_file_name|><|fim▁begin|># Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.tutorial.TutorialTVScenes
from panda3d.core import Camera
from direct.task.Task import Task
from otp.avatar import Emote
from toontown.television.TVScenes import *
from toontown.television.TVEffects import *
from toontown.suit.Suit import Suit
from toontown.suit.BossCog import BossCog
from toontown.suit.SuitDNA import SuitDNA
from toontown.toon import NPCToons, TTEmote
import random
class CEOScene(ThreeDScene):
CameraPos = [(0, 203.5, 23.5, 0, 350, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'CEOScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BanquetInterior_1')
self.geom.reparentTo(self)
self.ceo = BossCog()
dna = SuitDNA()
dna.newBossCog('c')
self.ceo.setDNA(dna)
self.ceo.reparentTo(self)
self.ceo.setPosHpr(0, 236.5, 0, 180, 0, 0)
self.ceo.loop('Bb_neutral')
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.ceo:
self.ceo.delete()
self.ceo = None
ThreeDScene.delete(self)
return
class HeadHunterScene(ThreeDScene):
CameraPos = [(-22, -12.5, 7, 92, -6, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'HeadHunterScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BossbotEntranceRoom')
self.geom.reparentTo(self)
self.cog = Suit()
dna = SuitDNA()
dna.newSuit('hh')
self.cog.setDNA(dna)
self.cog.reparentTo(self)
self.cog.setPosHpr(-32.5, -12.5, 0.02, 270, 0, 0)
self.cog.nametag3d.removeNode()
self.cog.nametag.destroy()
self.cog.loop('neutral')
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.cog:
self.cog.delete()
self.cog = None
ThreeDScene.delete(self)
return
class ScientistScene(ThreeDScene):
<|fim_middle|>
<|fim▁end|> | CameraPos = [(-47.5, 0.5, 3.415, 90, 0, 0)]
ToonPos = {2018: (-59, -1.5, 0.02, 270, 0, 0),
2019: (-59, 0.5, 0.02, 270, 0, 0),
2020: (-59, 2.5, 0.02, 270, 0, 0)}
RandomEmotes = ['wave',
'angry',
'applause',
'cringe',
'confused',
'slip-forward',
'slip-backward',
'resistance-salute',
'surprise',
'cry',
'furious',
'laugh',
'idea',
'taunt',
'rage']
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'ScientistScene', effects)
self.geom = loader.loadModel('phase_3.5/models/modules/tt_m_ara_int_toonhall')
self.geom.reparentTo(self)
self.taskStarted = False
self.npcs = []
for id, posHpr in self.ToonPos.iteritems():
npc = NPCToons.createLocalNPC(id)
npc.reparentTo(self.geom)
npc.setPosHpr(*posHpr)
npc.nametag3d.removeNode()
npc.nametag.destroy()
self.npcs.append(npc)
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
npc.delete()
self.npcs = []
self.taskStarted = False
ThreeDScene.delete(self)
return
def startTask(self):
if self.taskStarted:
return
for i, npc in enumerate(self.npcs):
taskMgr.doMethodLater(0.25 * i, lambda task, npc = npc: self.doRandomEmote(npc, task), npc.uniqueName('randomEmote'))
self.taskStarted = True
def stopTask(self):
if not self.taskStarted:
return
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
self.taskStarted = False
def doRandomEmote(self, npc, task):
Emote.globalEmote.doEmote(npc, TTEmote.Emotes.index(random.choice(self.RandomEmotes)), 0)
task.delayTime = npc.emoteTrack.getDuration() + 1.0
return task.again |
<|file_name|>TutorialTVScenes.py<|end_file_name|><|fim▁begin|># Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.tutorial.TutorialTVScenes
from panda3d.core import Camera
from direct.task.Task import Task
from otp.avatar import Emote
from toontown.television.TVScenes import *
from toontown.television.TVEffects import *
from toontown.suit.Suit import Suit
from toontown.suit.BossCog import BossCog
from toontown.suit.SuitDNA import SuitDNA
from toontown.toon import NPCToons, TTEmote
import random
class CEOScene(ThreeDScene):
CameraPos = [(0, 203.5, 23.5, 0, 350, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'CEOScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BanquetInterior_1')
self.geom.reparentTo(self)
self.ceo = BossCog()
dna = SuitDNA()
dna.newBossCog('c')
self.ceo.setDNA(dna)
self.ceo.reparentTo(self)
self.ceo.setPosHpr(0, 236.5, 0, 180, 0, 0)
self.ceo.loop('Bb_neutral')
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.ceo:
self.ceo.delete()
self.ceo = None
ThreeDScene.delete(self)
return
class HeadHunterScene(ThreeDScene):
CameraPos = [(-22, -12.5, 7, 92, -6, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'HeadHunterScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BossbotEntranceRoom')
self.geom.reparentTo(self)
self.cog = Suit()
dna = SuitDNA()
dna.newSuit('hh')
self.cog.setDNA(dna)
self.cog.reparentTo(self)
self.cog.setPosHpr(-32.5, -12.5, 0.02, 270, 0, 0)
self.cog.nametag3d.removeNode()
self.cog.nametag.destroy()
self.cog.loop('neutral')
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.cog:
self.cog.delete()
self.cog = None
ThreeDScene.delete(self)
return
class ScientistScene(ThreeDScene):
CameraPos = [(-47.5, 0.5, 3.415, 90, 0, 0)]
ToonPos = {2018: (-59, -1.5, 0.02, 270, 0, 0),
2019: (-59, 0.5, 0.02, 270, 0, 0),
2020: (-59, 2.5, 0.02, 270, 0, 0)}
RandomEmotes = ['wave',
'angry',
'applause',
'cringe',
'confused',
'slip-forward',
'slip-backward',
'resistance-salute',
'surprise',
'cry',
'furious',
'laugh',
'idea',
'taunt',
'rage']
def __init__(self, effects = []):
<|fim_middle|>
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
npc.delete()
self.npcs = []
self.taskStarted = False
ThreeDScene.delete(self)
return
def startTask(self):
if self.taskStarted:
return
for i, npc in enumerate(self.npcs):
taskMgr.doMethodLater(0.25 * i, lambda task, npc = npc: self.doRandomEmote(npc, task), npc.uniqueName('randomEmote'))
self.taskStarted = True
def stopTask(self):
if not self.taskStarted:
return
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
self.taskStarted = False
def doRandomEmote(self, npc, task):
Emote.globalEmote.doEmote(npc, TTEmote.Emotes.index(random.choice(self.RandomEmotes)), 0)
task.delayTime = npc.emoteTrack.getDuration() + 1.0
return task.again<|fim▁end|> | ThreeDScene.__init__(self, 'ScientistScene', effects)
self.geom = loader.loadModel('phase_3.5/models/modules/tt_m_ara_int_toonhall')
self.geom.reparentTo(self)
self.taskStarted = False
self.npcs = []
for id, posHpr in self.ToonPos.iteritems():
npc = NPCToons.createLocalNPC(id)
npc.reparentTo(self.geom)
npc.setPosHpr(*posHpr)
npc.nametag3d.removeNode()
npc.nametag.destroy()
self.npcs.append(npc) |
<|file_name|>TutorialTVScenes.py<|end_file_name|><|fim▁begin|># Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.tutorial.TutorialTVScenes
from panda3d.core import Camera
from direct.task.Task import Task
from otp.avatar import Emote
from toontown.television.TVScenes import *
from toontown.television.TVEffects import *
from toontown.suit.Suit import Suit
from toontown.suit.BossCog import BossCog
from toontown.suit.SuitDNA import SuitDNA
from toontown.toon import NPCToons, TTEmote
import random
class CEOScene(ThreeDScene):
CameraPos = [(0, 203.5, 23.5, 0, 350, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'CEOScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BanquetInterior_1')
self.geom.reparentTo(self)
self.ceo = BossCog()
dna = SuitDNA()
dna.newBossCog('c')
self.ceo.setDNA(dna)
self.ceo.reparentTo(self)
self.ceo.setPosHpr(0, 236.5, 0, 180, 0, 0)
self.ceo.loop('Bb_neutral')
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.ceo:
self.ceo.delete()
self.ceo = None
ThreeDScene.delete(self)
return
class HeadHunterScene(ThreeDScene):
CameraPos = [(-22, -12.5, 7, 92, -6, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'HeadHunterScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BossbotEntranceRoom')
self.geom.reparentTo(self)
self.cog = Suit()
dna = SuitDNA()
dna.newSuit('hh')
self.cog.setDNA(dna)
self.cog.reparentTo(self)
self.cog.setPosHpr(-32.5, -12.5, 0.02, 270, 0, 0)
self.cog.nametag3d.removeNode()
self.cog.nametag.destroy()
self.cog.loop('neutral')
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.cog:
self.cog.delete()
self.cog = None
ThreeDScene.delete(self)
return
class ScientistScene(ThreeDScene):
CameraPos = [(-47.5, 0.5, 3.415, 90, 0, 0)]
ToonPos = {2018: (-59, -1.5, 0.02, 270, 0, 0),
2019: (-59, 0.5, 0.02, 270, 0, 0),
2020: (-59, 2.5, 0.02, 270, 0, 0)}
RandomEmotes = ['wave',
'angry',
'applause',
'cringe',
'confused',
'slip-forward',
'slip-backward',
'resistance-salute',
'surprise',
'cry',
'furious',
'laugh',
'idea',
'taunt',
'rage']
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'ScientistScene', effects)
self.geom = loader.loadModel('phase_3.5/models/modules/tt_m_ara_int_toonhall')
self.geom.reparentTo(self)
self.taskStarted = False
self.npcs = []
for id, posHpr in self.ToonPos.iteritems():
npc = NPCToons.createLocalNPC(id)
npc.reparentTo(self.geom)
npc.setPosHpr(*posHpr)
npc.nametag3d.removeNode()
npc.nametag.destroy()
self.npcs.append(npc)
def delete(self):
<|fim_middle|>
def startTask(self):
if self.taskStarted:
return
for i, npc in enumerate(self.npcs):
taskMgr.doMethodLater(0.25 * i, lambda task, npc = npc: self.doRandomEmote(npc, task), npc.uniqueName('randomEmote'))
self.taskStarted = True
def stopTask(self):
if not self.taskStarted:
return
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
self.taskStarted = False
def doRandomEmote(self, npc, task):
Emote.globalEmote.doEmote(npc, TTEmote.Emotes.index(random.choice(self.RandomEmotes)), 0)
task.delayTime = npc.emoteTrack.getDuration() + 1.0
return task.again<|fim▁end|> | if self.geom:
self.geom.removeNode()
self.geom = None
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
npc.delete()
self.npcs = []
self.taskStarted = False
ThreeDScene.delete(self)
return |
<|file_name|>TutorialTVScenes.py<|end_file_name|><|fim▁begin|># Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.tutorial.TutorialTVScenes
from panda3d.core import Camera
from direct.task.Task import Task
from otp.avatar import Emote
from toontown.television.TVScenes import *
from toontown.television.TVEffects import *
from toontown.suit.Suit import Suit
from toontown.suit.BossCog import BossCog
from toontown.suit.SuitDNA import SuitDNA
from toontown.toon import NPCToons, TTEmote
import random
class CEOScene(ThreeDScene):
CameraPos = [(0, 203.5, 23.5, 0, 350, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'CEOScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BanquetInterior_1')
self.geom.reparentTo(self)
self.ceo = BossCog()
dna = SuitDNA()
dna.newBossCog('c')
self.ceo.setDNA(dna)
self.ceo.reparentTo(self)
self.ceo.setPosHpr(0, 236.5, 0, 180, 0, 0)
self.ceo.loop('Bb_neutral')
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.ceo:
self.ceo.delete()
self.ceo = None
ThreeDScene.delete(self)
return
class HeadHunterScene(ThreeDScene):
CameraPos = [(-22, -12.5, 7, 92, -6, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'HeadHunterScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BossbotEntranceRoom')
self.geom.reparentTo(self)
self.cog = Suit()
dna = SuitDNA()
dna.newSuit('hh')
self.cog.setDNA(dna)
self.cog.reparentTo(self)
self.cog.setPosHpr(-32.5, -12.5, 0.02, 270, 0, 0)
self.cog.nametag3d.removeNode()
self.cog.nametag.destroy()
self.cog.loop('neutral')
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.cog:
self.cog.delete()
self.cog = None
ThreeDScene.delete(self)
return
class ScientistScene(ThreeDScene):
CameraPos = [(-47.5, 0.5, 3.415, 90, 0, 0)]
ToonPos = {2018: (-59, -1.5, 0.02, 270, 0, 0),
2019: (-59, 0.5, 0.02, 270, 0, 0),
2020: (-59, 2.5, 0.02, 270, 0, 0)}
RandomEmotes = ['wave',
'angry',
'applause',
'cringe',
'confused',
'slip-forward',
'slip-backward',
'resistance-salute',
'surprise',
'cry',
'furious',
'laugh',
'idea',
'taunt',
'rage']
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'ScientistScene', effects)
self.geom = loader.loadModel('phase_3.5/models/modules/tt_m_ara_int_toonhall')
self.geom.reparentTo(self)
self.taskStarted = False
self.npcs = []
for id, posHpr in self.ToonPos.iteritems():
npc = NPCToons.createLocalNPC(id)
npc.reparentTo(self.geom)
npc.setPosHpr(*posHpr)
npc.nametag3d.removeNode()
npc.nametag.destroy()
self.npcs.append(npc)
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
npc.delete()
self.npcs = []
self.taskStarted = False
ThreeDScene.delete(self)
return
def startTask(self):
<|fim_middle|>
def stopTask(self):
if not self.taskStarted:
return
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
self.taskStarted = False
def doRandomEmote(self, npc, task):
Emote.globalEmote.doEmote(npc, TTEmote.Emotes.index(random.choice(self.RandomEmotes)), 0)
task.delayTime = npc.emoteTrack.getDuration() + 1.0
return task.again<|fim▁end|> | if self.taskStarted:
return
for i, npc in enumerate(self.npcs):
taskMgr.doMethodLater(0.25 * i, lambda task, npc = npc: self.doRandomEmote(npc, task), npc.uniqueName('randomEmote'))
self.taskStarted = True |
<|file_name|>TutorialTVScenes.py<|end_file_name|><|fim▁begin|># Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.tutorial.TutorialTVScenes
from panda3d.core import Camera
from direct.task.Task import Task
from otp.avatar import Emote
from toontown.television.TVScenes import *
from toontown.television.TVEffects import *
from toontown.suit.Suit import Suit
from toontown.suit.BossCog import BossCog
from toontown.suit.SuitDNA import SuitDNA
from toontown.toon import NPCToons, TTEmote
import random
class CEOScene(ThreeDScene):
CameraPos = [(0, 203.5, 23.5, 0, 350, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'CEOScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BanquetInterior_1')
self.geom.reparentTo(self)
self.ceo = BossCog()
dna = SuitDNA()
dna.newBossCog('c')
self.ceo.setDNA(dna)
self.ceo.reparentTo(self)
self.ceo.setPosHpr(0, 236.5, 0, 180, 0, 0)
self.ceo.loop('Bb_neutral')
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.ceo:
self.ceo.delete()
self.ceo = None
ThreeDScene.delete(self)
return
class HeadHunterScene(ThreeDScene):
CameraPos = [(-22, -12.5, 7, 92, -6, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'HeadHunterScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BossbotEntranceRoom')
self.geom.reparentTo(self)
self.cog = Suit()
dna = SuitDNA()
dna.newSuit('hh')
self.cog.setDNA(dna)
self.cog.reparentTo(self)
self.cog.setPosHpr(-32.5, -12.5, 0.02, 270, 0, 0)
self.cog.nametag3d.removeNode()
self.cog.nametag.destroy()
self.cog.loop('neutral')
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.cog:
self.cog.delete()
self.cog = None
ThreeDScene.delete(self)
return
class ScientistScene(ThreeDScene):
CameraPos = [(-47.5, 0.5, 3.415, 90, 0, 0)]
ToonPos = {2018: (-59, -1.5, 0.02, 270, 0, 0),
2019: (-59, 0.5, 0.02, 270, 0, 0),
2020: (-59, 2.5, 0.02, 270, 0, 0)}
RandomEmotes = ['wave',
'angry',
'applause',
'cringe',
'confused',
'slip-forward',
'slip-backward',
'resistance-salute',
'surprise',
'cry',
'furious',
'laugh',
'idea',
'taunt',
'rage']
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'ScientistScene', effects)
self.geom = loader.loadModel('phase_3.5/models/modules/tt_m_ara_int_toonhall')
self.geom.reparentTo(self)
self.taskStarted = False
self.npcs = []
for id, posHpr in self.ToonPos.iteritems():
npc = NPCToons.createLocalNPC(id)
npc.reparentTo(self.geom)
npc.setPosHpr(*posHpr)
npc.nametag3d.removeNode()
npc.nametag.destroy()
self.npcs.append(npc)
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
npc.delete()
self.npcs = []
self.taskStarted = False
ThreeDScene.delete(self)
return
def startTask(self):
if self.taskStarted:
return
for i, npc in enumerate(self.npcs):
taskMgr.doMethodLater(0.25 * i, lambda task, npc = npc: self.doRandomEmote(npc, task), npc.uniqueName('randomEmote'))
self.taskStarted = True
def stopTask(self):
<|fim_middle|>
def doRandomEmote(self, npc, task):
Emote.globalEmote.doEmote(npc, TTEmote.Emotes.index(random.choice(self.RandomEmotes)), 0)
task.delayTime = npc.emoteTrack.getDuration() + 1.0
return task.again<|fim▁end|> | if not self.taskStarted:
return
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
self.taskStarted = False |
<|file_name|>TutorialTVScenes.py<|end_file_name|><|fim▁begin|># Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.tutorial.TutorialTVScenes
from panda3d.core import Camera
from direct.task.Task import Task
from otp.avatar import Emote
from toontown.television.TVScenes import *
from toontown.television.TVEffects import *
from toontown.suit.Suit import Suit
from toontown.suit.BossCog import BossCog
from toontown.suit.SuitDNA import SuitDNA
from toontown.toon import NPCToons, TTEmote
import random
class CEOScene(ThreeDScene):
CameraPos = [(0, 203.5, 23.5, 0, 350, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'CEOScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BanquetInterior_1')
self.geom.reparentTo(self)
self.ceo = BossCog()
dna = SuitDNA()
dna.newBossCog('c')
self.ceo.setDNA(dna)
self.ceo.reparentTo(self)
self.ceo.setPosHpr(0, 236.5, 0, 180, 0, 0)
self.ceo.loop('Bb_neutral')
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.ceo:
self.ceo.delete()
self.ceo = None
ThreeDScene.delete(self)
return
class HeadHunterScene(ThreeDScene):
CameraPos = [(-22, -12.5, 7, 92, -6, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'HeadHunterScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BossbotEntranceRoom')
self.geom.reparentTo(self)
self.cog = Suit()
dna = SuitDNA()
dna.newSuit('hh')
self.cog.setDNA(dna)
self.cog.reparentTo(self)
self.cog.setPosHpr(-32.5, -12.5, 0.02, 270, 0, 0)
self.cog.nametag3d.removeNode()
self.cog.nametag.destroy()
self.cog.loop('neutral')
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.cog:
self.cog.delete()
self.cog = None
ThreeDScene.delete(self)
return
class ScientistScene(ThreeDScene):
CameraPos = [(-47.5, 0.5, 3.415, 90, 0, 0)]
ToonPos = {2018: (-59, -1.5, 0.02, 270, 0, 0),
2019: (-59, 0.5, 0.02, 270, 0, 0),
2020: (-59, 2.5, 0.02, 270, 0, 0)}
RandomEmotes = ['wave',
'angry',
'applause',
'cringe',
'confused',
'slip-forward',
'slip-backward',
'resistance-salute',
'surprise',
'cry',
'furious',
'laugh',
'idea',
'taunt',
'rage']
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'ScientistScene', effects)
self.geom = loader.loadModel('phase_3.5/models/modules/tt_m_ara_int_toonhall')
self.geom.reparentTo(self)
self.taskStarted = False
self.npcs = []
for id, posHpr in self.ToonPos.iteritems():
npc = NPCToons.createLocalNPC(id)
npc.reparentTo(self.geom)
npc.setPosHpr(*posHpr)
npc.nametag3d.removeNode()
npc.nametag.destroy()
self.npcs.append(npc)
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
npc.delete()
self.npcs = []
self.taskStarted = False
ThreeDScene.delete(self)
return
def startTask(self):
if self.taskStarted:
return
for i, npc in enumerate(self.npcs):
taskMgr.doMethodLater(0.25 * i, lambda task, npc = npc: self.doRandomEmote(npc, task), npc.uniqueName('randomEmote'))
self.taskStarted = True
def stopTask(self):
if not self.taskStarted:
return
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
self.taskStarted = False
def doRandomEmote(self, npc, task):
<|fim_middle|>
<|fim▁end|> | Emote.globalEmote.doEmote(npc, TTEmote.Emotes.index(random.choice(self.RandomEmotes)), 0)
task.delayTime = npc.emoteTrack.getDuration() + 1.0
return task.again |
<|file_name|>TutorialTVScenes.py<|end_file_name|><|fim▁begin|># Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.tutorial.TutorialTVScenes
from panda3d.core import Camera
from direct.task.Task import Task
from otp.avatar import Emote
from toontown.television.TVScenes import *
from toontown.television.TVEffects import *
from toontown.suit.Suit import Suit
from toontown.suit.BossCog import BossCog
from toontown.suit.SuitDNA import SuitDNA
from toontown.toon import NPCToons, TTEmote
import random
class CEOScene(ThreeDScene):
CameraPos = [(0, 203.5, 23.5, 0, 350, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'CEOScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BanquetInterior_1')
self.geom.reparentTo(self)
self.ceo = BossCog()
dna = SuitDNA()
dna.newBossCog('c')
self.ceo.setDNA(dna)
self.ceo.reparentTo(self)
self.ceo.setPosHpr(0, 236.5, 0, 180, 0, 0)
self.ceo.loop('Bb_neutral')
def delete(self):
if self.geom:
<|fim_middle|>
if self.ceo:
self.ceo.delete()
self.ceo = None
ThreeDScene.delete(self)
return
class HeadHunterScene(ThreeDScene):
CameraPos = [(-22, -12.5, 7, 92, -6, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'HeadHunterScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BossbotEntranceRoom')
self.geom.reparentTo(self)
self.cog = Suit()
dna = SuitDNA()
dna.newSuit('hh')
self.cog.setDNA(dna)
self.cog.reparentTo(self)
self.cog.setPosHpr(-32.5, -12.5, 0.02, 270, 0, 0)
self.cog.nametag3d.removeNode()
self.cog.nametag.destroy()
self.cog.loop('neutral')
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.cog:
self.cog.delete()
self.cog = None
ThreeDScene.delete(self)
return
class ScientistScene(ThreeDScene):
CameraPos = [(-47.5, 0.5, 3.415, 90, 0, 0)]
ToonPos = {2018: (-59, -1.5, 0.02, 270, 0, 0),
2019: (-59, 0.5, 0.02, 270, 0, 0),
2020: (-59, 2.5, 0.02, 270, 0, 0)}
RandomEmotes = ['wave',
'angry',
'applause',
'cringe',
'confused',
'slip-forward',
'slip-backward',
'resistance-salute',
'surprise',
'cry',
'furious',
'laugh',
'idea',
'taunt',
'rage']
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'ScientistScene', effects)
self.geom = loader.loadModel('phase_3.5/models/modules/tt_m_ara_int_toonhall')
self.geom.reparentTo(self)
self.taskStarted = False
self.npcs = []
for id, posHpr in self.ToonPos.iteritems():
npc = NPCToons.createLocalNPC(id)
npc.reparentTo(self.geom)
npc.setPosHpr(*posHpr)
npc.nametag3d.removeNode()
npc.nametag.destroy()
self.npcs.append(npc)
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
npc.delete()
self.npcs = []
self.taskStarted = False
ThreeDScene.delete(self)
return
def startTask(self):
if self.taskStarted:
return
for i, npc in enumerate(self.npcs):
taskMgr.doMethodLater(0.25 * i, lambda task, npc = npc: self.doRandomEmote(npc, task), npc.uniqueName('randomEmote'))
self.taskStarted = True
def stopTask(self):
if not self.taskStarted:
return
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
self.taskStarted = False
def doRandomEmote(self, npc, task):
Emote.globalEmote.doEmote(npc, TTEmote.Emotes.index(random.choice(self.RandomEmotes)), 0)
task.delayTime = npc.emoteTrack.getDuration() + 1.0
return task.again<|fim▁end|> | self.geom.removeNode()
self.geom = None |
<|file_name|>TutorialTVScenes.py<|end_file_name|><|fim▁begin|># Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.tutorial.TutorialTVScenes
from panda3d.core import Camera
from direct.task.Task import Task
from otp.avatar import Emote
from toontown.television.TVScenes import *
from toontown.television.TVEffects import *
from toontown.suit.Suit import Suit
from toontown.suit.BossCog import BossCog
from toontown.suit.SuitDNA import SuitDNA
from toontown.toon import NPCToons, TTEmote
import random
class CEOScene(ThreeDScene):
CameraPos = [(0, 203.5, 23.5, 0, 350, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'CEOScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BanquetInterior_1')
self.geom.reparentTo(self)
self.ceo = BossCog()
dna = SuitDNA()
dna.newBossCog('c')
self.ceo.setDNA(dna)
self.ceo.reparentTo(self)
self.ceo.setPosHpr(0, 236.5, 0, 180, 0, 0)
self.ceo.loop('Bb_neutral')
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.ceo:
<|fim_middle|>
ThreeDScene.delete(self)
return
class HeadHunterScene(ThreeDScene):
CameraPos = [(-22, -12.5, 7, 92, -6, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'HeadHunterScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BossbotEntranceRoom')
self.geom.reparentTo(self)
self.cog = Suit()
dna = SuitDNA()
dna.newSuit('hh')
self.cog.setDNA(dna)
self.cog.reparentTo(self)
self.cog.setPosHpr(-32.5, -12.5, 0.02, 270, 0, 0)
self.cog.nametag3d.removeNode()
self.cog.nametag.destroy()
self.cog.loop('neutral')
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.cog:
self.cog.delete()
self.cog = None
ThreeDScene.delete(self)
return
class ScientistScene(ThreeDScene):
CameraPos = [(-47.5, 0.5, 3.415, 90, 0, 0)]
ToonPos = {2018: (-59, -1.5, 0.02, 270, 0, 0),
2019: (-59, 0.5, 0.02, 270, 0, 0),
2020: (-59, 2.5, 0.02, 270, 0, 0)}
RandomEmotes = ['wave',
'angry',
'applause',
'cringe',
'confused',
'slip-forward',
'slip-backward',
'resistance-salute',
'surprise',
'cry',
'furious',
'laugh',
'idea',
'taunt',
'rage']
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'ScientistScene', effects)
self.geom = loader.loadModel('phase_3.5/models/modules/tt_m_ara_int_toonhall')
self.geom.reparentTo(self)
self.taskStarted = False
self.npcs = []
for id, posHpr in self.ToonPos.iteritems():
npc = NPCToons.createLocalNPC(id)
npc.reparentTo(self.geom)
npc.setPosHpr(*posHpr)
npc.nametag3d.removeNode()
npc.nametag.destroy()
self.npcs.append(npc)
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
npc.delete()
self.npcs = []
self.taskStarted = False
ThreeDScene.delete(self)
return
def startTask(self):
if self.taskStarted:
return
for i, npc in enumerate(self.npcs):
taskMgr.doMethodLater(0.25 * i, lambda task, npc = npc: self.doRandomEmote(npc, task), npc.uniqueName('randomEmote'))
self.taskStarted = True
def stopTask(self):
if not self.taskStarted:
return
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
self.taskStarted = False
def doRandomEmote(self, npc, task):
Emote.globalEmote.doEmote(npc, TTEmote.Emotes.index(random.choice(self.RandomEmotes)), 0)
task.delayTime = npc.emoteTrack.getDuration() + 1.0
return task.again<|fim▁end|> | self.ceo.delete()
self.ceo = None |
<|file_name|>TutorialTVScenes.py<|end_file_name|><|fim▁begin|># Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.tutorial.TutorialTVScenes
from panda3d.core import Camera
from direct.task.Task import Task
from otp.avatar import Emote
from toontown.television.TVScenes import *
from toontown.television.TVEffects import *
from toontown.suit.Suit import Suit
from toontown.suit.BossCog import BossCog
from toontown.suit.SuitDNA import SuitDNA
from toontown.toon import NPCToons, TTEmote
import random
class CEOScene(ThreeDScene):
CameraPos = [(0, 203.5, 23.5, 0, 350, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'CEOScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BanquetInterior_1')
self.geom.reparentTo(self)
self.ceo = BossCog()
dna = SuitDNA()
dna.newBossCog('c')
self.ceo.setDNA(dna)
self.ceo.reparentTo(self)
self.ceo.setPosHpr(0, 236.5, 0, 180, 0, 0)
self.ceo.loop('Bb_neutral')
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.ceo:
self.ceo.delete()
self.ceo = None
ThreeDScene.delete(self)
return
class HeadHunterScene(ThreeDScene):
CameraPos = [(-22, -12.5, 7, 92, -6, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'HeadHunterScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BossbotEntranceRoom')
self.geom.reparentTo(self)
self.cog = Suit()
dna = SuitDNA()
dna.newSuit('hh')
self.cog.setDNA(dna)
self.cog.reparentTo(self)
self.cog.setPosHpr(-32.5, -12.5, 0.02, 270, 0, 0)
self.cog.nametag3d.removeNode()
self.cog.nametag.destroy()
self.cog.loop('neutral')
def delete(self):
if self.geom:
<|fim_middle|>
if self.cog:
self.cog.delete()
self.cog = None
ThreeDScene.delete(self)
return
class ScientistScene(ThreeDScene):
CameraPos = [(-47.5, 0.5, 3.415, 90, 0, 0)]
ToonPos = {2018: (-59, -1.5, 0.02, 270, 0, 0),
2019: (-59, 0.5, 0.02, 270, 0, 0),
2020: (-59, 2.5, 0.02, 270, 0, 0)}
RandomEmotes = ['wave',
'angry',
'applause',
'cringe',
'confused',
'slip-forward',
'slip-backward',
'resistance-salute',
'surprise',
'cry',
'furious',
'laugh',
'idea',
'taunt',
'rage']
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'ScientistScene', effects)
self.geom = loader.loadModel('phase_3.5/models/modules/tt_m_ara_int_toonhall')
self.geom.reparentTo(self)
self.taskStarted = False
self.npcs = []
for id, posHpr in self.ToonPos.iteritems():
npc = NPCToons.createLocalNPC(id)
npc.reparentTo(self.geom)
npc.setPosHpr(*posHpr)
npc.nametag3d.removeNode()
npc.nametag.destroy()
self.npcs.append(npc)
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
npc.delete()
self.npcs = []
self.taskStarted = False
ThreeDScene.delete(self)
return
def startTask(self):
if self.taskStarted:
return
for i, npc in enumerate(self.npcs):
taskMgr.doMethodLater(0.25 * i, lambda task, npc = npc: self.doRandomEmote(npc, task), npc.uniqueName('randomEmote'))
self.taskStarted = True
def stopTask(self):
if not self.taskStarted:
return
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
self.taskStarted = False
def doRandomEmote(self, npc, task):
Emote.globalEmote.doEmote(npc, TTEmote.Emotes.index(random.choice(self.RandomEmotes)), 0)
task.delayTime = npc.emoteTrack.getDuration() + 1.0
return task.again<|fim▁end|> | self.geom.removeNode()
self.geom = None |
<|file_name|>TutorialTVScenes.py<|end_file_name|><|fim▁begin|># Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.tutorial.TutorialTVScenes
from panda3d.core import Camera
from direct.task.Task import Task
from otp.avatar import Emote
from toontown.television.TVScenes import *
from toontown.television.TVEffects import *
from toontown.suit.Suit import Suit
from toontown.suit.BossCog import BossCog
from toontown.suit.SuitDNA import SuitDNA
from toontown.toon import NPCToons, TTEmote
import random
class CEOScene(ThreeDScene):
CameraPos = [(0, 203.5, 23.5, 0, 350, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'CEOScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BanquetInterior_1')
self.geom.reparentTo(self)
self.ceo = BossCog()
dna = SuitDNA()
dna.newBossCog('c')
self.ceo.setDNA(dna)
self.ceo.reparentTo(self)
self.ceo.setPosHpr(0, 236.5, 0, 180, 0, 0)
self.ceo.loop('Bb_neutral')
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.ceo:
self.ceo.delete()
self.ceo = None
ThreeDScene.delete(self)
return
class HeadHunterScene(ThreeDScene):
CameraPos = [(-22, -12.5, 7, 92, -6, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'HeadHunterScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BossbotEntranceRoom')
self.geom.reparentTo(self)
self.cog = Suit()
dna = SuitDNA()
dna.newSuit('hh')
self.cog.setDNA(dna)
self.cog.reparentTo(self)
self.cog.setPosHpr(-32.5, -12.5, 0.02, 270, 0, 0)
self.cog.nametag3d.removeNode()
self.cog.nametag.destroy()
self.cog.loop('neutral')
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.cog:
<|fim_middle|>
ThreeDScene.delete(self)
return
class ScientistScene(ThreeDScene):
CameraPos = [(-47.5, 0.5, 3.415, 90, 0, 0)]
ToonPos = {2018: (-59, -1.5, 0.02, 270, 0, 0),
2019: (-59, 0.5, 0.02, 270, 0, 0),
2020: (-59, 2.5, 0.02, 270, 0, 0)}
RandomEmotes = ['wave',
'angry',
'applause',
'cringe',
'confused',
'slip-forward',
'slip-backward',
'resistance-salute',
'surprise',
'cry',
'furious',
'laugh',
'idea',
'taunt',
'rage']
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'ScientistScene', effects)
self.geom = loader.loadModel('phase_3.5/models/modules/tt_m_ara_int_toonhall')
self.geom.reparentTo(self)
self.taskStarted = False
self.npcs = []
for id, posHpr in self.ToonPos.iteritems():
npc = NPCToons.createLocalNPC(id)
npc.reparentTo(self.geom)
npc.setPosHpr(*posHpr)
npc.nametag3d.removeNode()
npc.nametag.destroy()
self.npcs.append(npc)
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
npc.delete()
self.npcs = []
self.taskStarted = False
ThreeDScene.delete(self)
return
def startTask(self):
if self.taskStarted:
return
for i, npc in enumerate(self.npcs):
taskMgr.doMethodLater(0.25 * i, lambda task, npc = npc: self.doRandomEmote(npc, task), npc.uniqueName('randomEmote'))
self.taskStarted = True
def stopTask(self):
if not self.taskStarted:
return
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
self.taskStarted = False
def doRandomEmote(self, npc, task):
Emote.globalEmote.doEmote(npc, TTEmote.Emotes.index(random.choice(self.RandomEmotes)), 0)
task.delayTime = npc.emoteTrack.getDuration() + 1.0
return task.again<|fim▁end|> | self.cog.delete()
self.cog = None |
<|file_name|>TutorialTVScenes.py<|end_file_name|><|fim▁begin|># Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.tutorial.TutorialTVScenes
from panda3d.core import Camera
from direct.task.Task import Task
from otp.avatar import Emote
from toontown.television.TVScenes import *
from toontown.television.TVEffects import *
from toontown.suit.Suit import Suit
from toontown.suit.BossCog import BossCog
from toontown.suit.SuitDNA import SuitDNA
from toontown.toon import NPCToons, TTEmote
import random
class CEOScene(ThreeDScene):
CameraPos = [(0, 203.5, 23.5, 0, 350, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'CEOScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BanquetInterior_1')
self.geom.reparentTo(self)
self.ceo = BossCog()
dna = SuitDNA()
dna.newBossCog('c')
self.ceo.setDNA(dna)
self.ceo.reparentTo(self)
self.ceo.setPosHpr(0, 236.5, 0, 180, 0, 0)
self.ceo.loop('Bb_neutral')
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.ceo:
self.ceo.delete()
self.ceo = None
ThreeDScene.delete(self)
return
class HeadHunterScene(ThreeDScene):
CameraPos = [(-22, -12.5, 7, 92, -6, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'HeadHunterScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BossbotEntranceRoom')
self.geom.reparentTo(self)
self.cog = Suit()
dna = SuitDNA()
dna.newSuit('hh')
self.cog.setDNA(dna)
self.cog.reparentTo(self)
self.cog.setPosHpr(-32.5, -12.5, 0.02, 270, 0, 0)
self.cog.nametag3d.removeNode()
self.cog.nametag.destroy()
self.cog.loop('neutral')
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.cog:
self.cog.delete()
self.cog = None
ThreeDScene.delete(self)
return
class ScientistScene(ThreeDScene):
CameraPos = [(-47.5, 0.5, 3.415, 90, 0, 0)]
ToonPos = {2018: (-59, -1.5, 0.02, 270, 0, 0),
2019: (-59, 0.5, 0.02, 270, 0, 0),
2020: (-59, 2.5, 0.02, 270, 0, 0)}
RandomEmotes = ['wave',
'angry',
'applause',
'cringe',
'confused',
'slip-forward',
'slip-backward',
'resistance-salute',
'surprise',
'cry',
'furious',
'laugh',
'idea',
'taunt',
'rage']
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'ScientistScene', effects)
self.geom = loader.loadModel('phase_3.5/models/modules/tt_m_ara_int_toonhall')
self.geom.reparentTo(self)
self.taskStarted = False
self.npcs = []
for id, posHpr in self.ToonPos.iteritems():
npc = NPCToons.createLocalNPC(id)
npc.reparentTo(self.geom)
npc.setPosHpr(*posHpr)
npc.nametag3d.removeNode()
npc.nametag.destroy()
self.npcs.append(npc)
def delete(self):
if self.geom:
<|fim_middle|>
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
npc.delete()
self.npcs = []
self.taskStarted = False
ThreeDScene.delete(self)
return
def startTask(self):
if self.taskStarted:
return
for i, npc in enumerate(self.npcs):
taskMgr.doMethodLater(0.25 * i, lambda task, npc = npc: self.doRandomEmote(npc, task), npc.uniqueName('randomEmote'))
self.taskStarted = True
def stopTask(self):
if not self.taskStarted:
return
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
self.taskStarted = False
def doRandomEmote(self, npc, task):
Emote.globalEmote.doEmote(npc, TTEmote.Emotes.index(random.choice(self.RandomEmotes)), 0)
task.delayTime = npc.emoteTrack.getDuration() + 1.0
return task.again<|fim▁end|> | self.geom.removeNode()
self.geom = None |
<|file_name|>TutorialTVScenes.py<|end_file_name|><|fim▁begin|># Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.tutorial.TutorialTVScenes
from panda3d.core import Camera
from direct.task.Task import Task
from otp.avatar import Emote
from toontown.television.TVScenes import *
from toontown.television.TVEffects import *
from toontown.suit.Suit import Suit
from toontown.suit.BossCog import BossCog
from toontown.suit.SuitDNA import SuitDNA
from toontown.toon import NPCToons, TTEmote
import random
class CEOScene(ThreeDScene):
CameraPos = [(0, 203.5, 23.5, 0, 350, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'CEOScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BanquetInterior_1')
self.geom.reparentTo(self)
self.ceo = BossCog()
dna = SuitDNA()
dna.newBossCog('c')
self.ceo.setDNA(dna)
self.ceo.reparentTo(self)
self.ceo.setPosHpr(0, 236.5, 0, 180, 0, 0)
self.ceo.loop('Bb_neutral')
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.ceo:
self.ceo.delete()
self.ceo = None
ThreeDScene.delete(self)
return
class HeadHunterScene(ThreeDScene):
CameraPos = [(-22, -12.5, 7, 92, -6, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'HeadHunterScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BossbotEntranceRoom')
self.geom.reparentTo(self)
self.cog = Suit()
dna = SuitDNA()
dna.newSuit('hh')
self.cog.setDNA(dna)
self.cog.reparentTo(self)
self.cog.setPosHpr(-32.5, -12.5, 0.02, 270, 0, 0)
self.cog.nametag3d.removeNode()
self.cog.nametag.destroy()
self.cog.loop('neutral')
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.cog:
self.cog.delete()
self.cog = None
ThreeDScene.delete(self)
return
class ScientistScene(ThreeDScene):
CameraPos = [(-47.5, 0.5, 3.415, 90, 0, 0)]
ToonPos = {2018: (-59, -1.5, 0.02, 270, 0, 0),
2019: (-59, 0.5, 0.02, 270, 0, 0),
2020: (-59, 2.5, 0.02, 270, 0, 0)}
RandomEmotes = ['wave',
'angry',
'applause',
'cringe',
'confused',
'slip-forward',
'slip-backward',
'resistance-salute',
'surprise',
'cry',
'furious',
'laugh',
'idea',
'taunt',
'rage']
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'ScientistScene', effects)
self.geom = loader.loadModel('phase_3.5/models/modules/tt_m_ara_int_toonhall')
self.geom.reparentTo(self)
self.taskStarted = False
self.npcs = []
for id, posHpr in self.ToonPos.iteritems():
npc = NPCToons.createLocalNPC(id)
npc.reparentTo(self.geom)
npc.setPosHpr(*posHpr)
npc.nametag3d.removeNode()
npc.nametag.destroy()
self.npcs.append(npc)
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
npc.delete()
self.npcs = []
self.taskStarted = False
ThreeDScene.delete(self)
return
def startTask(self):
if self.taskStarted:
<|fim_middle|>
for i, npc in enumerate(self.npcs):
taskMgr.doMethodLater(0.25 * i, lambda task, npc = npc: self.doRandomEmote(npc, task), npc.uniqueName('randomEmote'))
self.taskStarted = True
def stopTask(self):
if not self.taskStarted:
return
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
self.taskStarted = False
def doRandomEmote(self, npc, task):
Emote.globalEmote.doEmote(npc, TTEmote.Emotes.index(random.choice(self.RandomEmotes)), 0)
task.delayTime = npc.emoteTrack.getDuration() + 1.0
return task.again<|fim▁end|> | return |
<|file_name|>TutorialTVScenes.py<|end_file_name|><|fim▁begin|># Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.tutorial.TutorialTVScenes
from panda3d.core import Camera
from direct.task.Task import Task
from otp.avatar import Emote
from toontown.television.TVScenes import *
from toontown.television.TVEffects import *
from toontown.suit.Suit import Suit
from toontown.suit.BossCog import BossCog
from toontown.suit.SuitDNA import SuitDNA
from toontown.toon import NPCToons, TTEmote
import random
class CEOScene(ThreeDScene):
CameraPos = [(0, 203.5, 23.5, 0, 350, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'CEOScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BanquetInterior_1')
self.geom.reparentTo(self)
self.ceo = BossCog()
dna = SuitDNA()
dna.newBossCog('c')
self.ceo.setDNA(dna)
self.ceo.reparentTo(self)
self.ceo.setPosHpr(0, 236.5, 0, 180, 0, 0)
self.ceo.loop('Bb_neutral')
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.ceo:
self.ceo.delete()
self.ceo = None
ThreeDScene.delete(self)
return
class HeadHunterScene(ThreeDScene):
CameraPos = [(-22, -12.5, 7, 92, -6, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'HeadHunterScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BossbotEntranceRoom')
self.geom.reparentTo(self)
self.cog = Suit()
dna = SuitDNA()
dna.newSuit('hh')
self.cog.setDNA(dna)
self.cog.reparentTo(self)
self.cog.setPosHpr(-32.5, -12.5, 0.02, 270, 0, 0)
self.cog.nametag3d.removeNode()
self.cog.nametag.destroy()
self.cog.loop('neutral')
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.cog:
self.cog.delete()
self.cog = None
ThreeDScene.delete(self)
return
class ScientistScene(ThreeDScene):
CameraPos = [(-47.5, 0.5, 3.415, 90, 0, 0)]
ToonPos = {2018: (-59, -1.5, 0.02, 270, 0, 0),
2019: (-59, 0.5, 0.02, 270, 0, 0),
2020: (-59, 2.5, 0.02, 270, 0, 0)}
RandomEmotes = ['wave',
'angry',
'applause',
'cringe',
'confused',
'slip-forward',
'slip-backward',
'resistance-salute',
'surprise',
'cry',
'furious',
'laugh',
'idea',
'taunt',
'rage']
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'ScientistScene', effects)
self.geom = loader.loadModel('phase_3.5/models/modules/tt_m_ara_int_toonhall')
self.geom.reparentTo(self)
self.taskStarted = False
self.npcs = []
for id, posHpr in self.ToonPos.iteritems():
npc = NPCToons.createLocalNPC(id)
npc.reparentTo(self.geom)
npc.setPosHpr(*posHpr)
npc.nametag3d.removeNode()
npc.nametag.destroy()
self.npcs.append(npc)
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
npc.delete()
self.npcs = []
self.taskStarted = False
ThreeDScene.delete(self)
return
def startTask(self):
if self.taskStarted:
return
for i, npc in enumerate(self.npcs):
taskMgr.doMethodLater(0.25 * i, lambda task, npc = npc: self.doRandomEmote(npc, task), npc.uniqueName('randomEmote'))
self.taskStarted = True
def stopTask(self):
if not self.taskStarted:
<|fim_middle|>
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
self.taskStarted = False
def doRandomEmote(self, npc, task):
Emote.globalEmote.doEmote(npc, TTEmote.Emotes.index(random.choice(self.RandomEmotes)), 0)
task.delayTime = npc.emoteTrack.getDuration() + 1.0
return task.again<|fim▁end|> | return |
<|file_name|>TutorialTVScenes.py<|end_file_name|><|fim▁begin|># Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.tutorial.TutorialTVScenes
from panda3d.core import Camera
from direct.task.Task import Task
from otp.avatar import Emote
from toontown.television.TVScenes import *
from toontown.television.TVEffects import *
from toontown.suit.Suit import Suit
from toontown.suit.BossCog import BossCog
from toontown.suit.SuitDNA import SuitDNA
from toontown.toon import NPCToons, TTEmote
import random
class CEOScene(ThreeDScene):
CameraPos = [(0, 203.5, 23.5, 0, 350, 0)]
def <|fim_middle|>(self, effects = []):
ThreeDScene.__init__(self, 'CEOScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BanquetInterior_1')
self.geom.reparentTo(self)
self.ceo = BossCog()
dna = SuitDNA()
dna.newBossCog('c')
self.ceo.setDNA(dna)
self.ceo.reparentTo(self)
self.ceo.setPosHpr(0, 236.5, 0, 180, 0, 0)
self.ceo.loop('Bb_neutral')
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.ceo:
self.ceo.delete()
self.ceo = None
ThreeDScene.delete(self)
return
class HeadHunterScene(ThreeDScene):
CameraPos = [(-22, -12.5, 7, 92, -6, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'HeadHunterScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BossbotEntranceRoom')
self.geom.reparentTo(self)
self.cog = Suit()
dna = SuitDNA()
dna.newSuit('hh')
self.cog.setDNA(dna)
self.cog.reparentTo(self)
self.cog.setPosHpr(-32.5, -12.5, 0.02, 270, 0, 0)
self.cog.nametag3d.removeNode()
self.cog.nametag.destroy()
self.cog.loop('neutral')
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.cog:
self.cog.delete()
self.cog = None
ThreeDScene.delete(self)
return
class ScientistScene(ThreeDScene):
CameraPos = [(-47.5, 0.5, 3.415, 90, 0, 0)]
ToonPos = {2018: (-59, -1.5, 0.02, 270, 0, 0),
2019: (-59, 0.5, 0.02, 270, 0, 0),
2020: (-59, 2.5, 0.02, 270, 0, 0)}
RandomEmotes = ['wave',
'angry',
'applause',
'cringe',
'confused',
'slip-forward',
'slip-backward',
'resistance-salute',
'surprise',
'cry',
'furious',
'laugh',
'idea',
'taunt',
'rage']
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'ScientistScene', effects)
self.geom = loader.loadModel('phase_3.5/models/modules/tt_m_ara_int_toonhall')
self.geom.reparentTo(self)
self.taskStarted = False
self.npcs = []
for id, posHpr in self.ToonPos.iteritems():
npc = NPCToons.createLocalNPC(id)
npc.reparentTo(self.geom)
npc.setPosHpr(*posHpr)
npc.nametag3d.removeNode()
npc.nametag.destroy()
self.npcs.append(npc)
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
npc.delete()
self.npcs = []
self.taskStarted = False
ThreeDScene.delete(self)
return
def startTask(self):
if self.taskStarted:
return
for i, npc in enumerate(self.npcs):
taskMgr.doMethodLater(0.25 * i, lambda task, npc = npc: self.doRandomEmote(npc, task), npc.uniqueName('randomEmote'))
self.taskStarted = True
def stopTask(self):
if not self.taskStarted:
return
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
self.taskStarted = False
def doRandomEmote(self, npc, task):
Emote.globalEmote.doEmote(npc, TTEmote.Emotes.index(random.choice(self.RandomEmotes)), 0)
task.delayTime = npc.emoteTrack.getDuration() + 1.0
return task.again<|fim▁end|> | __init__ |
<|file_name|>TutorialTVScenes.py<|end_file_name|><|fim▁begin|># Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.tutorial.TutorialTVScenes
from panda3d.core import Camera
from direct.task.Task import Task
from otp.avatar import Emote
from toontown.television.TVScenes import *
from toontown.television.TVEffects import *
from toontown.suit.Suit import Suit
from toontown.suit.BossCog import BossCog
from toontown.suit.SuitDNA import SuitDNA
from toontown.toon import NPCToons, TTEmote
import random
class CEOScene(ThreeDScene):
CameraPos = [(0, 203.5, 23.5, 0, 350, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'CEOScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BanquetInterior_1')
self.geom.reparentTo(self)
self.ceo = BossCog()
dna = SuitDNA()
dna.newBossCog('c')
self.ceo.setDNA(dna)
self.ceo.reparentTo(self)
self.ceo.setPosHpr(0, 236.5, 0, 180, 0, 0)
self.ceo.loop('Bb_neutral')
def <|fim_middle|>(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.ceo:
self.ceo.delete()
self.ceo = None
ThreeDScene.delete(self)
return
class HeadHunterScene(ThreeDScene):
CameraPos = [(-22, -12.5, 7, 92, -6, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'HeadHunterScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BossbotEntranceRoom')
self.geom.reparentTo(self)
self.cog = Suit()
dna = SuitDNA()
dna.newSuit('hh')
self.cog.setDNA(dna)
self.cog.reparentTo(self)
self.cog.setPosHpr(-32.5, -12.5, 0.02, 270, 0, 0)
self.cog.nametag3d.removeNode()
self.cog.nametag.destroy()
self.cog.loop('neutral')
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.cog:
self.cog.delete()
self.cog = None
ThreeDScene.delete(self)
return
class ScientistScene(ThreeDScene):
CameraPos = [(-47.5, 0.5, 3.415, 90, 0, 0)]
ToonPos = {2018: (-59, -1.5, 0.02, 270, 0, 0),
2019: (-59, 0.5, 0.02, 270, 0, 0),
2020: (-59, 2.5, 0.02, 270, 0, 0)}
RandomEmotes = ['wave',
'angry',
'applause',
'cringe',
'confused',
'slip-forward',
'slip-backward',
'resistance-salute',
'surprise',
'cry',
'furious',
'laugh',
'idea',
'taunt',
'rage']
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'ScientistScene', effects)
self.geom = loader.loadModel('phase_3.5/models/modules/tt_m_ara_int_toonhall')
self.geom.reparentTo(self)
self.taskStarted = False
self.npcs = []
for id, posHpr in self.ToonPos.iteritems():
npc = NPCToons.createLocalNPC(id)
npc.reparentTo(self.geom)
npc.setPosHpr(*posHpr)
npc.nametag3d.removeNode()
npc.nametag.destroy()
self.npcs.append(npc)
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
npc.delete()
self.npcs = []
self.taskStarted = False
ThreeDScene.delete(self)
return
def startTask(self):
if self.taskStarted:
return
for i, npc in enumerate(self.npcs):
taskMgr.doMethodLater(0.25 * i, lambda task, npc = npc: self.doRandomEmote(npc, task), npc.uniqueName('randomEmote'))
self.taskStarted = True
def stopTask(self):
if not self.taskStarted:
return
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
self.taskStarted = False
def doRandomEmote(self, npc, task):
Emote.globalEmote.doEmote(npc, TTEmote.Emotes.index(random.choice(self.RandomEmotes)), 0)
task.delayTime = npc.emoteTrack.getDuration() + 1.0
return task.again<|fim▁end|> | delete |
<|file_name|>TutorialTVScenes.py<|end_file_name|><|fim▁begin|># Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.tutorial.TutorialTVScenes
from panda3d.core import Camera
from direct.task.Task import Task
from otp.avatar import Emote
from toontown.television.TVScenes import *
from toontown.television.TVEffects import *
from toontown.suit.Suit import Suit
from toontown.suit.BossCog import BossCog
from toontown.suit.SuitDNA import SuitDNA
from toontown.toon import NPCToons, TTEmote
import random
class CEOScene(ThreeDScene):
CameraPos = [(0, 203.5, 23.5, 0, 350, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'CEOScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BanquetInterior_1')
self.geom.reparentTo(self)
self.ceo = BossCog()
dna = SuitDNA()
dna.newBossCog('c')
self.ceo.setDNA(dna)
self.ceo.reparentTo(self)
self.ceo.setPosHpr(0, 236.5, 0, 180, 0, 0)
self.ceo.loop('Bb_neutral')
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.ceo:
self.ceo.delete()
self.ceo = None
ThreeDScene.delete(self)
return
class HeadHunterScene(ThreeDScene):
CameraPos = [(-22, -12.5, 7, 92, -6, 0)]
def <|fim_middle|>(self, effects = []):
ThreeDScene.__init__(self, 'HeadHunterScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BossbotEntranceRoom')
self.geom.reparentTo(self)
self.cog = Suit()
dna = SuitDNA()
dna.newSuit('hh')
self.cog.setDNA(dna)
self.cog.reparentTo(self)
self.cog.setPosHpr(-32.5, -12.5, 0.02, 270, 0, 0)
self.cog.nametag3d.removeNode()
self.cog.nametag.destroy()
self.cog.loop('neutral')
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.cog:
self.cog.delete()
self.cog = None
ThreeDScene.delete(self)
return
class ScientistScene(ThreeDScene):
CameraPos = [(-47.5, 0.5, 3.415, 90, 0, 0)]
ToonPos = {2018: (-59, -1.5, 0.02, 270, 0, 0),
2019: (-59, 0.5, 0.02, 270, 0, 0),
2020: (-59, 2.5, 0.02, 270, 0, 0)}
RandomEmotes = ['wave',
'angry',
'applause',
'cringe',
'confused',
'slip-forward',
'slip-backward',
'resistance-salute',
'surprise',
'cry',
'furious',
'laugh',
'idea',
'taunt',
'rage']
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'ScientistScene', effects)
self.geom = loader.loadModel('phase_3.5/models/modules/tt_m_ara_int_toonhall')
self.geom.reparentTo(self)
self.taskStarted = False
self.npcs = []
for id, posHpr in self.ToonPos.iteritems():
npc = NPCToons.createLocalNPC(id)
npc.reparentTo(self.geom)
npc.setPosHpr(*posHpr)
npc.nametag3d.removeNode()
npc.nametag.destroy()
self.npcs.append(npc)
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
npc.delete()
self.npcs = []
self.taskStarted = False
ThreeDScene.delete(self)
return
def startTask(self):
if self.taskStarted:
return
for i, npc in enumerate(self.npcs):
taskMgr.doMethodLater(0.25 * i, lambda task, npc = npc: self.doRandomEmote(npc, task), npc.uniqueName('randomEmote'))
self.taskStarted = True
def stopTask(self):
if not self.taskStarted:
return
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
self.taskStarted = False
def doRandomEmote(self, npc, task):
Emote.globalEmote.doEmote(npc, TTEmote.Emotes.index(random.choice(self.RandomEmotes)), 0)
task.delayTime = npc.emoteTrack.getDuration() + 1.0
return task.again<|fim▁end|> | __init__ |
<|file_name|>TutorialTVScenes.py<|end_file_name|><|fim▁begin|># Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.tutorial.TutorialTVScenes
from panda3d.core import Camera
from direct.task.Task import Task
from otp.avatar import Emote
from toontown.television.TVScenes import *
from toontown.television.TVEffects import *
from toontown.suit.Suit import Suit
from toontown.suit.BossCog import BossCog
from toontown.suit.SuitDNA import SuitDNA
from toontown.toon import NPCToons, TTEmote
import random
class CEOScene(ThreeDScene):
CameraPos = [(0, 203.5, 23.5, 0, 350, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'CEOScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BanquetInterior_1')
self.geom.reparentTo(self)
self.ceo = BossCog()
dna = SuitDNA()
dna.newBossCog('c')
self.ceo.setDNA(dna)
self.ceo.reparentTo(self)
self.ceo.setPosHpr(0, 236.5, 0, 180, 0, 0)
self.ceo.loop('Bb_neutral')
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.ceo:
self.ceo.delete()
self.ceo = None
ThreeDScene.delete(self)
return
class HeadHunterScene(ThreeDScene):
CameraPos = [(-22, -12.5, 7, 92, -6, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'HeadHunterScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BossbotEntranceRoom')
self.geom.reparentTo(self)
self.cog = Suit()
dna = SuitDNA()
dna.newSuit('hh')
self.cog.setDNA(dna)
self.cog.reparentTo(self)
self.cog.setPosHpr(-32.5, -12.5, 0.02, 270, 0, 0)
self.cog.nametag3d.removeNode()
self.cog.nametag.destroy()
self.cog.loop('neutral')
def <|fim_middle|>(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.cog:
self.cog.delete()
self.cog = None
ThreeDScene.delete(self)
return
class ScientistScene(ThreeDScene):
CameraPos = [(-47.5, 0.5, 3.415, 90, 0, 0)]
ToonPos = {2018: (-59, -1.5, 0.02, 270, 0, 0),
2019: (-59, 0.5, 0.02, 270, 0, 0),
2020: (-59, 2.5, 0.02, 270, 0, 0)}
RandomEmotes = ['wave',
'angry',
'applause',
'cringe',
'confused',
'slip-forward',
'slip-backward',
'resistance-salute',
'surprise',
'cry',
'furious',
'laugh',
'idea',
'taunt',
'rage']
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'ScientistScene', effects)
self.geom = loader.loadModel('phase_3.5/models/modules/tt_m_ara_int_toonhall')
self.geom.reparentTo(self)
self.taskStarted = False
self.npcs = []
for id, posHpr in self.ToonPos.iteritems():
npc = NPCToons.createLocalNPC(id)
npc.reparentTo(self.geom)
npc.setPosHpr(*posHpr)
npc.nametag3d.removeNode()
npc.nametag.destroy()
self.npcs.append(npc)
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
npc.delete()
self.npcs = []
self.taskStarted = False
ThreeDScene.delete(self)
return
def startTask(self):
if self.taskStarted:
return
for i, npc in enumerate(self.npcs):
taskMgr.doMethodLater(0.25 * i, lambda task, npc = npc: self.doRandomEmote(npc, task), npc.uniqueName('randomEmote'))
self.taskStarted = True
def stopTask(self):
if not self.taskStarted:
return
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
self.taskStarted = False
def doRandomEmote(self, npc, task):
Emote.globalEmote.doEmote(npc, TTEmote.Emotes.index(random.choice(self.RandomEmotes)), 0)
task.delayTime = npc.emoteTrack.getDuration() + 1.0
return task.again<|fim▁end|> | delete |
<|file_name|>TutorialTVScenes.py<|end_file_name|><|fim▁begin|># Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.tutorial.TutorialTVScenes
from panda3d.core import Camera
from direct.task.Task import Task
from otp.avatar import Emote
from toontown.television.TVScenes import *
from toontown.television.TVEffects import *
from toontown.suit.Suit import Suit
from toontown.suit.BossCog import BossCog
from toontown.suit.SuitDNA import SuitDNA
from toontown.toon import NPCToons, TTEmote
import random
class CEOScene(ThreeDScene):
CameraPos = [(0, 203.5, 23.5, 0, 350, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'CEOScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BanquetInterior_1')
self.geom.reparentTo(self)
self.ceo = BossCog()
dna = SuitDNA()
dna.newBossCog('c')
self.ceo.setDNA(dna)
self.ceo.reparentTo(self)
self.ceo.setPosHpr(0, 236.5, 0, 180, 0, 0)
self.ceo.loop('Bb_neutral')
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.ceo:
self.ceo.delete()
self.ceo = None
ThreeDScene.delete(self)
return
class HeadHunterScene(ThreeDScene):
CameraPos = [(-22, -12.5, 7, 92, -6, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'HeadHunterScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BossbotEntranceRoom')
self.geom.reparentTo(self)
self.cog = Suit()
dna = SuitDNA()
dna.newSuit('hh')
self.cog.setDNA(dna)
self.cog.reparentTo(self)
self.cog.setPosHpr(-32.5, -12.5, 0.02, 270, 0, 0)
self.cog.nametag3d.removeNode()
self.cog.nametag.destroy()
self.cog.loop('neutral')
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.cog:
self.cog.delete()
self.cog = None
ThreeDScene.delete(self)
return
class ScientistScene(ThreeDScene):
CameraPos = [(-47.5, 0.5, 3.415, 90, 0, 0)]
ToonPos = {2018: (-59, -1.5, 0.02, 270, 0, 0),
2019: (-59, 0.5, 0.02, 270, 0, 0),
2020: (-59, 2.5, 0.02, 270, 0, 0)}
RandomEmotes = ['wave',
'angry',
'applause',
'cringe',
'confused',
'slip-forward',
'slip-backward',
'resistance-salute',
'surprise',
'cry',
'furious',
'laugh',
'idea',
'taunt',
'rage']
def <|fim_middle|>(self, effects = []):
ThreeDScene.__init__(self, 'ScientistScene', effects)
self.geom = loader.loadModel('phase_3.5/models/modules/tt_m_ara_int_toonhall')
self.geom.reparentTo(self)
self.taskStarted = False
self.npcs = []
for id, posHpr in self.ToonPos.iteritems():
npc = NPCToons.createLocalNPC(id)
npc.reparentTo(self.geom)
npc.setPosHpr(*posHpr)
npc.nametag3d.removeNode()
npc.nametag.destroy()
self.npcs.append(npc)
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
npc.delete()
self.npcs = []
self.taskStarted = False
ThreeDScene.delete(self)
return
def startTask(self):
if self.taskStarted:
return
for i, npc in enumerate(self.npcs):
taskMgr.doMethodLater(0.25 * i, lambda task, npc = npc: self.doRandomEmote(npc, task), npc.uniqueName('randomEmote'))
self.taskStarted = True
def stopTask(self):
if not self.taskStarted:
return
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
self.taskStarted = False
def doRandomEmote(self, npc, task):
Emote.globalEmote.doEmote(npc, TTEmote.Emotes.index(random.choice(self.RandomEmotes)), 0)
task.delayTime = npc.emoteTrack.getDuration() + 1.0
return task.again<|fim▁end|> | __init__ |
<|file_name|>TutorialTVScenes.py<|end_file_name|><|fim▁begin|># Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.tutorial.TutorialTVScenes
from panda3d.core import Camera
from direct.task.Task import Task
from otp.avatar import Emote
from toontown.television.TVScenes import *
from toontown.television.TVEffects import *
from toontown.suit.Suit import Suit
from toontown.suit.BossCog import BossCog
from toontown.suit.SuitDNA import SuitDNA
from toontown.toon import NPCToons, TTEmote
import random
class CEOScene(ThreeDScene):
CameraPos = [(0, 203.5, 23.5, 0, 350, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'CEOScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BanquetInterior_1')
self.geom.reparentTo(self)
self.ceo = BossCog()
dna = SuitDNA()
dna.newBossCog('c')
self.ceo.setDNA(dna)
self.ceo.reparentTo(self)
self.ceo.setPosHpr(0, 236.5, 0, 180, 0, 0)
self.ceo.loop('Bb_neutral')
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.ceo:
self.ceo.delete()
self.ceo = None
ThreeDScene.delete(self)
return
class HeadHunterScene(ThreeDScene):
CameraPos = [(-22, -12.5, 7, 92, -6, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'HeadHunterScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BossbotEntranceRoom')
self.geom.reparentTo(self)
self.cog = Suit()
dna = SuitDNA()
dna.newSuit('hh')
self.cog.setDNA(dna)
self.cog.reparentTo(self)
self.cog.setPosHpr(-32.5, -12.5, 0.02, 270, 0, 0)
self.cog.nametag3d.removeNode()
self.cog.nametag.destroy()
self.cog.loop('neutral')
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.cog:
self.cog.delete()
self.cog = None
ThreeDScene.delete(self)
return
class ScientistScene(ThreeDScene):
CameraPos = [(-47.5, 0.5, 3.415, 90, 0, 0)]
ToonPos = {2018: (-59, -1.5, 0.02, 270, 0, 0),
2019: (-59, 0.5, 0.02, 270, 0, 0),
2020: (-59, 2.5, 0.02, 270, 0, 0)}
RandomEmotes = ['wave',
'angry',
'applause',
'cringe',
'confused',
'slip-forward',
'slip-backward',
'resistance-salute',
'surprise',
'cry',
'furious',
'laugh',
'idea',
'taunt',
'rage']
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'ScientistScene', effects)
self.geom = loader.loadModel('phase_3.5/models/modules/tt_m_ara_int_toonhall')
self.geom.reparentTo(self)
self.taskStarted = False
self.npcs = []
for id, posHpr in self.ToonPos.iteritems():
npc = NPCToons.createLocalNPC(id)
npc.reparentTo(self.geom)
npc.setPosHpr(*posHpr)
npc.nametag3d.removeNode()
npc.nametag.destroy()
self.npcs.append(npc)
def <|fim_middle|>(self):
if self.geom:
self.geom.removeNode()
self.geom = None
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
npc.delete()
self.npcs = []
self.taskStarted = False
ThreeDScene.delete(self)
return
def startTask(self):
if self.taskStarted:
return
for i, npc in enumerate(self.npcs):
taskMgr.doMethodLater(0.25 * i, lambda task, npc = npc: self.doRandomEmote(npc, task), npc.uniqueName('randomEmote'))
self.taskStarted = True
def stopTask(self):
if not self.taskStarted:
return
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
self.taskStarted = False
def doRandomEmote(self, npc, task):
Emote.globalEmote.doEmote(npc, TTEmote.Emotes.index(random.choice(self.RandomEmotes)), 0)
task.delayTime = npc.emoteTrack.getDuration() + 1.0
return task.again<|fim▁end|> | delete |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.