INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
THIS FUNCTION MUST BE CALLED BEFORE CALLING freshroastsr700. auto_connect (). | def set_state_transition_func(self, func):
"""THIS FUNCTION MUST BE CALLED BEFORE CALLING
freshroastsr700.auto_connect().
Set, or re-set, the state transition function callback.
The supplied function will be called from a separate thread within
freshroastsr700, triggered by a se... |
This is the thread that listens to an event from the comm process to execute the update_data_func callback in the context of the main process. | def update_data_run(self, event_to_wait_on):
"""This is the thread that listens to an event from
the comm process to execute the update_data_func callback
in the context of the main process.
"""
# with the daemon=Turue setting, this thread should
# quit 'automati... |
This is the thread that listens to an event from the timer process to execute the state_transition_func callback in the context of the main process. | def state_transition_run(self, event_to_wait_on):
"""This is the thread that listens to an event from
the timer process to execute the state_transition_func callback
in the context of the main process.
"""
# with the daemon=Turue setting, this thread should
# qui... |
Do not call this directly - call auto_connect () or connect () which will call _connect () for you. | def _connect(self):
"""Do not call this directly - call auto_connect() or connect(),
which will call _connect() for you.
Connects to the roaster and creates communication thread.
Raises a RoasterLokkupError exception if the hardware is not found.
"""
# the following call... |
Sends the initialization packet to the roaster. | def _initialize(self):
"""Sends the initialization packet to the roaster."""
self._header.value = b'\xAA\x55'
self._current_state.value = b'\x00\x00'
s = self._generate_packet()
self._ser.write(s)
self._header.value = b'\xAA\xAA'
self._current_state.value = b'\x02... |
Attempt to connect to hardware immediately. Will not retry. Check freshroastsr700. connected or freshroastsr700. connect_state to verify result. Raises: freshroastsr700. exeptions. RoasterLookupError No hardware connected to the computer. | def connect(self):
"""Attempt to connect to hardware immediately. Will not retry.
Check freshroastsr700.connected or freshroastsr700.connect_state
to verify result.
Raises:
freshroastsr700.exeptions.RoasterLookupError
No hardware connected to the computer.
... |
Starts the connection process as called ( internally ) from the user context either from auto_connect () or connect (). Never call this from the _comm () process context. | def _start_connect(self, connect_type):
"""Starts the connection process, as called (internally)
from the user context, either from auto_connect() or connect().
Never call this from the _comm() process context.
"""
if self._connect_state.value != self.CS_NOT_CONNECTED:
... |
Attempts to connect to the roaster every quarter of a second. | def _auto_connect(self):
"""Attempts to connect to the roaster every quarter of a second."""
while not self._teardown.value:
try:
self._connect()
return True
except exceptions.RoasterLookupError:
time.sleep(.25)
return False |
Do not call this directly - call auto_connect () which will spawn comm () for you. | def _comm(self, thermostat=False,
kp=0.06, ki=0.0075, kd=0.01,
heater_segments=8, ext_sw_heater_drive=False,
update_data_event=None):
"""Do not call this directly - call auto_connect(), which will spawn
comm() for you.
This is the main communications lo... |
Timer loop used to keep track of the time while roasting or cooling. If the time remaining reaches zero the roaster will call the supplied state transistion function or the roaster will be set to the idle state. | def _timer(self, state_transition_event=None):
"""Timer loop used to keep track of the time while roasting or
cooling. If the time remaining reaches zero, the roaster will call the
supplied state transistion function or the roaster will be set to
the idle state."""
while not self... |
Returns a string based upon the current state of the roaster. Will raise an exception if the state is unknown. | def get_roaster_state(self):
"""Returns a string based upon the current state of the roaster. Will
raise an exception if the state is unknown.
Returns:
'idle' if idle,
'sleeping' if sleeping,
'cooling' if cooling,
'roasting' if roasting,
... |
Generates a packet based upon the current class variables. Note that current temperature is not sent as the original application sent zeros to the roaster for the current temperature. | def _generate_packet(self):
"""Generates a packet based upon the current class variables. Note that
current temperature is not sent, as the original application sent zeros
to the roaster for the current temperature."""
roaster_time = utils.seconds_to_float(self._time_remaining.value)
... |
Set the desired output level. Must be between 0 and number_of_segments inclusive. | def heat_level(self, value):
"""Set the desired output level. Must be between 0 and
number_of_segments inclusive."""
if value < 0:
self._heat_level = 0
elif round(value) > self._num_segments:
self._heat_level = self._num_segments
else:
self._he... |
Generates the latest on or off pulse in the string of on ( True ) or off ( False ) pulses according to the desired heat_level setting. Successive calls to this function will return the next value in the on/ off array series. Call this at control loop rate to obtain the necessary on/ off pulse train. This system will no... | def generate_bangbang_output(self):
"""Generates the latest on or off pulse in
the string of on (True) or off (False) pulses
according to the desired heat_level setting. Successive calls
to this function will return the next value in the
on/off array series. Call th... |
This is a method that will be called every time a packet is opened from the roaster. | def update_data(self):
"""This is a method that will be called every time a packet is opened
from the roaster."""
time_elapsed = datetime.datetime.now() - self.start_time
crntTemp = self.roaster.current_temp
targetTemp = self.roaster.target_temp
heaterLevel = self.roaster... |
This is a method that will be called when the time remaining ends. The current state can be: roasting cooling idle sleeping connecting or unkown. | def next_state(self):
"""This is a method that will be called when the time remaining ends.
The current state can be: roasting, cooling, idle, sleeping, connecting,
or unkown."""
self.active_recipe_item += 1
if self.active_recipe_item >= len(self.recipe):
# we're done... |
Process results by providers | def process_results(self):
""" Process results by providers """
for result in self._results:
provider = result.provider
self.providers.append(provider)
if result.error:
self.failed_providers.append(provider)
continue
if not ... |
Make lookup to dnsbl provider Parameters: * addr ( string ) - ip address to check * provider ( string ) - dnsbl provider | async def dnsbl_request(self, addr, provider):
"""
Make lookup to dnsbl provider
Parameters:
* addr (string) - ip address to check
* provider (string) - dnsbl provider
Returns:
* DNSBLResponse object
Raises:
* ValueError
"... |
Async check ip with dnsbl providers. Parameters: * addr - ip address to check | async def _check_ip(self, addr):
"""
Async check ip with dnsbl providers.
Parameters:
* addr - ip address to check
Returns:
* DNSBLResult object
"""
tasks = []
for provider in self.providers:
tasks.append(self.dnsbl_request(ad... |
sync check multiple ips | def check_ips(self, addrs):
"""
sync check multiple ips
"""
tasks = []
for addr in addrs:
tasks.append(self._check_ip(addr))
return self._loop.run_until_complete(asyncio.gather(*tasks)) |
A generator that will generate a range of floats. | def frange(start, stop, step, precision):
"""A generator that will generate a range of floats."""
value = start
while round(value, precision) < stop:
yield round(value, precision)
value += step |
Finds a connected device with the given VID: PID. Returns the serial port url. | def find_device(vidpid):
"""Finds a connected device with the given VID:PID. Returns the serial
port url."""
for port in list_ports.comports():
if re.search(vidpid, port[2], flags=re.IGNORECASE):
return port[0]
raise exceptions.RoasterLookupError |
Calculate PID output value for given reference input and feedback. | def update(self, currentTemp, targetTemp):
"""Calculate PID output value for given reference input and feedback."""
# in this implementation, ki includes the dt multiplier term,
# and kd includes the dt divisor term. This is typical practice in
# industry.
self.targetTemp = targ... |
Initilize the setpoint of PID. | def setPoint(self, targetTemp):
"""Initilize the setpoint of PID."""
self.targetTemp = targetTemp
self.Integrator = 0
self.Derivator = 0 |
This is a method that will be called when the time remaining ends. The current state can be: roasting cooling idle sleeping connecting or unkown. | def next_state(self):
"""This is a method that will be called when the time remaining ends.
The current state can be: roasting, cooling, idle, sleeping, connecting,
or unkown."""
if(self.roaster.get_roaster_state() == 'roasting'):
self.roaster.time_remaining = 20
... |
Load dict from file for random words. | def load_nouns(self, file):
"""
Load dict from file for random words.
:param str file: filename
"""
with open(os.path.join(main_dir, file + '.dat'), 'r') as f:
self.nouns = json.load(f) |
Load list from file for random mails | def load_dmails(self, file):
"""
Load list from file for random mails
:param str file: filename
"""
with open(os.path.join(main_dir, file + '.dat'), 'r') as f:
self.dmails = frozenset(json.load(f)) |
Load dict from file for random nicknames. | def load_nicknames(self, file):
"""
Load dict from file for random nicknames.
:param str file: filename
"""
with open(os.path.join(main_dir, file + '.dat'), 'r') as f:
self.nicknames = json.load(f) |
Returns list of random words. | def random_words(self, letter=None, count=1):
"""
Returns list of random words.
:param str letter: letter
:param int count: how much words
:rtype: list
:returns: list of random words
:raises: ValueError
"""
self.check_count(count)
words =... |
Return list of random nicks. | def random_nicks(self, letter=None, gender='u', count=1):
"""
Return list of random nicks.
:param str letter: letter
:param str gender: ``'f'`` for female, ``'m'`` for male and None for both
:param int count: how much nicks
:rtype: list
:returns: list of random n... |
Return random e - mails. | def randomMails(self, count=1):
"""
Return random e-mails.
:rtype: list
:returns: list of random e-mails
"""
self.check_count(count)
random_nicks = self.rn.random_nicks(count=count)
random_domains = sample(self.dmails, count)
return [
... |
Return sentences in list. | def get_sentences_list(self, sentences=1):
"""
Return sentences in list.
:param int sentences: how many sentences
:returns: list of strings with sentence
:rtype: list
"""
if sentences < 1:
raise ValueError('Param "sentences" must be greater than 0.')
... |
Return a sentence from list of words. | def make_sentence(list_words):
"""
Return a sentence from list of words.
:param list list_words: list of words
:returns: sentence
:rtype: str
"""
lw_len = len(list_words)
if lw_len > 6:
list_words.insert(lw_len // 2 + random.choice(range(-2, ... |
Find the cover image path in the OPF file. Returns a tuple: ( image content in base64 file extension ) | def _discover_cover_image(zf, opf_xmldoc, opf_filepath):
'''
Find the cover image path in the OPF file.
Returns a tuple: (image content in base64, file extension)
'''
content = None
filepath = None
extension = None
# Strategies to discover the cover-image path:
# e.g.: <meta name="... |
Returns a list of objects: { title: str src: str level: int index: int } | def _discover_toc(zf, opf_xmldoc, opf_filepath):
'''
Returns a list of objects: {title: str, src: str, level: int, index: int}
'''
toc = None
# ePub 3.x
tag = find_tag(opf_xmldoc, 'item', 'properties', 'nav')
if tag and 'href' in tag.attributes.keys():
filepath = unquote(tag.attribu... |
References: http:// idpf. org/ epub/ 201 and http:// idpf. org/ epub/ 301 1. Parse META - INF/ container. xml file and find the. OPF file path. 2. In the. OPF file find the metadata | def get_epub_metadata(filepath, read_cover_image=True, read_toc=True):
'''
References: http://idpf.org/epub/201 and http://idpf.org/epub/301
1. Parse META-INF/container.xml file and find the .OPF file path.
2. In the .OPF file, find the metadata
'''
if not zipfile.is_zipfile(filepath):
r... |
Returns the file. OPF contents of the ePub file | def get_epub_opf_xml(filepath):
'''
Returns the file.OPF contents of the ePub file
'''
if not zipfile.is_zipfile(filepath):
raise EPubException('Unknown file')
# print('Reading ePub file: {}'.format(filepath))
zf = zipfile.ZipFile(filepath, 'r', compression=zipfile.ZIP_DEFLATED, allowZi... |
u Склонение имени | def firstname(self, value, case, gender=None):
u"""
Склонение имени
:param value: Значение для склонения
:param case: Падеж для склонения (значение из класса Case)
:param gender: Грамматический род
"""
if not value:
raise ValueError('Firstname cannot ... |
u Склонение фамилии | def lastname(self, value, case, gender=None):
u"""
Склонение фамилии
:param value: Значение для склонения
:param case: Падеж для склонения (значение из класса Case)
:param gender: Грамматический род
"""
if not value:
raise ValueError('Lastname cannot ... |
u Склонение отчества | def middlename(self, value, case, gender=None):
u"""
Склонение отчества
:param value: Значение для склонения
:param case: Падеж для склонения (значение из класса Case)
:param gender: Грамматический род
"""
if not value:
raise ValueError('Middlename ca... |
u Разделяет имя на сегменты по разделителям в self. separators: param name: имя: return: разделённое имя вместе с разделителями | def __split_name(self, name):
u"""
Разделяет имя на сегменты по разделителям в self.separators
:param name: имя
:return: разделённое имя вместе с разделителями
"""
def gen(name, separators):
if len(separators) == 0:
yield name
else:... |
Expand a reference expression to individual spans. Also works on space - separated ID lists although a sequence of space characters will be considered a delimiter. | def expand(expression):
"""
Expand a reference expression to individual spans.
Also works on space-separated ID lists, although a sequence of space
characters will be considered a delimiter.
>>> expand('a1')
'a1'
>>> expand('a1[3:5]')
'a1[3:5]'
>>> expand('a1[3:5+6:7]')
'a1[3:5]... |
Compress a reference expression to group spans on the same id. Also works on space - separated ID lists although a sequence of space characters will be considered a delimiter. | def compress(expression):
"""
Compress a reference expression to group spans on the same id.
Also works on space-separated ID lists, although a sequence of space
characters will be considered a delimiter.
>>> compress('a1')
'a1'
>>> compress('a1[3:5]')
'a1[3:5]'
>>> compress('a1[3:5... |
Split the expression into individual selection expressions. The delimiters will be kept as separate items if keep_delimters = True. Also works on space - separated ID lists although a sequence of space characters will be considered a delimiter. | def selections(expression, keep_delimiters=True):
"""
Split the expression into individual selection expressions. The
delimiters will be kept as separate items if keep_delimters=True.
Also works on space-separated ID lists, although a sequence of space
characters will be considered a delimiter.
... |
Return the string that is the resolution of the alignment expression expression which selects ids from container. | def resolve(container, expression):
"""
Return the string that is the resolution of the alignment expression
`expression`, which selects ids from `container`.
"""
itemgetter = getattr(container, 'get_item', container.get)
tokens = []
expression = expression.strip()
for sel_delim, _id, _r... |
Return a list of ids denoting objects ( tiers or items ) in igt that are referred by the object denoted by id using a reference attribute in refattrs. If refattrs is None then consider all known reference attributes for the type of object denoted by _id_. In other words if b1 refers to a1 using alignment then referents... | def referents(igt, id, refattrs=None):
"""
Return a list of ids denoting objects (tiers or items) in `igt` that
are referred by the object denoted by `id` using a reference
attribute in `refattrs`. If `refattrs` is None, then consider all
known reference attributes for the type of object denoted by ... |
Return a list of ids denoting objects ( tiers or items ) in igt that refer to the given id. In other words if b1 refers to a1 then referrers ( igt a1 ) returns [ b1 ]. | def referrers(igt, id, refattrs=None):
"""
Return a list of ids denoting objects (tiers or items) in `igt` that
refer to the given `id`. In other words, if 'b1' refers to 'a1',
then `referrers(igt, 'a1')` returns `['b1']`.
"""
if refattrs is None:
result = {}
else:
result = {... |
>>> for anc in query. ancestors ( igt. get_item ( g1 ) refattrs = ( ALIGNMENT SEGMENTATION )):... print ( anc ) ( <Tier object ( id: g type: glosses ) at... > alignment <Tier object ( id: m type: morphemes ) at... > [ <Item object ( id: m1 ) at... > ] ) ( <Tier object ( id: m type: morphemes ) at... > segmentation <Tie... | def ancestors(obj, refattrs=(ALIGNMENT, SEGMENTATION)):
"""
>>> for anc in query.ancestors(igt.get_item('g1'), refattrs=(ALIGNMENT, SEGMENTATION)):
... print(anc)
(<Tier object (id: g type: glosses) at ...>, 'alignment', <Tier object (id: m type: morphemes) at ...>, [<Item object (id: m1) at ...>])
... |
>>> for des in query. descendants ( igt. get_item ( p1 ) refattrs = ( SEGMENTATION ALIGNMENT )):... print ( des ) ( <Tier object ( id: p type: phrases ) at... > segmentation <Tier object ( id: w type: words ) at... > [ <Item object ( id: w1 ) at... > ] ) ( <Tier object ( id: p type: phrases ) at... > alignment <Tier ob... | def descendants(obj, refattrs=(SEGMENTATION, ALIGNMENT), follow='first'):
"""
>>> for des in query.descendants(igt.get_item('p1'), refattrs=(SEGMENTATION, ALIGNMENT)):
... print(des)
(<Tier object (id: p type: phrases) at ...>, 'segmentation', <Tier object (id: w type: words) at ...>, [<Item object ... |
Decode a XigtCorpus element. | def default_decode(events, mode='full'):
"""Decode a XigtCorpus element."""
event, elem = next(events)
root = elem # store root for later instantiation
while (event, elem.tag) not in [('start', 'igt'), ('end', 'xigt-corpus')]:
event, elem = next(events)
igts = None
if event == 'start' a... |
Return a tuple each value being a line of the source file. | def _get_file_content(source):
"""Return a tuple, each value being a line of the source file.
Remove empty lines and comments (lines starting with a '#').
"""
filepath = os.path.join('siglists', source + '.txt')
lines = []
with resource_stream(__name__, filepath) as f:
for i, line in ... |
Check quickly whether file is rar archive. | def _get_rar_version(xfile):
"""Check quickly whether file is rar archive.
"""
buf = xfile.read(len(RAR5_ID))
if buf.startswith(RAR_ID):
return 3
elif buf.startswith(RAR5_ID):
xfile.read(1)
return 5
return 0 |
Proceed to next volume. | def _open_next(self):
"""Proceed to next volume."""
# is the file split over archives?
if (self._cur.flags & rarfile.RAR_FILE_SPLIT_AFTER) == 0:
return False
if self._fd:
self._fd.close()
self._fd = None
# open next part
self._volfil... |
Do not check final CRC. | def _check(self): # TODO: fix?
"""Do not check final CRC."""
if self._returncode:
rarfile.check_returncode(self, '')
if self._remain != 0:
raise rarfile.BadRarFile("Failed the read enough data") |
rescales a numpy array so that min is 0 and max is 255 | def _normalize(mat: np.ndarray):
"""rescales a numpy array, so that min is 0 and max is 255"""
return ((mat - mat.min()) * (255 / mat.max())).astype(np.uint8) |
returns a matrix that contains RGB channels and colors scaled from 0 to 255 | def to_24bit_gray(mat: np.ndarray):
"""returns a matrix that contains RGB channels, and colors scaled
from 0 to 255"""
return np.repeat(np.expand_dims(_normalize(mat), axis=2), 3, axis=2) |
returns an RGB matrix scaled by a matplotlib color map | def apply_color_map(name: str, mat: np.ndarray = None):
"""returns an RGB matrix scaled by a matplotlib color map"""
def apply_map(mat):
return (cm.get_cmap(name)(_normalize(mat))[:, :, :3] * 255).astype(np.uint8)
return apply_map if mat is None else apply_map(mat) |
Can be used to create a pygame. Surface from a 2d numpy array. | def mat_to_surface(mat: np.ndarray, transformer=to_24bit_gray):
"""Can be used to create a pygame.Surface from a 2d numpy array.
By default a grey image with scaled colors is returned, but using the
transformer argument any transformation can be used.
:param mat: the matrix to create the surface of.
... |
Creates a random id with the given length and charset. ## Parameters * length the number of characters in the id * charset what character set to use ( a list of characters ) * first_charset what character set for the first character * sep = what character to insert between groups * group = 0 how long the groups are ( d... | def random_id(length=16, charset=alphanum_chars, first_charset=alpha_chars, sep='', group=0):
"""Creates a random id with the given length and charset.
## Parameters
* length the number of characters in the id
* charset what character set to use (a list of characters)
* first_c... |
Merge any number of dictionaries | def merge_dict(data, *args):
"""Merge any number of dictionaries
"""
results = {}
for current in (data,) + args:
results.update(current)
return results |
Joins individual URL strings together and returns a single string. | def make_url(url, *paths):
"""Joins individual URL strings together, and returns a single string.
"""
for path in paths:
url = re.sub(r'/?$', re.sub(r'^/?', '/', path), url)
return url |
aggregate result | def aggregate_result(self, return_code, output, service_description='', specific_servers=None):
'''
aggregate result
'''
if specific_servers == None:
specific_servers = self.servers
else:
specific_servers = set(self.servers).intersection(specific_servers)
... |
send results | def send_results(self):
'''
send results
'''
for server in self.servers:
if self.servers[server]['results']:
if len(self.servers[server]['results']) == 1:
msg = MIMEText('')
msg['Subject'] = '[%(custom_fqdn)s] [%(servic... |
MAIN | def main():
"""MAIN"""
config = {
"api": {
"services": [
{
"name": "my_api",
"testkey": "testval",
},
],
"calls": {
"hello_world": {
"delay": 5,
... |
Parse the outgoing schema | def make_request(self, data):
"""Parse the outgoing schema"""
sch = MockItemSchema()
return Request(**{
"callname": self.context.get("callname"),
"payload": sch.dump(data),
}) |
Parse the outgoing schema | def populate_data(self, data):
"""Parse the outgoing schema"""
sch = MockItemSchema()
return Result(**{
"callname": self.context.get("callname"),
"result": sch.dump(data),
}) |
returns a handler that can be used with EventListener. listen () and returns when a key in keys is pressed | def key_press(keys):
"""returns a handler that can be used with EventListener.listen()
and returns when a key in keys is pressed"""
return lambda e: e.key if e.type == pygame.KEYDOWN \
and e.key in keys else EventConsumerInfo.DONT_CARE |
returns a handler that listens for unicode characters | def unicode_char(ignored_chars=None):
"""returns a handler that listens for unicode characters"""
return lambda e: e.unicode if e.type == pygame.KEYDOWN \
and ((ignored_chars is None)
or (e.unicode not in ignored_chars))\
else EventConsumerInfo.DONT_CARE |
Adds a new MouseProxy for the given group to the EventListener. mouse_proxies dict if it is not in there yet and returns the ( new ) MouseProxy. In listen () all entries in the current group of mouse_proxies are used. | def mouse_area(self, handler, group=0, ident=None):
"""Adds a new MouseProxy for the given group to the
EventListener.mouse_proxies dict if it is not in there yet, and returns
the (new) MouseProxy. In listen() all entries in the current group of
mouse_proxies are used."""
key = ... |
When listen () is called all queued pygame. Events will be passed to all registered listeners. There are two ways to register a listener: | def listen(self, *temporary_handlers):
"""When listen() is called all queued pygame.Events will be passed to all
registered listeners. There are two ways to register a listener:
1. as a permanent listener, that is always executed for every event. These
are registered by passing the ... |
Calls listen repeatedly until listen returns something else than None. Then returns listen s result. If timeout is not zero listen_until_return stops after timeout seconds and returns None. | def listen_until_return(self, *temporary_handlers, timeout=0):
"""Calls listen repeatedly until listen returns something else than None.
Then returns listen's result. If timeout is not zero listen_until_return
stops after timeout seconds and returns None."""
start = time.time()
w... |
Waits till one key was pressed n times. | def wait_for_n_keypresses(self, key, n=1):
"""Waits till one key was pressed n times.
:param key: the key to be pressed as defined by pygame. E.g.
pygame.K_LEFT for the left arrow key
:type key: int
:param n: number of repetitions till the function returns
:type n: i... |
Waits until one of the specified keys was pressed and returns which key was pressed. | def wait_for_keys(self, *keys, timeout=0):
"""Waits until one of the specified keys was pressed, and returns
which key was pressed.
:param keys: iterable of integers of pygame-keycodes, or simply
multiple keys passed via multiple arguments
:type keys: iterable
:par... |
The same as wait_for_keys but returns a frozen_set which contains the pressed key and the modifier keys. | def wait_for_keys_modified(self, *keys, modifiers_to_check=_mod_keys,
timeout=0):
"""The same as wait_for_keys, but returns a frozen_set which contains
the pressed key, and the modifier keys.
:param modifiers_to_check: iterable of modifiers for which the function... |
Returns a str that contains the single character that was pressed. This already respects modifier keys and keyboard layouts. If timeout is not none and no key is pressed within the specified timeout None is returned. If a key is ingnored_chars it will be ignored. As argument for irgnored_chars any object that has a __c... | def wait_for_unicode_char(self, ignored_chars=None, timeout=0):
"""Returns a str that contains the single character that was pressed.
This already respects modifier keys and keyboard layouts. If timeout is
not none and no key is pressed within the specified timeout, None is
returned. If ... |
Does not support the full range of ways rar can split as it d require reading the file to ensure you are using the correct way. | def _find_all_first_files(self, item):
"""
Does not support the full range of ways rar can split
as it'd require reading the file to ensure you are using the
correct way.
"""
for listed_item in item.list():
new_style = re.findall(r'(?i)\.part(\d+)\.rar^', list... |
find all matching data files in search_path search_path: path of directories to load from codecs: allow to override from list of installed returns array of tuples ( codec_object filename ) | def find_datafile(name, search_path, codecs=get_codecs()):
"""
find all matching data files in search_path
search_path: path of directories to load from
codecs: allow to override from list of installed
returns array of tuples (codec_object, filename)
"""
return munge.find_datafile(name, sear... |
find datafile and load them from codec TODO only does the first one kwargs: default = if passed will return that on failure instead of throwing | def load_datafile(name, search_path, codecs=get_codecs(), **kwargs):
"""
find datafile and load them from codec
TODO only does the first one
kwargs:
default = if passed will return that on failure instead of throwing
"""
return munge.load_datafile(name, search_path, codecs, **kwargs) |
Initialize what requires credentials/ secret files. | def cred_init(
self,
*,
secrets_dir: str,
log: Logger,
bot_name: str,
) -> None:
"""
Initialize what requires credentials/secret files.
:param secrets_dir: dir to expect credentials in and store logs/history in.
:param log:... |
Send birdsite message. | def send(
self,
*,
text: str,
) -> List[OutputRecord]:
"""
Send birdsite message.
:param text: text to send in post.
:returns: list of output records,
each corresponding to either a single post,
or an error.
"""
... |
Upload media to birdsite and send status and media and captions if present. | def send_with_media(
self,
*,
text: str,
files: List[str],
captions: List[str]=[]
) -> List[OutputRecord]:
"""
Upload media to birdsite,
and send status and media,
and captions if present.
:param text: tweet text.
... |
Performs batch reply on target account. Looks up the recent messages of the target user applies the callback and replies with what the callback generates. | def perform_batch_reply(
self,
*,
callback: Callable[..., str],
lookback_limit: int,
target_handle: str,
) -> List[OutputRecord]:
"""
Performs batch reply on target account.
Looks up the recent messages of the target user,
a... |
Send DM to owner if something happens. | def send_dm_sos(self, message: str) -> None:
"""
Send DM to owner if something happens.
:param message: message to send to owner.
:returns: None.
"""
if self.owner_handle:
try:
# twitter changed the DM API and tweepy (as of 2019-03-08)
... |
Handle error while trying to do something. | def handle_error(
self,
*,
message: str,
error: tweepy.TweepError,
) -> OutputRecord:
"""
Handle error while trying to do something.
:param message: message to send in DM regarding error.
:param e: tweepy error object.
:returns... |
Handle uploading all captions. | def _handle_caption_upload(
self,
*,
media_ids: List[str],
captions: Optional[List[str]],
) -> None:
"""
Handle uploading all captions.
:param media_ids: media ids of uploads to attach captions to.
:param captions: captions to be attac... |
: reference: https:// developer. twitter. com/ en/ docs/ direct - messages/ sending - and - receiving/ api - reference/ new - event. html | def _send_direct_message_new(self, messageobject: Dict[str, Dict]) -> Any:
"""
:reference: https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-event.html
"""
headers, post_data = _buildmessageobject(messageobject)
newdm_path = "/direct_me... |
Takes crash data via stdin and generates a Socorro signature | def main():
"""Takes crash data via stdin and generates a Socorro signature"""
parser = argparse.ArgumentParser(description=DESCRIPTION)
parser.add_argument(
'-v', '--verbose', help='increase output verbosity', action='store_true'
)
args = parser.parse_args()
generator = SignatureGenera... |
Update internel configuration dict with config and recheck | def add_config(self, config):
"""
Update internel configuration dict with config and recheck
"""
for attr in self.__fixed_attrs:
if attr in config:
raise Exception("cannot set '%s' outside of init", attr)
# pre checkout
stages = config.get('s... |
called after config was modified to sanity check raises on error | def check_config(self):
"""
called after config was modified to sanity check
raises on error
"""
# sanity checks - no config access past here
if not getattr(self, 'stages', None):
raise NotImplementedError("member variable 'stages' must be defined")
#... |
called after Defintion was loaded to sanity check raises on error | def check_definition(self):
"""
called after Defintion was loaded to sanity check
raises on error
"""
if not self.write_codec:
self.__write_codec = self.defined.data_ext
# TODO need to add back a class scope target limited for subprojects with sub target sets... |
find all matching data files in search_path returns array of tuples ( codec_object filename ) | def find_datafile(self, name, search_path=None):
"""
find all matching data files in search_path
returns array of tuples (codec_object, filename)
"""
if not search_path:
search_path = self.define_dir
return codec.find_datafile(name, search_path) |
find datafile and load them from codec | def load_datafile(self, name, search_path=None, **kwargs):
"""
find datafile and load them from codec
"""
if not search_path:
search_path = self.define_dir
self.debug_msg('loading datafile %s from %s' % (name, str(search_path)))
return codec.load_datafile(nam... |
run all configured stages | def run(self):
""" run all configured stages """
self.sanity_check()
# TODO - check for devel
# if not self.version:
# raise Exception("no version")
# XXX check attr exist
if not self.release_environment:
raise Exception("no instance name")
time_start = t... |
Return POSIX timestamp as float. | def timestamp(dt):
"""
Return POSIX timestamp as float.
>>> timestamp(datetime.datetime.now()) > 1494638812
True
>>> timestamp(datetime.datetime.now()) % 1 > 0
True
"""
if dt.tzinfo is None:
return time.mktime((
dt.year, dt.month, dt.day,
dt.hour, dt.minute, dt.second,
-1, -1, -1)) + dt.microsecond... |
Rate limit a function. | def rate_limited(max_per_hour: int, *args: Any) -> Callable[..., Any]:
"""Rate limit a function."""
return util.rate_limited(max_per_hour, *args) |
Repair a corrupted IterationRecord with a specific known issue. | def _repair(record: Dict[str, Any]) -> Dict[str, Any]:
"""Repair a corrupted IterationRecord with a specific known issue."""
output_records = record.get("output_records")
if record.get("_type", None) == "IterationRecord" and output_records is not None:
birdsite_record = output_records.get("birdsite"... |
Get object back from dict. | def from_dict(cls, obj_dict: Dict[str, Any]) -> "IterationRecord":
"""Get object back from dict."""
obj = cls()
for key, item in obj_dict.items():
obj.__dict__[key] = item
return obj |
Post text - only to all outputs. | def send(
self,
*args: str,
text: str=None,
) -> IterationRecord:
"""
Post text-only to all outputs.
:param args: positional arguments.
expected: text to send as message in post.
keyword text argument is preferred over this.
... |
Post with one media item to all outputs. Provide filename so outputs can handle their own uploads. | def send_with_one_media(
self,
*args: str,
text: str=None,
file: str=None,
caption: str=None,
) -> IterationRecord:
"""
Post with one media item to all outputs.
Provide filename so outputs can handle their own uploads.
:par... |
Post with several media. Provide filenames so outputs can handle their own uploads. | def send_with_many_media(
self,
*args: str,
text: str=None,
files: List[str]=None,
captions: List[str]=[],
) -> IterationRecord:
"""
Post with several media.
Provide filenames so outputs can handle their own uploads.
:param... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.