Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def _get_geocoding(self, key, location):
url = self._location_query_base % quote_plus(key)
if self.api_key:
url += "&key=%s" % self.api_key
data = self._read_from_url(url)
response = json.loads(data)
if response["... | [
"Lookup the Google geocoding API information for `key`"
] |
Please provide a description of the function:def _get_timezone(self, location):
url = self._timezone_query_base % (
location.latitude,
location.longitude,
int(time()),
)
if self.api_key != "":
url += "&key=%s" % self.api_key
data ... | [
"Query the timezone information with the latitude and longitude of\n the specified `location`.\n\n This function assumes the timezone of the location has always been\n the same as it is now by using time() in the query string.\n "
] |
Please provide a description of the function:def _get_elevation(self, location):
url = self._elevation_query_base % (location.latitude, location.longitude)
if self.api_key != "":
url += "&key=%s" % self.api_key
data = self._read_from_url(url)
response = json.loads(d... | [
"Query the elevation information with the latitude and longitude of\n the specified `location`.\n "
] |
Please provide a description of the function:def sun_utc(self, date, latitude, longitude, observer_elevation=0):
dawn = self.dawn_utc(date, latitude, longitude, observer_elevation=observer_elevation)
sunrise = self.sunrise_utc(date, latitude, longitude, observer_elevation=observer_elevation)
... | [
"Calculate all the info for the sun at once.\n All times are returned in the UTC timezone.\n\n :param date: Date to calculate for.\n :type date: :class:`datetime.date`\n :param latitude: Latitude - Northern latitudes should be positive\n :type latitude: float\n ... |
Please provide a description of the function:def dawn_utc(self, date, latitude, longitude, depression=0, observer_elevation=0):
if depression == 0:
depression = self._depression
depression += 90
try:
return self._calc_time(depression, SUN_RISING, date, latitude... | [
"Calculate dawn time in the UTC timezone.\n\n :param date: Date to calculate for.\n :type date: :class:`datetime.date`\n :param latitude: Latitude - Northern latitudes should be positive\n :type latitude: float\n :param longitude: Longitude - Eastern longitudes ... |
Please provide a description of the function:def sunrise_utc(self, date, latitude, longitude, observer_elevation=0):
try:
return self._calc_time(90 + 0.833, SUN_RISING, date, latitude, longitude, observer_elevation)
except ValueError as exc:
if exc.args[0] == "math doma... | [
"Calculate sunrise time in the UTC timezone.\n\n :param date: Date to calculate for.\n :type date: :class:`datetime.date`\n :param latitude: Latitude - Northern latitudes should be positive\n :type latitude: float\n :param longitude: Longitude - Eastern longitud... |
Please provide a description of the function:def solar_noon_utc(self, date, longitude):
jc = self._jday_to_jcentury(self._julianday(date))
eqtime = self._eq_of_time(jc)
timeUTC = (720.0 - (4 * longitude) - eqtime) / 60.0
hour = int(timeUTC)
minute = int((timeUTC - hour... | [
"Calculate solar noon time in the UTC timezone.\n\n :param date: Date to calculate for.\n :type date: :class:`datetime.date`\n :param longitude: Longitude - Eastern longitudes should be positive\n :type longitude: float\n\n :return: The UTC date and time at which n... |
Please provide a description of the function:def sunset_utc(self, date, latitude, longitude, observer_elevation=0):
try:
return self._calc_time(90 + 0.833, SUN_SETTING, date, latitude, longitude, observer_elevation)
except ValueError as exc:
if exc.args[0] == "math doma... | [
"Calculate sunset time in the UTC timezone.\n\n :param date: Date to calculate for.\n :type date: :class:`datetime.date`\n :param latitude: Latitude - Northern latitudes should be positive\n :type latitude: float\n :param longitude: Longitude - Eastern longitude... |
Please provide a description of the function:def dusk_utc(self, date, latitude, longitude, depression=0, observer_elevation=0):
if depression == 0:
depression = self._depression
depression += 90
try:
return self._calc_time(depression, SUN_SETTING, date, latitud... | [
"Calculate dusk time in the UTC timezone.\n\n :param date: Date to calculate for.\n :type date: :class:`datetime.date`\n :param latitude: Latitude - Northern latitudes should be positive\n :type latitude: float\n :param longitude: Longitude - Eastern longitudes ... |
Please provide a description of the function:def solar_midnight_utc(self, date, longitude):
julianday = self._julianday(date)
newt = self._jday_to_jcentury(julianday + 0.5 + -longitude / 360.0)
eqtime = self._eq_of_time(newt)
timeUTC = (-longitude * 4.0) - eqtime
tim... | [
"Calculate solar midnight time in the UTC timezone.\n\n Note that this claculates the solar midgnight that is closest\n to 00:00:00 of the specified date i.e. it may return a time that is on\n the previous day.\n\n :param date: Date to calculate for.\n :type date: :cl... |
Please provide a description of the function:def daylight_utc(self, date, latitude, longitude, observer_elevation=0):
start = self.sunrise_utc(date, latitude, longitude, observer_elevation)
end = self.sunset_utc(date, latitude, longitude, observer_elevation)
return start, end | [
"Calculate daylight start and end times in the UTC timezone.\n\n :param date: Date to calculate for.\n :type date: :class:`datetime.date`\n :param latitude: Latitude - Northern latitudes should be positive\n :type latitude: float\n :param longitude: Longitude - ... |
Please provide a description of the function:def night_utc(self, date, latitude, longitude, observer_elevation=0):
start = self.dusk_utc(date, latitude, longitude, 18, observer_elevation)
tomorrow = date + datetime.timedelta(days=1)
end = self.dawn_utc(tomorrow, latitude, longitude, 18... | [
"Calculate night start and end times in the UTC timezone.\n\n Night is calculated to be between astronomical dusk on the\n date specified and astronomical dawn of the next day.\n\n :param date: Date to calculate for.\n :type date: :class:`datetime.date`\n :param latit... |
Please provide a description of the function:def twilight_utc(self, direction, date, latitude, longitude, observer_elevation=0):
if date is None:
date = datetime.date.today()
start = self.time_at_elevation_utc(-6, direction, date, latitude, longitude, observer_elevation)
i... | [
"Returns the start and end times of Twilight in the UTC timezone when\n the sun is traversing in the specified direction.\n\n This method defines twilight as being between the time\n when the sun is at -6 degrees and sunrise/sunset.\n\n :param direction: Determines whether the time is f... |
Please provide a description of the function:def blue_hour_utc(self, direction, date, latitude, longitude, observer_elevation=0):
if date is None:
date = datetime.date.today()
start = self.time_at_elevation_utc(-6, direction, date, latitude, longitude, observer_elevation)
... | [
"Returns the start and end times of the Blue Hour in the UTC timezone\n when the sun is traversing in the specified direction.\n\n This method uses the definition from PhotoPills i.e. the\n blue hour is when the sun is between 6 and 4 degrees below the horizon.\n\n :param direction: Det... |
Please provide a description of the function:def time_at_elevation_utc(self, elevation, direction, date, latitude, longitude, observer_elevation=0):
if elevation > 90.0:
elevation = 180.0 - elevation
direction = SUN_SETTING
depression = 90 - elevation
try:
... | [
"Calculate the time in the UTC timezone when the sun is at\n the specified elevation on the specified date.\n\n Note: This method uses positive elevations for those above the horizon.\n\n :param elevation: Elevation in degrees above the horizon to calculate for.\n :type elevation: flo... |
Please provide a description of the function:def solar_azimuth(self, dateandtime, latitude, longitude):
if latitude > 89.8:
latitude = 89.8
if latitude < -89.8:
latitude = -89.8
if dateandtime.tzinfo is None:
zone = 0
utc_datetime = dat... | [
"Calculate the azimuth angle of the sun.\n\n :param dateandtime: The date and time for which to calculate\n the angle.\n :type dateandtime: :class:`~datetime.datetime`\n :param latitude: Latitude - Northern latitudes should be positive\n :type latitude: f... |
Please provide a description of the function:def solar_elevation(self, dateandtime, latitude, longitude):
if latitude > 89.8:
latitude = 89.8
if latitude < -89.8:
latitude = -89.8
if dateandtime.tzinfo is None:
zone = 0
utc_datetime = d... | [
"Calculate the elevation angle of the sun.\n\n :param dateandtime: The date and time for which to calculate\n the angle.\n :type dateandtime: :class:`~datetime.datetime`\n :param latitude: Latitude - Northern latitudes should be positive\n :type latitude: ... |
Please provide a description of the function:def solar_zenith(self, dateandtime, latitude, longitude):
return 90.0 - self.solar_elevation(dateandtime, latitude, longitude) | [
"Calculates the solar zenith angle.\n\n :param dateandtime: The date and time for which to calculate\n the angle.\n :type dateandtime: :class:`~datetime.datetime`\n :param latitude: Latitude - Northern latitudes should be positive\n :type latitude: float\n... |
Please provide a description of the function:def moon_phase(self, date, rtype=int):
if rtype != float and rtype != int:
rtype = int
moon = self._moon_phase_asfloat(date)
if moon >= 28.0:
moon -= 28.0
moon = rtype(moon)
return moon | [
"Calculates the phase of the moon on the specified date.\n\n :param date: The date to calculate the phase for.\n :type date: :class:`datetime.date`\n :param rtype: The type to return either int (default) or float.\n\n :return:\n A number designating the phase.\n\n ... |
Please provide a description of the function:def rahukaalam_utc(self, date, latitude, longitude, observer_elevation=0):
if date is None:
date = datetime.date.today()
sunrise = self.sunrise_utc(date, latitude, longitude, observer_elevation)
sunset = self.sunset_utc(date, la... | [
"Calculate ruhakaalam times in the UTC timezone.\n\n :param date: Date to calculate for.\n :type date: :class:`datetime.date`\n :param latitude: Latitude - Northern latitudes should be positive\n :type latitude: float\n :param longitude: Longitude - Eastern long... |
Please provide a description of the function:def _depression_adjustment(self, elevation):
if elevation <= 0:
return 0
r = 6356900 # radius of the earth
a1 = r
h1 = r + elevation
theta1 = acos(a1 / h1)
a2 = r * sin(theta1)
b2 = r - (r * cos(... | [
"Calculate the extra degrees of depression due to the increase in elevation.\n\n :param elevation: Elevation above the earth in metres\n :type elevation: float\n "
] |
Please provide a description of the function:def find_config_files(self):
files = []
check_environ()
# Where to look for the system-wide Distutils config file
sys_dir = os.path.dirname(sys.modules['distutils'].__file__)
# Look for the system config file
sys_file = os.path.join(sys_dir, "... | [
"Find as many configuration files as should be processed for this\n platform, and return a list of filenames in the order in which they\n should be parsed. The filenames returned are guaranteed to exist\n (modulo nasty race conditions).\n\n There are three possible config files: distutils.cfg in the\n ... |
Please provide a description of the function:def callback(status, message, job, result, exception, stacktrace):
assert status in ['invalid', 'success', 'timeout', 'failure']
assert isinstance(message, Message)
if status == 'invalid':
assert job is None
assert result is None
ass... | [
"Example callback function.\n\n :param status: Job status. Possible values are \"invalid\" (job could not be\n deserialized or was malformed), \"failure\" (job raised an exception),\n \"timeout\" (job timed out), or \"success\" (job finished successfully and\n returned a result).\n :type ... |
Please provide a description of the function:def _execute_callback(self, status, message, job, res, err, stacktrace):
if self._callback is not None:
try:
self._logger.info('Executing callback ...')
self._callback(status, message, job, res, err, stacktrace)
... | [
"Execute the callback.\n\n :param status: Job status. Possible values are \"invalid\" (job could not\n be deserialized or was malformed), \"failure\" (job raised an error),\n \"timeout\" (job timed out), or \"success\" (job finished successfully\n and returned a result).\n ... |
Please provide a description of the function:def _process_message(self, msg):
self._logger.info(
'Processing Message(topic={}, partition={}, offset={}) ...'
.format(msg.topic, msg.partition, msg.offset))
try:
job = self._deserializer(msg.value)
jo... | [
"De-serialize the message and execute the job.\n\n :param msg: Kafka message.\n :type msg: :doc:`kq.Message <message>`\n "
] |
Please provide a description of the function:def start(self, max_messages=math.inf, commit_offsets=True):
self._logger.info('Starting {} ...'.format(self))
self._consumer.unsubscribe()
self._consumer.subscribe([self.topic])
messages_processed = 0
while messages_process... | [
"Start processing Kafka messages and executing jobs.\n\n :param max_messages: Maximum number of Kafka messages to process before\n stopping. If not set, worker runs until interrupted.\n :type max_messages: int\n :param commit_offsets: If set to True, consumer offsets are committed\n ... |
Please provide a description of the function:def get_call_repr(func, *args, **kwargs):
# Functions, builtins and methods
if ismethod(func) or isfunction(func) or isbuiltin(func):
func_repr = '{}.{}'.format(func.__module__, func.__qualname__)
# A callable class instance
elif not isclass(func... | [
"Return the string representation of the function call.\n\n :param func: A callable (e.g. function, method).\n :type func: callable\n :param args: Positional arguments for the callable.\n :param kwargs: Keyword arguments for the callable.\n :return: String representation of the function call.\n :r... |
Please provide a description of the function:def enqueue(self, func, *args, **kwargs):
return self._default_enqueue_spec.enqueue(func, *args, **kwargs) | [
"Enqueue a function call or a :doc:`job <job>`.\n\n :param func: Function or a :doc:`job <job>` object. Must be\n serializable and available to :doc:`workers <worker>`.\n :type func: callable | :doc:`kq.Job <job>`\n :param args: Positional arguments for the function. Ignored if **fun... |
Please provide a description of the function:def using(self, timeout=None, key=None, partition=None):
return EnqueueSpec(
topic=self._topic,
producer=self._producer,
serializer=self._serializer,
logger=self._logger,
timeout=timeout or self._ti... | [
"Set enqueue specifications such as timeout, key and partition.\n\n :param timeout: Job timeout threshold in seconds. If not set, default\n timeout (specified during queue initialization) is used instead.\n :type timeout: int | float\n :param key: Kafka message key. Jobs with the sam... |
Please provide a description of the function:def enqueue(self, obj, *args, **kwargs):
timestamp = int(time.time() * 1000)
if isinstance(obj, Job):
job_id = uuid.uuid4().hex if obj.id is None else obj.id
func = obj.func
args = tuple() if obj.args is None else... | [
"Enqueue a function call or :doc:`job` instance.\n\n :param func: Function or :doc:`job <job>`. Must be serializable and\n importable by :doc:`worker <worker>` processes.\n :type func: callable | :doc:`kq.Job <job>`\n :param args: Positional arguments for the function. Ignored if **f... |
Please provide a description of the function:def ensure_path_exists(dir_path):
if not os.path.exists(dir_path):
os.makedirs(dir_path)
return True
return False | [
"\n Make sure that a path exists\n "
] |
Please provide a description of the function:def send(instructions, printer_identifier=None, backend_identifier=None, blocking=True):
status = {
'instructions_sent': True, # The instructions were sent to the printer.
'outcome': 'unknown', # String description of the outcome of the sending operatio... | [
"\n Send instruction bytes to a printer.\n\n :param bytes instructions: The instructions to be sent to the printer.\n :param str printer_identifier: Identifier for the printer.\n :param str backend_identifier: Can enforce the use of a specific backend.\n :param bool blocking: Indicates whether the fu... |
Please provide a description of the function:def chunker(data, raise_exception=False):
instructions = []
data = bytes(data)
while True:
if len(data) == 0: break
try:
opcode = match_opcode(data)
except:
msg = 'unknown opcode starting with {}...)'.format(he... | [
"\n Breaks data stream (bytes) into a list of bytes objects containing single instructions each.\n\n Logs warnings for unknown opcodes or raises an exception instead, if raise_exception is set to True.\n\n returns: list of bytes objects\n "
] |
Please provide a description of the function:def merge_specific_instructions(chunks, join_preamble=True, join_raster=True):
new_instructions = []
last_opcode = None
instruction_buffer = b''
for instruction in chunks:
opcode = match_opcode(instruction)
if join_preamble and OPCODES[... | [
"\n Process a list of instructions by merging subsequent instuctions with\n identical opcodes into \"large instructions\".\n "
] |
Please provide a description of the function:def filtered_hsv(im, filter_h, filter_s, filter_v, default_col=(255,255,255)):
hsv_im = im.convert('HSV')
H, S, V = 0, 1, 2
hsv = hsv_im.split()
mask_h = hsv[H].point(filter_h)
mask_s = hsv[S].point(filter_s)
mask_v = hsv[V].point(filter_v)
... | [
" https://stackoverflow.com/a/22237709/183995 "
] |
Please provide a description of the function:def _warn(self, problem, kind=BrotherQLRasterError):
if self.exception_on_warning:
raise kind(problem)
else:
logger.warning(problem) | [
"\n Logs the warning message `problem` or raises a\n `BrotherQLRasterError` exception (changeable via `kind`)\n if `self.exception_on_warning` is set to True.\n\n :raises BrotherQLRasterError: Or other exception \\\n set via the `kind` keyword argument.\n "
] |
Please provide a description of the function:def add_switch_mode(self):
if self.model not in modesetting:
self._unsupported("Trying to switch the operating mode on a printer that doesn't support the command.")
return
self.data += b'\x1B\x69\x61\x01' | [
"\n Switch dynamic command mode\n Switch to the raster mode on the printers that support\n the mode change (others are in raster mode already).\n "
] |
Please provide a description of the function:def add_compression(self, compression=True):
if self.model not in compressionsupport:
self._unsupported("Trying to set compression on a printer that doesn't support it")
return
self._compression = compression
self.data... | [
"\n Add an instruction enabling or disabling compression for the transmitted raster image lines.\n Not all models support compression. If the specific model doesn't support it but this method\n is called trying to enable it, either a warning is set or an exception is raised depending on\n ... |
Please provide a description of the function:def add_raster_data(self, image, second_image=None):
logger.debug("raster_image_size: {0}x{1}".format(*image.size))
if image.size[0] != self.get_pixel_width():
fmt = 'Wrong pixel width: {}, expected {}'
raise BrotherQLRasterEr... | [
"\n Add the image data to the instructions.\n The provided image has to be binary (every pixel\n is either black or white).\n\n :param PIL.Image.Image image: The image to be converted and added to the raster instructions\n :param PIL.Image.Image second_image: A second image with a... |
Please provide a description of the function:def cli(ctx, *args, **kwargs):
backend = kwargs.get('backend', None)
model = kwargs.get('model', None)
printer = kwargs.get('printer', None)
debug = kwargs.get('debug')
# Store the general CLI options in the context meta dictionary.
# The name ... | [
" Command line interface for the brother_ql Python package. "
] |
Please provide a description of the function:def labels(ctx, *args, **kwargs):
from brother_ql.output_helpers import textual_label_description
print(textual_label_description(label_sizes)) | [
"\n List the choices for --label\n "
] |
Please provide a description of the function:def env(ctx, *args, **kwargs):
import sys, platform, os, shutil
from pkg_resources import get_distribution, working_set
print("\n##################\n")
print("Information about the running environment of brother_ql.")
print("(Please provide this info... | [
"\n print debug info about running environment\n "
] |
Please provide a description of the function:def print_cmd(ctx, *args, **kwargs):
backend = ctx.meta.get('BACKEND', 'pyusb')
model = ctx.meta.get('MODEL')
printer = ctx.meta.get('PRINTER')
from brother_ql.conversion import convert
from brother_ql.backends.helpers import send
from brother_ql... | [
" Print a label of the provided IMAGE. "
] |
Please provide a description of the function:def list_available_devices():
class find_class(object):
def __init__(self, class_):
self._class = class_
def __call__(self, device):
# first, let's check the device
if device.bDeviceClass == self._class:
... | [
"\n List all available devices for the respective backend\n\n returns: devices: a list of dictionaries with the keys 'identifier' and 'instance': \\\n [ {'identifier': 'usb://0x04f9:0x2015/C5Z315686', 'instance': pyusb.core.Device()}, ]\n The 'identifier' is of the format idVendor:idProduct_iSer... |
Please provide a description of the function:def convert(qlr, images, label, **kwargs):
r
label_specs = label_type_specs[label]
dots_printable = label_specs['dots_printable']
right_margin_dots = label_specs['right_margin_dots']
right_margin_dots += right_margin_addition.get(qlr.model, 0)
devic... | [
"Converts one or more images to a raster instruction file.\n\n :param qlr:\n An instance of the BrotherQLRaster class\n :type qlr: :py:class:`brother_ql.raster.BrotherQLRaster`\n :param images:\n The images to be converted. They can be filenames or instances of Pillow's Image.\n :type imag... |
Please provide a description of the function:def _populate_label_legacy_structures():
global DIE_CUT_LABEL, ENDLESS_LABEL, ROUND_DIE_CUT_LABEL
global label_sizes, label_type_specs
from brother_ql.labels import FormFactor
DIE_CUT_LABEL = FormFactor.DIE_CUT
ENDLESS_LABEL = FormFactor... | [
"\n We contain this code inside a function so that the imports\n we do in here are not visible at the module level.\n "
] |
Please provide a description of the function:def guess_backend(identifier):
if identifier.startswith('usb://') or identifier.startswith('0x'):
return 'pyusb'
elif identifier.startswith('file://') or identifier.startswith('/dev/usb/') or identifier.startswith('lp'):
return 'linux_kernel'
... | [
" guess the backend from a given identifier string for the device "
] |
Please provide a description of the function:def autocomplete_query(self, **kwargs):
if not kwargs.get('text'):
raise ValueError('Valid text (parameter "text") must be provided.')
return self._query(AUTOCOMPLETE_API_URL, **kwargs) | [
"\n Query the Yelp Autocomplete API.\n \n documentation: https://www.yelp.com/developers/documentation/v3/autocomplete\n\n required parameters:\n * text - search text\n "
] |
Please provide a description of the function:def business_query(self, id, **kwargs):
if not id:
raise ValueError('A valid business ID (parameter "id") must be provided.')
return self._query(BUSINESS_API_URL.format(id), **kwargs) | [
"\n Query the Yelp Business API.\n \n documentation: https://www.yelp.com/developers/documentation/v3/business\n\n required parameters:\n * id - business ID\n "
] |
Please provide a description of the function:def business_match_query(self, **kwargs):
if not kwargs.get('name'):
raise ValueError('Valid business name (parameter "name") must be provided.')
if not kwargs.get('city'):
raise ValueError('Valid city (parameter "city") must... | [
"\n Query the Yelp Business Match API.\n \n documentation: https://www.yelp.com/developers/documentation/v3/business_match\n\n required parameters:\n * name - business name\n * city\n * state\n * country\n ... |
Please provide a description of the function:def event_lookup_query(self, id, **kwargs):
if not id:
raise ValueError('A valid event ID (parameter "id") must be provided.')
return self._query(EVENT_LOOKUP_API_URL.format(id), **kwargs) | [
"\n Query the Yelp Event Lookup API.\n \n documentation: https://www.yelp.com/developers/documentation/v3/event\n\n required parameters:\n * id - event ID\n "
] |
Please provide a description of the function:def featured_event_query(self, **kwargs):
if not kwargs.get('location') and (not kwargs.get('latitude') or not kwargs.get('longitude')):
raise ValueError('A valid location (parameter "location") or latitude/longitude combination '
... | [
"\n Query the Yelp Featured Event API.\n\n documentation: https://www.yelp.com/developers/documentation/v3/featured_event\n\n required parameters:\n * one of either:\n * location - text specifying a location to search for\n * lati... |
Please provide a description of the function:def phone_search_query(self, **kwargs):
if not kwargs.get('phone'):
raise ValueError('A valid phone number (parameter "phone") must be provided.')
return self._query(PHONE_SEARCH_API_URL, **kwargs) | [
"\n Query the Yelp Phone Search API.\n \n documentation: https://www.yelp.com/developers/documentation/v3/business_search_phone\n\n required parameters:\n * phone - phone number\n "
] |
Please provide a description of the function:def reviews_query(self, id, **kwargs):
if not id:
raise ValueError('A valid business ID (parameter "id") must be provided.')
return self._query(REVIEWS_API_URL.format(id), **kwargs) | [
"\n Query the Yelp Reviews API.\n \n documentation: https://www.yelp.com/developers/documentation/v3/business_reviews\n\n required parameters:\n * id - business ID\n "
] |
Please provide a description of the function:def search_query(self, **kwargs):
if not kwargs.get('location') and (not kwargs.get('latitude') or not kwargs.get('longitude')):
raise ValueError('A valid location (parameter "location") or latitude/longitude combination '
... | [
"\n Query the Yelp Search API.\n \n documentation: https://www.yelp.com/developers/documentation/v3/business_search\n\n required parameters:\n * one of either:\n * location - text specifying a location to search for\n *... |
Please provide a description of the function:def transaction_search_query(self, transaction_type, **kwargs):
if not transaction_type:
raise ValueError('A valid transaction type (parameter "transaction_type") must be provided.')
if not kwargs.get('location') and (not kwargs.get('lat... | [
"\n Query the Yelp Transaction Search API.\n \n documentation: https://www.yelp.com/developers/documentation/v3/transactions_search\n \n required parameters:\n * transaction_type - transaction type\n * one of either:\n ... |
Please provide a description of the function:def _get_clean_parameters(kwargs):
return dict((k, v) for k, v in kwargs.items() if v is not None) | [
"\n Clean the parameters by filtering out any parameters that have a None value.\n "
] |
Please provide a description of the function:def _query(self, url, **kwargs):
parameters = YelpAPI._get_clean_parameters(kwargs)
response = self._yelp_session.get(
url,
headers=self._headers,
params=parameters,
timeout=self._timeout_s,
)
... | [
"\n All query methods have the same logic, so don't repeat it! Query the URL, parse the response as JSON,\n and check for errors. If all goes well, return the parsed JSON.\n "
] |
Please provide a description of the function:def _qualified_key(self, key):
fq_key = super(Reader, self)._qualified_key(key)
return fq_key.lstrip('/') | [
"\n Prepends the configured prefix to the key (if applicable).\n\n For Consul we also lstrip any '/' chars from the prefixed key.\n\n :param key: The unprefixed key.\n :return: The key with any configured prefix prepended.\n "
] |
Please provide a description of the function:def _qualified_key(self, key):
pfx = self.key_prefix if self.key_prefix is not None else ''
return '{}{}'.format(pfx, key) | [
"\n Prepends the configured prefix to the key (if applicable).\n\n :param key: The unprefixed key.\n :return: The key with any configured prefix prepended.\n "
] |
Please provide a description of the function:def url_join(base, *args):
scheme, netloc, path, query, fragment = urlsplit(base)
path = path if len(path) else "/"
path = posixpath.join(path, *[('%s' % x) for x in args])
return urlunsplit([scheme, netloc, path, query, fragment]) | [
"\n Helper function to join an arbitrary number of url segments together.\n "
] |
Please provide a description of the function:def probe_to_graphsrv(probe):
config = probe.config
# manual group set up via `group` config key
if "group" in config:
source, group = config["group"].split(".")
group_field = config.get("group_field", "host")
group_value = config[... | [
"\n takes a probe instance and generates\n a graphsrv data group for it using the\n probe's config\n "
] |
Please provide a description of the function:def new_message(self):
msg = {}
msg['data'] = []
msg['type'] = self.plugin_type
msg['source'] = self.name
msg['ts'] = (datetime.datetime.utcnow() - datetime.datetime(1970, 1, 1)).total_seconds()
return msg | [
"\n creates a new message, setting `type`, `source`, `ts`, `data`\n - `data` is initialized to an empty array\n "
] |
Please provide a description of the function:def popen(self, args, **kwargs):
self.log.debug("popen %s", ' '.join(args))
return vaping.io.subprocess.Popen(args, **kwargs) | [
"\n creates a subprocess with passed args\n "
] |
Please provide a description of the function:def queue_emission(self, msg):
if not msg:
return
for _emitter in self._emit:
if not hasattr(_emitter, 'emit'):
continue
def emit(emitter=_emitter):
self.log.debug("emit to {}".forma... | [
"\n queue an emission of a message for all output plugins\n "
] |
Please provide a description of the function:def send_emission(self):
if self._emit_queue.empty():
return
emit = self._emit_queue.get()
emit() | [
"\n emit and remove the first emission in the queue\n "
] |
Please provide a description of the function:def validate_file_handler(self):
if self.fh.closed:
try:
self.fh = open(self.path, "r")
self.fh.seek(0, 2)
except OSError as err:
logging.error("Could not reopen file: {}".format(err))
... | [
"\n Here we validate that our filehandler is pointing\n to an existing file.\n\n If it doesnt, because file has been deleted, we close\n the filehander and try to reopen\n "
] |
Please provide a description of the function:def probe(self):
# make sure the filehandler is still valid
# (e.g. file stat hasnt changed, file exists etc.)
if not self.validate_file_handler():
return []
messages = []
# read any new lines and push them onto... | [
"\n Probe the file for new lines\n "
] |
Please provide a description of the function:def filename_formatters(self, data, row):
r = {
"source" : data.get("source"),
"field" : self.field,
"type" : data.get("type")
}
r.update(**row)
return r | [
"\n Returns a dict containing the various filename formatter values\n\n Values are gotten from the vaping data message as well as the\n currently processed row in the message\n\n - `data`: vaping message\n - `row`: vaping message data row\n "
] |
Please provide a description of the function:def format_filename(self, data, row):
return self.filename.format(**self.filename_formatters(data, row)) | [
"\n Returns a formatted filename using the template stored\n in self.filename\n\n - `data`: vaping message\n - `row`: vaping message data row\n "
] |
Please provide a description of the function:def emit(self, message):
# handle vaping data that arrives in a list
if isinstance(message.get("data"), list):
for row in message.get("data"):
# format filename from data
filename = self.format_filename(m... | [
"\n emit to database\n "
] |
Please provide a description of the function:def parse_interval(val):
re_intv = re.compile(r"([\d\.]+)([a-zA-Z]+)")
val = val.strip()
total = 0.0
for match in re_intv.findall(val):
unit = match[1]
count = float(match[0])
if unit == 's':
total += count
el... | [
"\n converts a string to float of seconds\n .5 = 500ms\n 90 = 1m30s\n "
] |
Please provide a description of the function:def hosts_args(self):
host_args = []
for row in self.hosts:
if isinstance(row, dict):
host_args.append(row["host"])
else:
host_args.append(row)
# using a set changes the order
... | [
"\n hosts list can contain strings specifying a host directly\n or dicts containing a \"host\" key to specify the host\n\n this way we can allow passing further config details (color, name etc.)\n with each host as well as simply dropping in addresses for quick\n setup depending o... |
Please provide a description of the function:def parse_verbose(self, line):
try:
logging.debug(line)
(host, pings) = line.split(' : ')
cnt = 0
lost = 0
times = []
pings = pings.strip().split(' ')
cnt = len(pings)
... | [
"\n parse output from verbose format\n "
] |
Please provide a description of the function:def start(ctx, **kwargs):
update_context(ctx, kwargs)
daemon = mk_daemon(ctx)
if ctx.debug or kwargs['no_fork']:
daemon.run()
else:
daemon.start() | [
"\n start a vaping process\n "
] |
Please provide a description of the function:def stop(ctx, **kwargs):
update_context(ctx, kwargs)
daemon = mk_daemon(ctx)
daemon.stop() | [
"\n stop a vaping process\n "
] |
Please provide a description of the function:def restart(ctx, **kwargs):
update_context(ctx, kwargs)
daemon = mk_daemon(ctx)
daemon.stop()
daemon.start() | [
"\n restart a vaping process\n "
] |
Please provide a description of the function:def _exec(self, detach=True):
kwargs = {
'pidfile': self.pidfile,
'working_directory': self.home_dir,
}
# FIXME - doesn't work
if not detach:
kwargs.update({
'detach_process': F... | [
"\n daemonize and exec main()\n "
] |
Please provide a description of the function:def _main(self):
probes = self.config.get('probes', None)
if not probes:
raise ValueError('no probes specified')
for probe_config in self.config['probes']:
probe = plugin.get_probe(probe_config, self.plugin_context)
... | [
"\n process\n "
] |
Please provide a description of the function:def stop(self):
try:
with self.pidfile:
self.log.error("failed to stop, missing pid file or not running")
except pidfile.PidFileError:
# this isn't exposed in pidfile :o
with open(self.pidfile.file... | [
" stop daemon "
] |
Please provide a description of the function:def run(self):
# FIXME - not detaching doesn't work, just run directly for now
# self._exec(detach=False)
try:
with self.pidfile:
return self._main()
except pidfile.PidFileError:
# this isn't e... | [
" run daemon "
] |
Please provide a description of the function:def log(self, logfile=None):
if logfile is None:
logfile = sys.stderr
tb = self.plaintext.encode('utf-8', 'replace').rstrip() + '\n'
logfile.write(tb) | [
"Log the ASCII traceback into a file object."
] |
Please provide a description of the function:def render_summary(self, app, include_title=True):
title = ''
frames = []
classes = ['traceback']
if not self.frames:
classes.append('noframe-traceback')
if include_title:
if self.is_syntax_error:
... | [
"Render the traceback for the interactive console."
] |
Please provide a description of the function:def render_full(self, request, lodgeit_url=None):
static_path = request.app.router[STATIC_ROUTE_NAME].url_for(
filename='')
root_path = request.app.router[ROOT_ROUTE_NAME].url_for()
exc = escape(self.exception)
summary = s... | [
"Render the Full HTML page with the traceback info."
] |
Please provide a description of the function:def render(self):
return FRAME_HTML % {
'id': self.id,
'filename': escape(self.filename),
'lineno': self.lineno,
'function_name': escape(self.function_name),
'current_line': escape(self.current_line... | [
"Render a single frame in a traceback."
] |
Please provide a description of the function:def eval(self, code, mode='single'):
if isinstance(code, str):
if isinstance(code, str):
code = UTF8_COOKIE + code.encode('utf-8')
code = compile(code, '<interactive>', mode)
if mode != 'exec':
retu... | [
"Evaluate code in the context of the frame."
] |
Please provide a description of the function:def sourcelines(self):
# get sourcecode from loader or file
source = None
if self.loader is not None:
try:
if hasattr(self.loader, 'get_source'):
source = self.loader.get_source(self.module)
... | [
"The sourcecode of the file as list of unicode strings."
] |
Please provide a description of the function:def render_content(self, request):
context = self.data.copy()
context.update(self.render_vars(request))
return render(self.template, request.app, context, request=request) | [
"Return a string containing the HTML to be rendered for the panel.\n\n By default this will render the template defined by the\n :attr:`.template` attribute with a rendering context defined by\n :attr:`.data` combined with the ``dict`` returned from\n :meth:`.render_vars`.\n\n The... |
Please provide a description of the function:def inject(self, request, response):
# called in host app
if not isinstance(response, Response):
return
settings = request.app[APP_KEY]['settings']
response_html = response.body
route = request.app.router['debugtoo... | [
"\n Inject the debug toolbar iframe into an HTML response.\n "
] |
Please provide a description of the function:def replace_insensitive(string, target, replacement):
no_case = string.lower()
index = no_case.rfind(target.lower())
if index >= 0:
return string[:index] + replacement + string[index + len(target):]
else: # no results so return the original stri... | [
"Similar to string.replace() but is case insensitive\n Code borrowed from: http://forums.devshed.com/python-programming-11/\n case-insensitive-string-replace-490921.html\n "
] |
Please provide a description of the function:def common_segment_count(path, value):
i = 0
if len(path) <= len(value):
for x1, x2 in zip(path, value):
if x1 == x2:
i += 1
else:
return 0
return i | [
"Return the number of path segments common to both"
] |
Please provide a description of the function:def escape(s, quote=False):
if s is None:
return ''
if not isinstance(s, (str, bytes)):
s = str(s)
if isinstance(s, bytes):
try:
s.decode('ascii')
except UnicodeDecodeError:
s = s.decode('utf-8', 'repl... | [
"Replace special characters \"&\", \"<\" and \">\" to HTML-safe sequences. If\n the optional flag `quote` is `True`, the quotation mark character is\n also translated.\n\n There is a special handling for `None` which escapes to an empty string.\n\n :param s: the string to escape.\n :param quote: set... |
Please provide a description of the function:def _send(self, data):
try:
self._sock.sendto(data.encode('ascii'), self._addr)
except (socket.error, RuntimeError):
# No time for love, Dr. Jones!
pass | [
"Send data to statsd."
] |
Please provide a description of the function:def timing(self, stat, delta, rate=1):
if isinstance(delta, timedelta):
# Convert timedelta to number of milliseconds.
delta = delta.total_seconds() * 1000.
self._send_stat(stat, '%0.6f|ms' % delta, rate) | [
"\n Send new timing information.\n\n `delta` can be either a number of milliseconds or a timedelta.\n "
] |
Please provide a description of the function:def incr(self, stat, count=1, rate=1):
self._send_stat(stat, '%s|c' % count, rate) | [
"Increment a stat by `count`."
] |
Please provide a description of the function:def decr(self, stat, count=1, rate=1):
self.incr(stat, -count, rate) | [
"Decrement a stat by `count`."
] |
Please provide a description of the function:def gauge(self, stat, value, rate=1, delta=False):
if value < 0 and not delta:
if rate < 1:
if random.random() > rate:
return
with self.pipeline() as pipe:
pipe._send_stat(stat, '0|g... | [
"Set a gauge value."
] |
Please provide a description of the function:def set(self, stat, value, rate=1):
self._send_stat(stat, '%s|s' % value, rate) | [
"Set a set value."
] |
Please provide a description of the function:def _send(self, data):
if not self._sock:
self.connect()
self._do_send(data) | [
"Send data to statsd."
] |
Please provide a description of the function:def safe_wraps(wrapper, *args, **kwargs):
while isinstance(wrapper, functools.partial):
wrapper = wrapper.func
return functools.wraps(wrapper, *args, **kwargs) | [
"Safely wraps partial functions."
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.