Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def install(ctx, integrations, delete_after_install=False):
logger.debug("running command %s (%s)", ctx.command.name, ctx.params,
extra={"command": ctx.command.name, "params": ctx.params})
home = ctx.obj["HOME"]
integrations_path = os.path.... | [
"Install a honeycomb integration from the online library, local path or zipfile."
] |
Please provide a description of the function:def configure(ctx, integration, args, show_args, editable):
home = ctx.obj["HOME"]
integration_path = plugin_utils.get_plugin_path(home, defs.INTEGRATIONS, integration, editable)
logger.debug("running command %s (%s)", ctx.command.name, ctx.params,
... | [
"Configure an integration with default parameters.\n\n You can still provide one-off integration arguments to :func:`honeycomb.commands.service.run` if required.\n "
] |
Please provide a description of the function:def get_match_history(self, account_id=None, **kwargs):
if 'account_id' not in kwargs:
kwargs['account_id'] = account_id
url = self.__build_url(urls.GET_MATCH_HISTORY, **kwargs)
req = self.executor(url)
if self.logger:
... | [
"Returns a dictionary containing a list of the most recent Dota matches\n\n :param account_id: (int, optional)\n :param hero_id: (int, optional)\n :param game_mode: (int, optional) see ``ref/modes.json``\n :param skill: (int, optional) see ``ref/skill.json``\n :param min_players: ... |
Please provide a description of the function:def get_match_history_by_seq_num(self, start_at_match_seq_num=None, **kwargs):
if 'start_at_match_seq_num' not in kwargs:
kwargs['start_at_match_seq_num'] = start_at_match_seq_num
url = self.__build_url(urls.GET_MATCH_HISTORY_BY_SEQ_NUM, ... | [
"Returns a dictionary containing a list of Dota matches in the order they were recorded\n\n :param start_at_match_seq_num: (int, optional) start at matches equal to or\n older than this match id\n :param matches_requested: (int, optional) defaults to ``100``\n :return: dictionary of ... |
Please provide a description of the function:def get_match_details(self, match_id=None, **kwargs):
if 'match_id' not in kwargs:
kwargs['match_id'] = match_id
url = self.__build_url(urls.GET_MATCH_DETAILS, **kwargs)
req = self.executor(url)
if self.logger:
... | [
"Returns a dictionary containing the details for a Dota 2 match\n\n :param match_id: (int, optional)\n :return: dictionary of matches, see :doc:`responses </responses>`\n "
] |
Please provide a description of the function:def get_league_listing(self):
url = self.__build_url(urls.GET_LEAGUE_LISTING)
req = self.executor(url)
if self.logger:
self.logger.info('URL: {0}'.format(url))
if not self.__check_http_err(req.status_code):
ret... | [
"Returns a dictionary containing a list of all ticketed leagues\n\n :return: dictionary of ticketed leagues, see :doc:`responses </responses>`\n "
] |
Please provide a description of the function:def get_live_league_games(self):
url = self.__build_url(urls.GET_LIVE_LEAGUE_GAMES)
req = self.executor(url)
if self.logger:
self.logger.info('URL: {0}'.format(url))
if not self.__check_http_err(req.status_code):
... | [
"Returns a dictionary containing a list of ticked games in progress\n\n :return: dictionary of live games, see :doc:`responses </responses>`\n "
] |
Please provide a description of the function:def get_team_info_by_team_id(self, start_at_team_id=None, **kwargs):
if 'start_at_team_id' not in kwargs:
kwargs['start_at_team_id'] = start_at_team_id
url = self.__build_url(urls.GET_TEAM_INFO_BY_TEAM_ID, **kwargs)
req = self.exe... | [
"Returns a dictionary containing a in-game teams\n\n :param start_at_team_id: (int, optional)\n :param teams_requested: (int, optional)\n :return: dictionary of teams, see :doc:`responses </responses>`\n "
] |
Please provide a description of the function:def get_player_summaries(self, steamids=None, **kwargs):
if not isinstance(steamids, collections.Iterable):
steamids = [steamids]
base64_ids = list(map(convert_to_64_bit, filter(lambda x: x is not None, steamids)))
if 'steamids'... | [
"Returns a dictionary containing a player summaries\n\n :param steamids: (list) list of ``32-bit`` or ``64-bit`` steam ids, notice\n that api will convert if ``32-bit`` are given\n :return: dictionary of player summaries, see :doc:`responses </responses>`\n "
] |
Please provide a description of the function:def get_heroes(self, **kwargs):
url = self.__build_url(urls.GET_HEROES, language=self.language, **kwargs)
req = self.executor(url)
if self.logger:
self.logger.info('URL: {0}'.format(url))
if not self.__check_http_err(req.s... | [
"Returns a dictionary of in-game heroes, used to parse ids into localised names\n\n :return: dictionary of heroes, see :doc:`responses </responses>`\n "
] |
Please provide a description of the function:def get_tournament_prize_pool(self, leagueid=None, **kwargs):
if 'leagueid' not in kwargs:
kwargs['leagueid'] = leagueid
url = self.__build_url(urls.GET_TOURNAMENT_PRIZE_POOL, **kwargs)
req = self.executor(url)
if self.log... | [
"Returns a dictionary that includes community funded tournament prize pools\n\n :param leagueid: (int, optional)\n :return: dictionary of prize pools, see :doc:`responses </responses>`\n "
] |
Please provide a description of the function:def get_top_live_games(self, partner='', **kwargs):
if 'partner' not in kwargs:
kwargs['partner'] = partner
url = self.__build_url(urls.GET_TOP_LIVE_GAME, **kwargs)
req = self.executor(url)
if self.logger:
self... | [
"Returns a dictionary that includes top MMR live games\n\n :param partner: (int, optional)\n :return: dictionary of prize pools, see :doc:`responses </responses>`\n "
] |
Please provide a description of the function:def __build_url(self, api_call, **kwargs):
kwargs['key'] = self.api_key
if 'language' not in kwargs:
kwargs['language'] = self.language
if 'format' not in kwargs:
kwargs['format'] = self.__format
api_query = ur... | [
"Builds the api query"
] |
Please provide a description of the function:def __check_http_err(self, status_code):
if status_code == 403:
raise exceptions.APIAuthenticationError(self.api_key)
elif status_code == 503:
raise exceptions.APITimeoutError()
else:
return False | [
"Raises an exception if we get a http error"
] |
Please provide a description of the function:def hero_id(response):
for player in response['players']:
for hero in heroes['heroes']:
if hero['id'] == player['hero_id']:
player['hero_name'] = hero['localized_name']
return response | [
"\n Parse the lobby, will be available as ``hero_name``\n "
] |
Please provide a description of the function:def leaver(response):
for player in response['players']:
for leaver in leavers:
if leaver['id'] == player['leaver_status']:
player['leaver_status_name'] = leaver['name']
player['leaver_status_description'] = leaver... | [
"\n Parse the lobby, will be available as ``hero_name``\n "
] |
Please provide a description of the function:def item_id(response):
dict_keys = ['item_0', 'item_1', 'item_2',
'item_3', 'item_4', 'item_5']
new_keys = ['item_0_name', 'item_1_name', 'item_2_name',
'item_3_name', 'item_4_name', 'item_5_name']
for player in response['pl... | [
"\n Parse the item ids, will be available as ``item_0_name``, ``item_1_name``,\n ``item_2_name`` and so on\n "
] |
Please provide a description of the function:def get_reviews(obj):
ctype = ContentType.objects.get_for_model(obj)
return models.Review.objects.filter(content_type=ctype, object_id=obj.id) | [
"Simply returns the reviews for an object."
] |
Please provide a description of the function:def get_review_average(obj):
total = 0
reviews = get_reviews(obj)
if not reviews:
return False
for review in reviews:
average = review.get_average_rating()
if average:
total += review.get_average_rating()
if total ... | [
"Returns the review average for an object."
] |
Please provide a description of the function:def render_category_averages(obj, normalize_to=100):
context = {'reviewed_item': obj}
ctype = ContentType.objects.get_for_model(obj)
reviews = models.Review.objects.filter(
content_type=ctype, object_id=obj.id)
category_averages = {}
for revi... | [
"Renders all the sub-averages for each category."
] |
Please provide a description of the function:def total_review_average(obj, normalize_to=100):
ctype = ContentType.objects.get_for_model(obj)
total_average = 0
reviews = models.Review.objects.filter(
content_type=ctype, object_id=obj.id)
for review in reviews:
total_average += review... | [
"Returns the average for all reviews of the given object."
] |
Please provide a description of the function:def user_has_reviewed(obj, user):
ctype = ContentType.objects.get_for_model(obj)
try:
models.Review.objects.get(user=user, content_type=ctype,
object_id=obj.id)
except models.Review.DoesNotExist:
return False... | [
"Returns True if the user has already reviewed the object."
] |
Please provide a description of the function:def datetime(self) -> hints.Datetime:
mills = self.int
return datetime.datetime.utcfromtimestamp(mills // 1000.0).replace(microsecond=mills % 1000 * 1000) | [
"\n Creates a :class:`~datetime.datetime` instance (assumes UTC) from the Unix time value of the timestamp\n with millisecond precision.\n\n :return: Timestamp in datetime form.\n :rtype: :class:`~datetime.datetime`\n "
] |
Please provide a description of the function:def new() -> ulid.ULID:
timestamp = int(time.time() * 1000).to_bytes(6, byteorder='big')
randomness = os.urandom(10)
return ulid.ULID(timestamp + randomness) | [
"\n Create a new :class:`~ulid.ulid.ULID` instance.\n\n The timestamp is created from :func:`~time.time`.\n The randomness is created from :func:`~os.urandom`.\n\n :return: ULID from current timestamp\n :rtype: :class:`~ulid.ulid.ULID`\n "
] |
Please provide a description of the function:def parse(value: ULIDPrimitive) -> ulid.ULID:
if isinstance(value, ulid.ULID):
return value
if isinstance(value, uuid.UUID):
return from_uuid(value)
if isinstance(value, str):
len_value = len(value)
if len_value == 36:
... | [
"\n Create a new :class:`~ulid.ulid.ULID` instance from the given value.\n\n .. note:: This method should only be used when the caller is trying to parse a ULID from\n a value when they're unsure what format/primitive type it will be given in.\n\n :param value: ULID value of any supported type\n :typ... |
Please provide a description of the function:def from_bytes(value: hints.Buffer) -> ulid.ULID:
length = len(value)
if length != 16:
raise ValueError('Expects bytes to be 128 bits; got {} bytes'.format(length))
return ulid.ULID(value) | [
"\n Create a new :class:`~ulid.ulid.ULID` instance from the given :class:`~bytes`,\n :class:`~bytearray`, or :class:`~memoryview` value.\n\n :param value: 16 bytes\n :type value: :class:`~bytes`, :class:`~bytearray`, or :class:`~memoryview`\n :return: ULID from buffer value\n :rtype: :class:`~ulid... |
Please provide a description of the function:def from_int(value: int) -> ulid.ULID:
if value < 0:
raise ValueError('Expects positive integer')
length = (value.bit_length() + 7) // 8
if length > 16:
raise ValueError('Expects integer to be 128 bits; got {} bytes'.format(length))
ret... | [
"\n Create a new :class:`~ulid.ulid.ULID` instance from the given :class:`~int` value.\n\n :param value: 128 bit integer\n :type value: :class:`~int`\n :return: ULID from integer value\n :rtype: :class:`~ulid.ulid.ULID`\n :raises ValueError: when the value is not a 128 bit integer\n "
] |
Please provide a description of the function:def from_str(value: str) -> ulid.ULID:
return ulid.ULID(base32.decode_ulid(value)) | [
"\n Create a new :class:`~ulid.ulid.ULID` instance from the given :class:`~str` value.\n\n :param value: Base32 encoded string\n :type value: :class:`~str`\n :return: ULID from string value\n :rtype: :class:`~ulid.ulid.ULID`\n :raises ValueError: when the value is not 26 characters or malformed\n ... |
Please provide a description of the function:def from_uuid(value: uuid.UUID) -> ulid.ULID:
return ulid.ULID(value.bytes) | [
"\n Create a new :class:`~ulid.ulid.ULID` instance from the given :class:`~uuid.UUID` value.\n\n :param value: UUIDv4 value\n :type value: :class:`~uuid.UUID`\n :return: ULID from UUID value\n :rtype: :class:`~ulid.ulid.ULID`\n "
] |
Please provide a description of the function:def from_timestamp(timestamp: TimestampPrimitive) -> ulid.ULID:
if isinstance(timestamp, datetime.datetime):
timestamp = timestamp.timestamp()
if isinstance(timestamp, (int, float)):
timestamp = int(timestamp * 1000.0).to_bytes(6, byteorder='big'... | [
"\n Create a new :class:`~ulid.ulid.ULID` instance using a timestamp value of a supported type.\n\n The following types are supported for timestamp values:\n\n * :class:`~datetime.datetime`\n * :class:`~int`\n * :class:`~float`\n * :class:`~str`\n * :class:`~memoryview`\n * :class:`~ulid.uli... |
Please provide a description of the function:def from_randomness(randomness: RandomnessPrimitive) -> ulid.ULID:
if isinstance(randomness, (int, float)):
randomness = int(randomness).to_bytes(10, byteorder='big')
elif isinstance(randomness, str):
randomness = base32.decode_randomness(randomn... | [
"\n Create a new :class:`~ulid.ulid.ULID` instance using the given randomness value of a supported type.\n\n The following types are supported for randomness values:\n\n * :class:`~int`\n * :class:`~float`\n * :class:`~str`\n * :class:`~memoryview`\n * :class:`~ulid.ulid.Randomness`\n * :cla... |
Please provide a description of the function:def encode(value: hints.Buffer) -> str:
length = len(value)
# Order here is based on assumed hot path.
if length == 16:
return encode_ulid(value)
if length == 6:
return encode_timestamp(value)
if length == 10:
return encode_r... | [
"\n Encode the given :class:`~bytes` instance to a :class:`~str` using Base32 encoding.\n\n .. note:: You should only use this method if you've got a :class:`~bytes` instance\n and you are unsure of what it represents. If you know the the _meaning_ of the\n :class:`~bytes` instance, you should c... |
Please provide a description of the function:def encode_ulid(value: hints.Buffer) -> str:
length = len(value)
if length != 16:
raise ValueError('Expects 16 bytes for timestamp + randomness; got {}'.format(length))
encoding = ENCODING
return \
encoding[(value[0] & 224) >> 5] + \
... | [
"\n Encode the given buffer to a :class:`~str` using Base32 encoding.\n\n .. note:: This uses an optimized strategy from the `NUlid` project for encoding ULID\n bytes specifically and is not meant for arbitrary encoding.\n\n :param value: Bytes to encode\n :type value: :class:`~bytes`, :class:`~b... |
Please provide a description of the function:def encode_timestamp(timestamp: hints.Buffer) -> str:
length = len(timestamp)
if length != 6:
raise ValueError('Expects 6 bytes for timestamp; got {}'.format(length))
encoding = ENCODING
return \
encoding[(timestamp[0] & 224) >> 5] + \
... | [
"\n Encode the given buffer to a :class:`~str` using Base32 encoding.\n\n The given :class:`~bytes` are expected to represent the first 6 bytes of a ULID, which\n are a timestamp in milliseconds.\n\n .. note:: This uses an optimized strategy from the `NUlid` project for encoding ULID\n bytes spec... |
Please provide a description of the function:def encode_randomness(randomness: hints.Buffer) -> str:
length = len(randomness)
if length != 10:
raise ValueError('Expects 10 bytes for randomness; got {}'.format(length))
encoding = ENCODING
return \
encoding[(randomness[0] & 248) >> ... | [
"\n Encode the given buffer to a :class:`~str` using Base32 encoding.\n\n The given :class:`~bytes` are expected to represent the last 10 bytes of a ULID, which\n are cryptographically secure random values.\n\n .. note:: This uses an optimized strategy from the `NUlid` project for encoding ULID\n ... |
Please provide a description of the function:def decode(value: str) -> bytes:
length = len(value)
# Order here is based on assumed hot path.
if length == 26:
return decode_ulid(value)
if length == 10:
return decode_timestamp(value)
if length == 16:
return decode_randomn... | [
"\n Decode the given Base32 encoded :class:`~str` instance to :class:`~bytes`.\n\n .. note:: You should only use this method if you've got a :class:`~str` instance\n and you are unsure of what it represents. If you know the the _meaning_ of the\n :class:`~str` instance, you should call the `deco... |
Please provide a description of the function:def decode_ulid(value: str) -> bytes:
encoded = str_to_bytes(value, 26)
decoding = DECODING
return bytes((
((decoding[encoded[0]] << 5) | decoding[encoded[1]]) & 0xFF,
((decoding[encoded[2]] << 3) | (decoding[encoded[3]] >> 2)) & 0xFF,
... | [
"\n Decode the given Base32 encoded :class:`~str` instance to :class:`~bytes`.\n\n .. note:: This uses an optimized strategy from the `NUlid` project for decoding ULID\n strings specifically and is not meant for arbitrary decoding.\n\n :param value: String to decode\n :type value: :class:`~str`\n... |
Please provide a description of the function:def decode_timestamp(timestamp: str) -> bytes:
encoded = str_to_bytes(timestamp, 10)
decoding = DECODING
return bytes((
((decoding[encoded[0]] << 5) | decoding[encoded[1]]) & 0xFF,
((decoding[encoded[2]] << 3) | (decoding[encoded[3]] >> 2))... | [
"\n Decode the given Base32 encoded :class:`~str` instance to :class:`~bytes`.\n\n The given :class:`~str` are expected to represent the first 10 characters of a ULID, which\n are the timestamp in milliseconds.\n\n .. note:: This uses an optimized strategy from the `NUlid` project for decoding ULID\n ... |
Please provide a description of the function:def decode_randomness(randomness: str) -> bytes:
encoded = str_to_bytes(randomness, 16)
decoding = DECODING
return bytes((
((decoding[encoded[0]] << 3) | (decoding[encoded[1]] >> 2)) & 0xFF,
((decoding[encoded[1]] << 6) | (decoding[encoded[... | [
"\n Decode the given Base32 encoded :class:`~str` instance to :class:`~bytes`.\n\n The given :class:`~str` are expected to represent the last 16 characters of a ULID, which\n are cryptographically secure random values.\n\n .. note:: This uses an optimized strategy from the `NUlid` project for decoding U... |
Please provide a description of the function:def str_to_bytes(value: str, expected_length: int) -> bytes:
length = len(value)
if length != expected_length:
raise ValueError('Expects {} characters for decoding; got {}'.format(expected_length, length))
try:
encoded = value.encode('ascii'... | [
"\n Convert the given string to bytes and validate it is within the Base32 character set.\n\n :param value: String to convert to bytes\n :type value: :class:`~str`\n :param expected_length: Expected length of the input string\n :type expected_length: :class:`~int`\n :return: Value converted to byt... |
Please provide a description of the function:def get_mac_address(
interface=None, ip=None, ip6=None,
hostname=None, network_request=True
):
# type: (Optional[str], Optional[str], Optional[str], Optional[str], bool) -> Optional[str]
if (hostname and hostname == 'localhost') or (ip and ip == ... | [
"Get a Unicast IEEE 802 MAC-48 address from a local interface or remote host.\n\n You must only use one of the first four arguments. If none of the arguments\n are selected, the default network interface for the system will be used.\n\n Exceptions will be handled silently and returned as a None.\n For t... |
Please provide a description of the function:def _hunt_for_mac(to_find, type_of_thing, net_ok=True):
# type: (Optional[str], int, bool) -> Optional[str]
if to_find is None:
log.warning("_hunt_for_mac() failed: to_find is None")
return None
if not PY2 and isinstance(to_find, bytes):
... | [
"Tries a variety of methods to get a MAC address.\n\n Format of method lists:\n Tuple: (regex, regex index, command, command args)\n Command args is a list of strings to attempt to use as arguments\n lambda: Function to call\n "
] |
Please provide a description of the function:def _try_methods(methods, to_find=None):
# type: (list, Optional[str]) -> Optional[str]
found = None
for m in methods:
try:
if isinstance(m, tuple):
for arg in m[3]: # list(str)
if DEBUG:
... | [
"Runs the methods specified by _hunt_for_mac().\n\n We try every method and see if it returned a MAC address. If it returns\n None or raises an exception, we continue and try the next method.\n "
] |
Please provide a description of the function:def _get_default_iface_linux():
# type: () -> Optional[str]
data = _read_file('/proc/net/route')
if data is not None and len(data) > 1:
for line in data.split('\n')[1:-1]:
iface_name, dest = line.split('\t')[:2]
if dest == '00... | [
"Get the default interface by reading /proc/net/route.\n\n This is the same source as the `route` command, however it's much\n faster to read this file than to call `route`. If it fails for whatever\n reason, we can fall back on the system commands (e.g for a platform\n that has a route command, but may... |
Please provide a description of the function:def package_version():
version_path = os.path.join(os.path.dirname(__file__), 'version.py')
version = read_version(version_path)
write_version(version_path, version)
return version | [
"Get the package version via Git Tag."
] |
Please provide a description of the function:def waitforqueues(queues, timeout=None):
lock = threading.Condition(threading.Lock())
prepare_queues(queues, lock)
try:
wait_queues(queues, lock, timeout)
finally:
reset_queues(queues)
return filter(lambda q: not q.empty(), queues) | [
"Waits for one or more *Queue* to be ready or until *timeout* expires.\n\n *queues* is a list containing one or more *Queue.Queue* objects.\n If *timeout* is not None the function will block\n for the specified amount of seconds.\n\n The function returns a list containing the ready *Queues*.\n\n "
] |
Please provide a description of the function:def prepare_queues(queues, lock):
for queue in queues:
queue._pebble_lock = lock
with queue.mutex:
queue._pebble_old_method = queue._put
queue._put = MethodType(new_method, queue) | [
"Replaces queue._put() method in order to notify the waiting Condition."
] |
Please provide a description of the function:def reset_queues(queues):
for queue in queues:
with queue.mutex:
queue._put = queue._pebble_old_method
delattr(queue, '_pebble_old_method')
delattr(queue, '_pebble_lock') | [
"Resets original queue._put() method."
] |
Please provide a description of the function:def waitforthreads(threads, timeout=None):
old_function = None
lock = threading.Condition(threading.Lock())
def new_function(*args):
old_function(*args)
with lock:
lock.notify_all()
old_function = prepare_threads(new_functio... | [
"Waits for one or more *Thread* to exit or until *timeout* expires.\n\n .. note::\n\n Expired *Threads* are not joined by *waitforthreads*.\n\n *threads* is a list containing one or more *threading.Thread* objects.\n If *timeout* is not None the function will block\n for the specified amount of se... |
Please provide a description of the function:def prepare_threads(new_function):
with _waitforthreads_lock:
if hasattr(threading, 'get_ident'):
old_function = threading.get_ident
threading.get_ident = new_function
else:
old_function = threading._get_ident
... | [
"Replaces threading._get_ident() function in order to notify\n the waiting Condition."
] |
Please provide a description of the function:def reset_threads(old_function):
with _waitforthreads_lock:
if hasattr(threading, 'get_ident'):
threading.get_ident = old_function
else:
threading._get_ident = old_function | [
"Resets original threading._get_ident() function."
] |
Please provide a description of the function:def synchronized(*args):
if callable(args[0]):
return decorate_synchronized(args[0], _synchronized_lock)
else:
def wrap(function):
return decorate_synchronized(function, args[0])
return wrap | [
"A synchronized function prevents two or more callers to interleave\n its execution preventing race conditions.\n\n The synchronized decorator accepts as optional parameter a Lock, RLock or\n Semaphore object which will be employed to ensure the function's atomicity.\n\n If no synchronization object is ... |
Please provide a description of the function:def sighandler(signals):
def wrap(function):
set_signal_handlers(signals, function)
@wraps(function)
def wrapper(*args, **kwargs):
return function(*args, **kwargs)
return wrapper
return wrap | [
"Sets the decorated function as signal handler of given *signals*.\n\n *signals* can be either a single signal or a list/tuple\n of multiple ones.\n\n "
] |
Please provide a description of the function:def worker_thread(context):
queue = context.task_queue
parameters = context.worker_parameters
if parameters.initializer is not None:
if not run_initializer(parameters.initializer, parameters.initargs):
context.state = ERROR
r... | [
"The worker thread routines."
] |
Please provide a description of the function:def schedule(self, function, args=(), kwargs={}):
self._check_pool_state()
future = Future()
payload = TaskPayload(function, args, kwargs)
task = Task(next(self._task_counter), future, None, payload)
self._context.task_queue... | [
"Schedules *function* to be run the Pool.\n\n *args* and *kwargs* will be forwareded to the scheduled function\n respectively as arguments and keyword arguments.\n\n A *concurrent.futures.Future* object is returned.\n "
] |
Please provide a description of the function:def map(self, function, *iterables, **kwargs):
self._check_pool_state()
timeout = kwargs.get('timeout')
chunksize = kwargs.get('chunksize', 1)
if chunksize < 1:
raise ValueError("chunksize must be >= 1")
futures... | [
"Returns an iterator equivalent to map(function, iterables).\n\n *chunksize* controls the size of the chunks the iterable will\n be broken into before being passed to the function. If None\n the size will be controlled by the Pool.\n\n "
] |
Please provide a description of the function:def stop_process(process):
process.terminate()
process.join(3)
if process.is_alive() and os.name != 'nt':
try:
os.kill(process.pid, signal.SIGKILL)
process.join()
except OSError:
return
if process.is_... | [
"Does its best to stop the process."
] |
Please provide a description of the function:def execute(function, *args, **kwargs):
try:
return function(*args, **kwargs)
except Exception as error:
error.traceback = format_exc()
return error | [
"Runs the given function returning its results or exception."
] |
Please provide a description of the function:def process_execute(function, *args, **kwargs):
try:
return function(*args, **kwargs)
except Exception as error:
error.traceback = format_exc()
return RemoteException(error, error.traceback) | [
"Runs the given function returning its results or exception."
] |
Please provide a description of the function:def send_result(pipe, data):
try:
pipe.send(data)
except (pickle.PicklingError, TypeError) as error:
error.traceback = format_exc()
pipe.send(RemoteException(error, error.traceback)) | [
"Send result handling pickling and communication errors."
] |
Please provide a description of the function:def process(*args, **kwargs):
timeout = kwargs.get('timeout')
# decorator without parameters
if len(args) == 1 and len(kwargs) == 0 and callable(args[0]):
return _process_wrapper(args[0], timeout)
else:
# decorator with parameters
... | [
"Runs the decorated function in a concurrent process,\n taking care of the result and error management.\n\n Decorated functions will return a concurrent.futures.Future object\n once called.\n\n The timeout parameter will set a maximum execution time\n for the decorated function. If the execution exce... |
Please provide a description of the function:def _worker_handler(future, worker, pipe, timeout):
result = _get_result(future, pipe, timeout)
if isinstance(result, BaseException):
if isinstance(result, ProcessExpired):
result.exitcode = worker.exitcode
future.set_exception(resu... | [
"Worker lifecycle manager.\n\n Waits for the worker to be perform its task,\n collects result, runs the callback and cleans up the process.\n\n "
] |
Please provide a description of the function:def _function_handler(function, args, kwargs, pipe):
signal.signal(signal.SIGINT, signal.SIG_IGN)
result = process_execute(function, *args, **kwargs)
send_result(pipe, result) | [
"Runs the actual function in separate process and returns its result."
] |
Please provide a description of the function:def _get_result(future, pipe, timeout):
counter = count(step=SLEEP_UNIT)
try:
while not pipe.poll(SLEEP_UNIT):
if timeout is not None and next(counter) >= timeout:
return TimeoutError('Task Timeout', timeout)
elif... | [
"Waits for result and handles communication errors."
] |
Please provide a description of the function:def _trampoline(name, module, *args, **kwargs):
function = _function_lookup(name, module)
return function(*args, **kwargs) | [
"Trampoline function for decorators.\n\n Lookups the function between the registered ones;\n if not found, forces its registering and then executes it.\n\n "
] |
Please provide a description of the function:def _function_lookup(name, module):
try:
return _registered_functions[name]
except KeyError: # force function registering
__import__(module)
mod = sys.modules[module]
getattr(mod, name)
return _registered_functions[name] | [
"Searches the function between the registered ones.\n If not found, it imports the module forcing its registration.\n\n "
] |
Please provide a description of the function:def worker_process(params, channel):
signal(SIGINT, SIG_IGN)
if params.initializer is not None:
if not run_initializer(params.initializer, params.initargs):
os._exit(1)
try:
for task in worker_get_next_task(channel, params.max_t... | [
"The worker process routines."
] |
Please provide a description of the function:def task_transaction(channel):
with channel.lock:
if channel.poll(0):
task = channel.recv()
channel.send(Acknowledgement(os.getpid(), task.id))
else:
raise RuntimeError("Race condition between workers")
return... | [
"Ensures a task is fetched and acknowledged atomically."
] |
Please provide a description of the function:def schedule(self, task):
self.task_manager.register(task)
self.worker_manager.dispatch(task) | [
"Schedules a new Task in the PoolManager."
] |
Please provide a description of the function:def process_next_message(self, timeout):
message = self.worker_manager.receive(timeout)
if isinstance(message, Acknowledgement):
self.task_manager.task_start(message.task, message.worker)
elif isinstance(message, Result):
... | [
"Processes the next message coming from the workers."
] |
Please provide a description of the function:def update_tasks(self):
for task in self.task_manager.timeout_tasks():
self.task_manager.task_done(
task.id, TimeoutError("Task timeout", task.timeout))
self.worker_manager.stop_worker(task.worker_id)
for task... | [
"Handles timing out Tasks."
] |
Please provide a description of the function:def update_workers(self):
for expiration in self.worker_manager.inspect_workers():
self.handle_worker_expiration(expiration)
self.worker_manager.create_workers() | [
"Handles unexpected processes termination."
] |
Please provide a description of the function:def task_done(self, task_id, result):
try:
task = self.tasks.pop(task_id)
except KeyError:
return # result of previously timeout Task
else:
if task.future.cancelled():
task.set_running_or_n... | [
"Set the tasks result and run the callback."
] |
Please provide a description of the function:def inspect_workers(self):
workers = tuple(self.workers.values())
expired = tuple(w for w in workers if not w.is_alive())
for worker in expired:
self.workers.pop(worker.pid)
return ((w.pid, w.exitcode) for w in expired i... | [
"Updates the workers status.\n\n Returns the workers which have unexpectedly ended.\n\n "
] |
Please provide a description of the function:def iter_chunks(chunksize, *iterables):
iterables = iter(zip(*iterables))
while 1:
chunk = tuple(islice(iterables, chunksize))
if not chunk:
return
yield chunk | [
"Iterates over zipped iterables in chunks."
] |
Please provide a description of the function:def run_initializer(initializer, initargs):
try:
initializer(*initargs)
return True
except Exception as error:
logging.exception(error)
return False | [
"Runs the Pool initializer dealing with errors."
] |
Please provide a description of the function:def join(self, timeout=None):
if self._context.state == RUNNING:
raise RuntimeError('The Pool is still running')
if self._context.state == CLOSED:
self._wait_queue_depletion(timeout)
self.stop()
self.jo... | [
"Joins the pool waiting until all workers exited.\n\n If *timeout* is set, it block until all workers are done\n or raises TimeoutError.\n "
] |
Please provide a description of the function:def cancel(self):
super(MapFuture, self).cancel()
return any(tuple(f.cancel() for f in self._futures)) | [
"Cancel the future.\n\n Returns True if any of the elements of the iterables is cancelled.\n False otherwise.\n "
] |
Please provide a description of the function:def cancel(self):
super(ProcessMapFuture, self).cancel()
return any(tuple(f.cancel() for f in self._futures)) | [
"Cancel the future.\n\n Returns True if any of the elements of the iterables is cancelled.\n False otherwise.\n "
] |
Please provide a description of the function:def thread(function):
@wraps(function)
def wrapper(*args, **kwargs):
future = Future()
launch_thread(_function_handler, function, args, kwargs, future)
return future
return wrapper | [
"Runs the decorated function within a concurrent thread,\n taking care of the result and error management.\n\n Decorated functions will return a concurrent.futures.Future object\n once called.\n\n "
] |
Please provide a description of the function:def _function_handler(function, args, kwargs, future):
future.set_running_or_notify_cancel()
try:
result = function(*args, **kwargs)
except BaseException as error:
error.traceback = format_exc()
future.set_exception(error)
else:
... | [
"Runs the actual function in separate thread and returns its result."
] |
Please provide a description of the function:def post_multipart(host, selector, fields, files):
content_type, body = encode_multipart_formdata(fields, files)
h = httplib.HTTP(host)
h.putrequest('POST', selector)
h.putheader('content-type', content_type)
h.putheader('content-length', str(len(bod... | [
"\n Post fields and files to an http host as multipart/form-data.\n fields is a sequence of (name, value) elements for regular form fields.\n files is a sequence of (name, filename, value) elements for data to be uploaded as files\n Return the server's response page.\n "
] |
Please provide a description of the function:def encode_multipart_formdata(fields, files):
BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$'
CRLF = '\r\n'
L = []
for (key, value) in fields:
L.append('--' + BOUNDARY)
L.append('Content-Disposition: form-data; name="%s"' % key)
L.a... | [
"\n fields is a sequence of (name, value) elements for regular form fields.\n files is a sequence of (name, filename, value) elements for data to be uploaded as files\n Return (content_type, body) ready for httplib.HTTP instance\n "
] |
Please provide a description of the function:def create_cities_csv(filename="places2k.txt", output="cities.csv"):
with open(filename, 'r') as city_file:
with open(output, 'w') as out:
for line in city_file:
# Drop Puerto Rico (just looking for the 50 states)
... | [
"\n Takes the places2k.txt from USPS and creates a simple file of all cities.\n "
] |
Please provide a description of the function:def parse_address(self, address, line_number=-1):
return Address(address, self, line_number, self.logger) | [
"\n Return an Address object from the given address. Passes itself to the Address constructor to use all the custom\n loaded suffixes, cities, etc.\n "
] |
Please provide a description of the function:def load_suffixes(self, filename):
with open(filename, 'r') as f:
for line in f:
# Make sure we have key and value
if len(line.split(',')) != 2:
continue
# Strip off newlines... | [
"\n Build the suffix dictionary. The keys will be possible long versions, and the values will be the\n accepted abbreviations. Everything should be stored using the value version, and you can search all\n by using building a set of self.suffixes.keys() and self.suffixes.values().\n "
] |
Please provide a description of the function:def load_cities(self, filename):
with open(filename, 'r') as f:
for line in f:
self.cities.append(line.strip().lower()) | [
"\n Load up all cities in lowercase for easier matching. The file should have one city per line, with no extra\n characters. This isn't strictly required, but will vastly increase the accuracy.\n "
] |
Please provide a description of the function:def load_streets(self, filename):
with open(filename, 'r') as f:
for line in f:
self.streets.append(line.strip().lower()) | [
"\n Load up all streets in lowercase for easier matching. The file should have one street per line, with no extra\n characters. This isn't strictly required, but will vastly increase the accuracy.\n "
] |
Please provide a description of the function:def preprocess_address(self, address):
# Run some basic cleaning
address = address.replace("# ", "#")
address = address.replace(" & ", "&")
# Clear the address of things like 'X units', which shouldn't be in an address anyway. We won'... | [
"\n Takes a basic address and attempts to clean it up, extract reasonably assured bits that may throw off the\n rest of the parsing, and return the cleaned address.\n "
] |
Please provide a description of the function:def check_zip(self, token):
if self.zip is None:
# print "last matched", self.last_matched
if self.last_matched is not None:
return False
# print "zip check", len(token) == 5, re.match(r"\d{5}", token)
... | [
"\n Returns true if token is matches a zip code (5 numbers). Zip code must be the last token in an address (minus anything\n removed during preprocessing such as --2 units.\n "
] |
Please provide a description of the function:def check_state(self, token):
# print "zip", self.zip
if len(token) == 2 and self.state is None:
if token.capitalize() in self.parser.states.keys():
self.state = self._clean(self.parser.states[token.capitalize()])
... | [
"\n Check if state is in either the keys or values of our states list. Must come before the suffix.\n "
] |
Please provide a description of the function:def check_city(self, token):
shortened_cities = {'saint': 'st.'}
if self.city is None and self.state is not None and self.street_suffix is None:
if token.lower() in self.parser.cities:
self.city = self._clean(token.capital... | [
"\n Check if there is a known city from our city list. Must come before the suffix.\n "
] |
Please provide a description of the function:def check_apartment_number(self, token):
apartment_regexes = [r'#\w+ & \w+', '#\w+ rm \w+', "#\w+-\w", r'apt #{0,1}\w+', r'apartment #{0,1}\w+', r'#\w+',
r'# \w+', r'rm \w+', r'unit #?\w+', r'units #?\w+', r'- #{0,1}\w+', r'no\s?... | [
"\n Finds apartment, unit, #, etc, regardless of spot in string. This needs to come after everything else has been ruled out,\n because it has a lot of false positives.\n "
] |
Please provide a description of the function:def check_street_suffix(self, token):
# Suffix must come before street
# print "Suffix check", token, "suffix", self.street_suffix, "street", self.street
if self.street_suffix is None and self.street is None:
# print "upper", toke... | [
"\n Attempts to match a street suffix. If found, it will return the abbreviation, with the first letter capitalized\n and a period after it. E.g. \"St.\" or \"Ave.\"\n "
] |
Please provide a description of the function:def check_street(self, token):
# First check for single word streets between a prefix and a suffix
if self.street is None and self.street_suffix is not None and self.street_prefix is None and self.house_number is None:
self.street = self.... | [
"\n Let's assume a street comes before a prefix and after a suffix. This isn't always the case, but we'll deal\n with that in our guessing game. Also, two word street names...well...\n\n This check must come after the checks for house_number and street_prefix to help us deal with multi word str... |
Please provide a description of the function:def check_street_prefix(self, token):
if self.street and not self.street_prefix and token.lower().replace('.', '') in self.parser.prefixes.keys():
self.street_prefix = self._clean(self.parser.prefixes[token.lower().replace('.', '')])
... | [
"\n Finds street prefixes, such as N. or Northwest, before a street name. Standardizes to 1 or two letters, followed\n by a period.\n "
] |
Please provide a description of the function:def check_house_number(self, token):
if self.street and self.house_number is None and re.match(street_num_regex, token.lower()):
if '/' in token:
token = token.split('/')[0]
if '-' in token:
token = tok... | [
"\n Attempts to find a house number, generally the first thing in an address. If anything is in front of it,\n we assume it is a building name.\n "
] |
Please provide a description of the function:def check_building(self, token):
if self.street and self.house_number:
if not self.building:
self.building = self._clean(token)
else:
self.building = self._clean(token + ' ' + self.building)
... | [
"\n Building name check. If we have leftover and everything else is set, probably building names.\n Allows for multi word building names.\n "
] |
Please provide a description of the function:def guess_unmatched(self, token):
# Check if this is probably an apartment:
if token.lower() in ['apt', 'apartment']:
return False
# Stray dashes are likely useless
if token.strip() == '-':
return True
... | [
"\n When we find something that doesn't match, we can make an educated guess and log it as such.\n "
] |
Please provide a description of the function:def full_address(self):
addr = ""
# if self.building:
# addr = addr + "(" + self.building + ") "
if self.house_number:
addr = addr + self.house_number
if self.street_prefix:
addr = addr + " " + self... | [
"\n Print the address in a human readable format\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.