content
stringlengths 39
9.28k
| sha1
stringlengths 40
40
| id
int64 8
710k
|
---|---|---|
def find_parent_by_name(element, names):
"""
Find the ancestor for an element whose name matches one of those
in names.
Args:
element: A BeautifulSoup Tag corresponding to an XML node
Returns:
A BeautifulSoup element corresponding to the matched parent, or None.
For example, assuming the following XML structure:
<static>
<anything>
<entry name="Hello" /> # this is in variable 'Hello'
</anything>
</static>
el = find_parent_by_name(Hello, ['static'])
# el is now a value pointing to the '<static>' element
"""
matching_parents = [i.name for i in element.parents if i.name in names]
if matching_parents:
return matching_parents[0]
else:
return None
|
b55aa8704c78c9bfbb30e691ccd33ded10aa2fe6
| 515,328 |
import fractions
def change_to_rational(number):
"""convert a number to rantional
Keyword arguments: number
return: tuple like (1, 2), (numerator, denominator)
"""
f = fractions.Fraction(str(number))
return (f.numerator, f.denominator)
|
96b581ad5fb5ce0880210eea274e7aa5477d40a4
| 318,962 |
def pybel_to_inchi(pybel_mol):
"""
Convert an Open Babel molecule object to InChI
"""
inchi = pybel_mol.write('inchi', opt={'F': None}).strip() # Add fixed H layer
return inchi
|
6facb16bbaeb1b37074d2eb106f9b2769cb1a9a0
| 321,562 |
def tofloat(v):
"""Check and convert a string to a real number"""
try:
return float(v) if v != '.' else v
except ValueError:
raise ValueError('Could not convert %s to float' % v)
|
9345a55bcd4f4e8e57aef9d456eb6ba7e0b26646
| 640,376 |
def parabola_through_three_points(p1, p2, p3):
"""
Calculates the parabola a*(x-b)+c through three points. The points should be given as (y, x) tuples.
Returns a tuple (a, b, c)
"""
# formula taken from http://stackoverflow.com/questions/4039039/fastest-way-to-fit-a-parabola-to-set-of-points
# Avoid division by zero in calculation of s
if p2[0] == p3[0]:
temp = p2
p2 = p1
p1 = temp
s = (p1[0]-p2[0])/(p2[0]-p3[0])
b = (-p1[1]**2 + p2[1]**2 + s*(p2[1]**2 - p3[1]**2)) / (2*(-p1[1] + p2[1] + s*p2[1] - s*p3[1]))
a = (p1[0] - p2[0]) / ((p1[1] - b)**2 - (p2[1] - b)**2)
c = p1[0] - a*(p1[1] - b)**2
return (a, b, c)
|
477c3a4190dc04c26edd4eedf7232e1f64003834
| 642,682 |
import requests
def get_csv_zip_url(table_id)->str:
"""
Returns the url for a table_id to extract raw data from Stats Canada.
Parameters
--------
table_id : int
Statistics Canada Table ID
Returns
--------
str
http address for downloading zipped csv file
References
--------
Statistics Canada developer guide:
https://www.statcan.gc.ca/eng/developers/wds/user-guide#a12-6
"""
stats_can_url = 'https://www150.statcan.gc.ca/t1/wds/rest/'
func = 'getFullTableDownloadCSV/'
table_id = str(table_id) + '/'
language = 'en'
api_call = stats_can_url + func + table_id + language
response = requests.get(api_call)
return response.json()['object']
|
9292c2e09f2c29f1c234499e7a0632b5c5605c58
| 608,654 |
def preprocess_examples(examples, mode='train'):
"""
For training set and dev set, treat each utterance of the first speaker as
the response, and concatenate the goal, knowledge and the dialog’s previous
utterances as the history. In this way, multiple history-response pairs
are constructed.
"""
if mode == 'test':
return examples
new_examples = []
for example in examples:
conversation = example['conversation']
for i in range(0, len(conversation), 2):
new_examples.append({
'goal': example['goal'],
'knowledge': example['knowledge'],
'history': conversation[:i],
'response': conversation[i]
})
return new_examples
|
99beb7b61f7c6af00d30f751ddddc87be4fdabde
| 590,498 |
def edit_is_rejected_addition(edit):
"""
Returns boolean whether an edit is a rejected addition.
"""
return edit.EditType == 'A' and edit.ReviewStatus == 'R'
|
7b4b8e0e91f477513c9c27e9ead926489872ef2c
| 388,583 |
import json
def get_es_config(file_path):
"""
Reads a json file containing the elastic search credentials and url.
The file is expected to have 'url', 'username' and 'password' keys
"""
with open(file_path) as stream:
credentials = json.load(stream)
return (credentials['url'],
(credentials['username'], credentials['password']),
credentials['host'])
|
cdf3e7a3566604445cff1257b57486072c11a469
| 90,439 |
def getFormatName(qry, fmt):
"""
Retrieves a format name, given a format
"""
return qry["searches"][fmt]["name"]
|
486fa840246136f07b9ee8011cda7660eb473b15
| 524,618 |
def group4_forward_branch(layer, in_tensor):
"""Defines group 1 connections.
Args:
layer (torch.nn.Module):
Network layer.
in_tensor (torch.Tensor):
Input tensor.
Returns:
torch.Tensor: Output of group 1 layer.
"""
a = layer["up1"](in_tensor)
return layer["conv1"](a)
|
3a8ce771ac18fe00b033233482b8084c0692de00
| 602,127 |
def chunk(input_data, size):
"""
Chunk given bytes into parts
:param input_data: bytes to split
:param size: size of a single chunk
:return: list of chunks
"""
assert len(input_data) % size == 0, \
"can't split data into chunks of equal size, try using chunk_with_remainder or pad data"
return [input_data[i:i + size] for i in range(0, len(input_data), size)]
|
83bb4ad9a4e3b51e9063d532ed35794e8d051334
| 237,359 |
def convert_float_coord_to_string(coord, p=2):
"""Convert a (lon,lat) coord to string."""
lon, lat = round(coord[0], p), round(coord[1], p)
LA, LO = 'n', 'e'
if lat < 0: LA = 's'
if lon < 0: LO = 'w'
lat_s = "%.2f" % round(abs(lat),2)
lon_s = "%.2f" % round(abs(lon),2)
coord_s = '%s%s%s%s' % (LA, lat_s.zfill(p+3), LO, lon_s.zfill(p+4))
return coord_s
|
eba6a21b91f03c7b4fbf785e869f06a25c68a70c
| 373,127 |
def base_url(host, port):
"""
Provides base URL for HTTP Management API
:param host: JBossAS hostname
:param port: JBossAS HTTP Management Port
"""
url = "http://{host}:{port}/management".format(host=host, port=port)
return url
|
3c132c461bb25a497e774f06cfc0b7a159fbb4e3
| 547,800 |
def mutindex2pos(x, start, end, mut_pos):
"""
Convert mutation indices back to genome positions
"""
if x == -.5:
return start
elif x == len(mut_pos) - .5:
return end
else:
i = int(x - .5)
j = int(x + .5)
return (mut_pos[i] + mut_pos[j]) / 2.0
|
06e09a0a3281ab2de076e28a32cc08e37c610fce
| 634,718 |
def gene_catalogue(db):
"""Get list of genes from database."""
cur = db.cursor()
cur.execute('SELECT entrez, gene '
'FROM genes;')
results = cur.fetchall()
# format into single list
genes = []
for item in results:
genes.append([item[0], item[1]])
return genes
|
fdaadf567ea81953333f6c32f987794d1c5b6ac7
| 443,883 |
def bi_var_equal(var1, unifier1, var2, unifier2):
"""Returns True iff variable VAR1 in unifier UNIFIER1 is the same
variable as VAR2 in UNIFIER2.
"""
return (var1 == var2 and unifier1 is unifier2)
|
315639eddf62184e070b62a8f83ebe22c16c4d0c
| 234,643 |
def _index_ranges_without_offsets(index_ranges_with_offsets):
"""Return index_ranges excluding the offset dimension."""
return index_ranges_with_offsets[1:]
|
414d2ed39c32a4df7b28f1f26e9bef5d720659bc
| 450,324 |
from unittest.mock import Mock
def theme_mock(name='example-theme'):
"""Get a mock representing a theme object.
:param name: a name of a theme represented by the mock
:returns: the mock.
"""
theme = Mock()
theme.name = name
return theme
|
9ace283d551f834dc28977de6409c4ce16f11c4f
| 502,013 |
def xywh_from_bbox(minx, miny, maxx, maxy):
"""Convert a bounding box from a numeric list to a numeric dict representation."""
return {
'x': minx,
'y': miny,
'w': maxx - minx,
'h': maxy - miny,
}
|
e6116c805e65dd43231e33bf5a5e7d64ccc28cec
| 180,218 |
import re
def valid_email(email=None):
"""Returns True if argument is a string with valid email adddress"""
if not email:
return False
pattern = r"[^@]+@[^@]+\.[^@]+"
p = re.compile(pattern)
if p.match(email):
return True
return False
|
1c6cd70d8eb6bb0053dee25b7cb0f9f4055395b3
| 67,389 |
from typing import TextIO
from typing import Dict
def read_rank_file(input_fh: TextIO, max_records=-1) -> Dict[str, int]:
"""Reads lines and returns a dictionary where each key is a line and each value is the rank / line number.
Repeated lines are ignored.
"""
output_ranks = {}
line_number = 1
for line in input_fh:
text = line.strip()
if text not in output_ranks:
output_ranks[text] = line_number
line_number += 1
if line_number > max_records > 0:
break
return output_ranks
|
a45e7829862fe6b2aed0e3e70035a57296e1c608
| 474,948 |
def twiddle_bit(bb, bit):
""" Flip a bit from on to off and vice-versa """
return bb ^ (1 << bit)
|
b2520909ce0165d46a72b84cadbb065da2ebd8c2
| 572,023 |
import collections
def __units_seen(states, army_type):
"""Identifies units seen, adding to dictionary in the order seen
Args:
states (list): list of game states.
army_type (string): "Commanding" or "Opposing".
Returns:
Dictionary: { unit_id : step_when_seen } <int> : <int>
"""
units_seen_dict = collections.OrderedDict()
for state in states:
for unit in state['Armies'][army_type]:
if not unit in units_seen_dict.keys():
units_seen_dict[unit] = state['Step']
return units_seen_dict
|
d0dcb1c7f2db5b3ec0c243c415758cf29efb7cc5
| 244,560 |
def list_parser_dest(parser, exclude=('help',)):
"""
Return parser list of ``dest``.
Parameters
----------
parser : argparse.ArgumentParser
Parser.
exclude : list, tuple, default=('help',)
Brick name.
Returns
-------
args : list
Parser list of ``dest``.
"""
return [act.dest for act in parser._actions if act.dest not in exclude]
|
1c67770b68dd22be82e097afad321e25b969fe1d
| 528,848 |
def _uint32(x):
"""Transform x's type to uint32."""
return x & 0xFFFFFFFF
|
8b7547738f69b7aa39b40e85852ebbf03cc6fbfa
| 43,749 |
def tasks(tmpdir):
"""
Set up a project with some tasks that we can test displaying
"""
task_l = [
"",
" ^ this is the first task (released)",
" and it has a second line",
" > this is the second task (committed)",
" . this is the third task (changed, not yet committed)",
" - this is the fourth task (not yet made)",
" and this one has a second line also",
" + fifth task -- completed",
" < sixth task -- moved elsewhere",
" x seventh task -- abandoned",
"",
]
# project dir
prjdir = tmpdir.join("myproj")
# .project file
prjdir.join(".project").ensure()
# DODO file with content
dodo = prjdir.join("DODO")
dodo.write("\n".join(task_l) + "\n")
data = {
'tmpdir': tmpdir,
'prj': prjdir,
'dodo': dodo,
}
return data
|
64104bde2aab55021cf0d49fbb1d47670d0e4e0d
| 704,376 |
def url_gen_dicter(inlist, filelist):
"""
Prepare name:URL dicts for a given pair of names and URLs.
:param inlist: List of dictionary keys (OS/radio platforms)
:type inlist: list(str)
:param filelist: List of dictionary values (URLs)
:type filelist: list(str)
"""
pairs = {title: url for title, url in zip(inlist, filelist)}
return pairs
|
36d4e066524903f7a5a19f5ca402502561d7ff52
| 36,970 |
def translate_table(fields):
"""Parse form fields into a list addresses"""
addrs = list()
for f in sorted(fields):
if f.startswith('addr') and fields[f]:
addrs.append(fields[f])
return addrs
|
a5648e43fb58723a51d28d328c15bfa05d0e1639
| 235,758 |
def reduce_deg(deg):
""" Return *deg* in the range [-180, 180) """
return (deg+180) % 360 - 180
|
2a11f2281c9a1937052ad800c82a545f0f0d0946
| 349,550 |
import socket
def create_rawsock(iface):
"""Creates a new raw socket object.
The socket sends/receives data at the link layer (TCP/IP model)/data-link
layer (OSI model).
Args:
iface: A string specifying the name of the network interface to which
the raw socket should be bound. For example "eth0".
Returns:
A socket object.
"""
sock = socket.socket(socket.AF_PACKET,
socket.SOCK_RAW,
socket.htons(socket.SOCK_RAW))
sock.bind((iface, socket.SOCK_RAW))
return sock
|
ea56408403ada6b9750265547677028c197ae933
| 695,946 |
def format_with_default_value(handle_missing_key, s, d):
"""Formats a string with handling of missing keys from the dict.
Calls s.format(**d) while handling missing keys by calling
handle_missing_key to get the appropriate values for the missing keys.
Args:
handle_issing_key: A function that takes a missing key as the argument
and returns a value for the value of the missing key.
s: A format string.
d: A dict providing values to format s.
Returns s.format(**d) with missing keys handled by calling
handle_missing_key to get the values for the missing keys.
"""
copy = dict(**d)
while True:
try:
return s.format(**copy)
except KeyError as ex:
key = ex.args[0]
copy[key] = handle_missing_key(key)
|
957b851dcacfc98c5bcdb5f1c76850014f8262f5
| 22,559 |
def validate_float(data):
"""
Checks if data contains something that can be used as float:
- string containing float
- int
- float itself
and converts it to float.
Return:
- float if possible
- 0.0 if empty string
- None if float not possible
"""
if isinstance(data, str):
if len(data) > 0:
if data.lstrip('-').replace('.', '').isdigit():
return float(data)
else:
return 0.0
elif isinstance(data, float):
return data
elif isinstance(data, int):
return float(data)
else:
return None
|
d64e6bcdb6c730dc486284ca98e9f79efbcec9e4
| 257,112 |
def expression_split(src):
"""
parse a string and return a list of pair with
open and close parenthesis
The result is generated in the order that the inner-most and left-most
parenthesis will be at the start of the list, which logically should be processed first
:param:
src: input string
:return:
list of pair contains the index of ( and )
"""
result = []
open_index = []
for ind, _ in enumerate(src):
if src[ind] == "(":
open_index.append(ind)
if src[ind] == ")":
result.append((open_index.pop(), ind))
return result
|
92a8a604abbb1b4a8099bdb8969eef702b44fc38
| 230,714 |
def remove_white_spaces_a_comment(mystr):
"""
Remove all the whitespaces in a comment
"""
mystr = ' '.join([x.strip() for x in mystr.split()])
return mystr
|
58ded95d7c02c86459e13180d83db7cfaf86145a
| 366,043 |
from typing import Dict
from typing import Any
from typing import Optional
def get_name(hook: Dict[Any, Any]) -> Optional[str]:
"""
Creates a name based on the webhook call it recieved
Format: Timestamp_Devicename.mp4
Removes any characters that are not regular characters, numbers, '_' '.' or '-'
to ensure the filename is valid
:param hook: Dict with webhook response
:return: filename: str, None if invalid hook failed
"""
if 'extraInfo' not in hook:
return
timestamp = hook.get('createdOn', '').replace(':', '-')
device_name = hook['extraInfo'].get('Device name', '').replace(' ', '_')
if timestamp == '' or device_name == '':
return
name = f'{timestamp}_{device_name}.mp4'
# https://stackoverflow.com/questions/7406102/create-sane-safe-filename-from-any-unsafe-string
file_name = "".join([c for c in name if
c.isalpha()
or c.isdigit()
or c == '_'
or c == '.'
or c == '-']).rstrip()
return file_name
|
2b9a034ee551894adc4a03cebce3711cdbad58d3
| 679,814 |
import math
def i4_bit_lo0(n):
"""
I4_BIT_LO0 returns the position of the low 0 bit base 2 in an integer.
Example:
+------+------------+----
| N | Binary | BIT
+------+------------+----
| 0 | 0 | 1
| 1 | 1 | 2
| 2 | 10 | 1
| 3 | 11 | 3
| 4 | 100 | 1
| 5 | 101 | 2
| 6 | 110 | 1
| 7 | 111 | 4
| 8 | 1000 | 1
| 9 | 1001 | 2
| 10 | 1010 | 1
| 11 | 1011 | 3
| 12 | 1100 | 1
| 13 | 1101 | 2
| 14 | 1110 | 1
| 15 | 1111 | 5
| 16 | 10000 | 1
| 17 | 10001 | 2
| 1023 | 1111111111 | 1
| 1024 | 0000000000 | 1
| 1025 | 0000000001 | 1
Parameters:
Input, integer N, the integer to be measured.
N should be nonnegative.
Output, integer BIT, the position of the low 1 bit.
"""
bit = 0
i = math.floor(n)
while (1):
bit = bit + 1
i2 = math.floor(i / 2.)
if (i == 2 * i2):
break
i = i2
return bit
|
f8766d351183ecb9fe74b836a4bbf226e8db1501
| 591,364 |
def binary(val):
""" validates if the value passed is binary (true/false)"""
if type(val) == bool:
return val
else:
raise ValueError("random seed is a boolean flag")
|
fd5c5f8229fb9b227b5aff9a50b063463b51147c
| 680,643 |
def pad_sents(sents, padding_token_index):
"""
Pad the sents(in word index form) into same length so they can form a matrix
# 15447
>>> sents = [[1,2,3], [1,2], [1,2,3,4,5]]
>>> pad_sents(sents, padding_token_index = -1)
[[1, 2, 3, -1, -1], [1, 2, -1, -1, -1], [1, 2, 3, 4, 5]]
"""
max_len_sent = max(sents,
key = lambda sent: len(sent))
max_len = len(max_len_sent)
get_padding = lambda sent: [padding_token_index] * (max_len - len(sent))
padded_sents = [(sent + get_padding(sent))
for sent in sents]
return padded_sents
|
0063d8716f7081644e4353de662d58f0dc04e8fe
| 13,550 |
import json
def build_search_body(event):
"""Extract owners and filters from event."""
owners = json.loads(event["Owners"])
filters = json.loads(event["Filters"])
return {"Owners": owners, "Filters": filters}
|
07818f59cd992cb10e5dd28d112873c136bf5dc1
| 625,885 |
def brws_show_url(driver, _):
"""Shows the current url"""
return driver.current_url
|
9fb018919b3c68263aae8a0dcbae7a40571fe413
| 160,834 |
def get_crop_margins(page, crop_percent, side='both'):
""" Get the margins to remove from all sides using the crop_percent """
width, height = page.mediaBox.upperRight
w_diff, h_diff = float(width) * (crop_percent / 2), float(height) * (crop_percent / 2)
scale = (width / (width - w_diff * 2))
if side == 'left':
return (w_diff * 2, h_diff), (width, height - h_diff), scale
elif side == 'right':
return (0, h_diff), (width - w_diff * 2, height - h_diff), scale
else:
return (w_diff, h_diff), (width - w_diff, height - h_diff), scale
|
a2b4ecd86b9bf4922c33f856f3f7eb4d242a0d9f
| 600,517 |
from typing import Dict
import yaml
import click
def _load_yaml(filepath: str) -> Dict:
"""
Read content from yaml file.
:param filepath: str path to yaml file.
:return: dict YAML content
"""
with open(filepath, "r") as f:
try:
return yaml.safe_load(f)
except yaml.YAMLError as e:
raise click.ClickException(
"Loading yaml config from {} failed: {}".format(filepath, e)
)
|
69e0f84d9fddf0a2bdc9d151be9baebe4d658b9f
| 77,143 |
def humancoords_to_0interbase( start, stop ):
"""
The typical human-readable coordinate system, such as found in GBK flat files,
has a start and stop coordinate only. They are 1-based, on-base coordinates
and features on a reverse strand are indicated by having start > stop. This
transforms them into the GMOD standard 0-based inter-base coordinates.
Returns a list of fmin, fmax and strand values.
"""
fmin = start
fmax = stop
strand = 1
if ( stop < start ):
fmin = stop
fmax = start
strand = -1
fmin -= 1
return (fmin, fmax, strand)
|
9ef3230b0b9fbc3b4c8d993a8ecf091f3b2b85e6
| 494,284 |
def post_directory_path(instance, filename):
"""
file will be uploaded to MEDIA_ROOT/post_<post_id>/<filename>
:param instance:
:param filename:
:return:
"""
return 'post_{0}/{1}'.format(instance.post_id, filename)
|
b0bb740cfc3c5e5739bbd188741ff3c167bffd0e
| 417,905 |
def confopt_bool(confstr):
"""Check and return a boolean option from config."""
if isinstance(confstr, str):
if confstr.lower() in ['yes', 'true', '1']:
return True
else:
return False
else:
return bool(confstr)
|
9303c1944b13d390b3b06eed0d4cc13b4b764e8e
| 200,276 |
def get_rt(user_input, bound):
"""
Get reproduction rate from scenario choice.
"""
rules = {
"estavel": lambda x: x, # cenario estavel
"positivo": lambda x: x / 2, # cenario positivo
"negativo": lambda x: x * 2, # cenario negativo
}
return rules[user_input["strategy"]](user_input["rt_values"][bound])
|
42180ef08f21c081df5c74b6aab6deed3eeefc8f
| 270,075 |
def get_type(line):
"""
Returns either a string, indicating whether this is a wired, wireless,
or loopback interface, or None if this can not be determinted.
:param line: line of output from: ip a
"""
if "fq_codel" in line:
return "wired"
if "mq" in line:
return "wireless"
if "noqueue" in line:
return "loopback"
return None
|
e80d55dbb71540e1b8027258635e0273ddde95a2
| 301,473 |
def get_head(observation):
"""Given the current state of the snake environment, finds where the head of the snake is.
Args:
observation (numpy array): a 4xMxN ndarray.
Returns:
tuple: a tuple of length 2 representing the location of the head of the snake on a 2D grid.
"""
one_hot_head = observation[0]
for i in range(one_hot_head.shape[0]):
for j in range(one_hot_head.shape[1]):
if one_hot_head[i][j] == 1:
return (i, j)
return (-1, -1)
|
fe0c846133741ce5ff5b713e957aa03b98052750
| 196,844 |
import re
def valid_manifest_key(key):
"""Validate manifest key to make sure only top level manifests are processed"""
result = re.search(r'\d{8}-\d{8}\/((?:\w+-)+\w+)\.json$', key)
if result:
return True
return False
|
afc8fc998206166bd676b58f8b989a904702404d
| 411,729 |
def el (name, content):
"""Write a XML element with given element tag name (incl. element attributes) and the element's inner content."""
return "<%s>%s</%s>" % (name, content, name.partition(" ")[0])
|
8100779aa7935eb3ca0ea0c720508c1728c1874d
| 46,287 |
import click
def parse_rangelist(rli):
"""Parse a range list into a list of integers"""
try:
mylist = []
for nidrange in rli.split(","):
startstr, sep, endstr = nidrange.partition("-")
start = int(startstr, 0)
if sep:
end = int(endstr, 0)
if end < start:
mylist.extend(range(start, end - 1, -1))
else:
mylist.extend(range(start, end + 1))
else:
mylist.append(start)
except ValueError:
# pylint: disable=raise-missing-from
raise click.ClickException("Invalid range list %s" % rli)
return mylist
|
321496a1170b81d02b8378d687d8ce6d6295bff6
| 6,303 |
def compute_precision(confusionMatrix):
"""
Compute precision based on a Confusion Matrix
with prediction on rows
and truth on columns.
precision = true positive / (true positive + false positive)
"""
precision = []
for i in range(confusionMatrix.shape[0]):
tot = 0
for j in range(confusionMatrix.shape[0]):
tot += confusionMatrix[i, j]
correct = confusionMatrix[i, i]
precision.append(correct/tot)
return precision
|
24f51be1de97ed9a7257ba63787f84425e920f2f
| 209,319 |
def store_till_end_callback_factory(destination=lambda m: None):
"""
A :func:`callback_factory` which stores the messages in a list
and send them to the destination at the last message
Parameters
----------
destination : callable (Default : destination=lambda m: None)
A function which takes as input a list of string
Return
------
:func:`store_till_end_callback`
"""
messages = []
def store_till_end_callback(string, last_com=False):
"""
A :func:`callback` which stores the messages in a list
and send them to the destination at the last message
Parameters
----------
string : str
The string to process
last_com : bool (Default : False)
Whether is it the last message or not
"""
messages.append(string)
if last_com:
destination(messages)
return store_till_end_callback
|
6cd687569eb107c9c786186610926a708d4f83d5
| 168,362 |
def grade_stability(avg_smape):
"""Qualitative label for the average symmetric mean absolute percentage
error (SMAPE).
Parameters
----------
avg_smape : float (> 0)
The average absolute relative difference.
Returns
-------
qualitative_label : str
The qualitative label for the given average SMAPE. Can be: 'poor',
'moderate', 'good' or 'excellent'
"""
qualitative_label = None
if avg_smape <= 5.0:
qualitative_label = 'excellent'
elif avg_smape <= 10.0:
qualitative_label = 'good'
elif avg_smape <= 20.0:
qualitative_label = 'moderate'
else:
qualitative_label = 'poor'
return qualitative_label
|
663916d6f52a86514dfd8b418e7f5b7f354ed84e
| 348,982 |
def normalize_brightness_dict(brightness_dict):
"""Usually the distribution of the character brightness for a given font
is not as diverse as we would like it to be. This results in a pretty
poor result during the image to ASCII art conversion (if used as-is).
Because of this it's much better to normalize the brightness distribution.
Normalization widens the distribution ranges to 8-bit 0-255 range.
Args:
brightness_dict (dict): A map of characters to brightness.
Returns:
dict: normalized map of characters to brightness.
"""
b_min, b_max = 255, 0
for brightness in brightness_dict.values():
b_min = min(b_min, brightness)
b_max = max(b_max, brightness)
def widen(b):
"""Using the min and max bounds to widen the char brightness"""
return int(round( ( (b - b_min) / (b_max - b_min) ) * 255 ))
return {char: widen(brightness) for char, brightness in brightness_dict.items()}
|
fa857be51d983c96ec03856da252935eb44cb6be
| 677,036 |
def catplot_abscissa(x_order, hue_order=None, xtype='center'):
"""
Returns a dict that contains, for each possibly combination of x and hue
values, the abscissa of the corresponding bar in any Facet of a
seaborn 'bar' catplot called with x_order and hue_order as arguments.
Depending on the value of xtype, the abscissas of the center, left or right
of the bars is returned.
"""
assert xtype in ['center', 'left', 'right']
delta = .5 if xtype=='center' else (0. if xtype=='left' else 1)
origin = 0
grp_stride = 1
grp_width = .8
if hue_order is None:
nb_hues = 1
else:
nb_hues = len(hue_order)
bar_width = grp_width/float(nb_hues)
d = {}
for i, xval in enumerate(x_order):
if not(hue_order is None):
for j, hval in enumerate(hue_order):
d[xval, hval] = origin + grp_stride*i - grp_width/2. +\
(j+delta)*bar_width
else:
# if no hues, groups contain a single bar
d[xval] = origin + grp_stride*i - grp_width/2. + delta*grp_width
return d
|
c62dfe26027bc4d9be97c599df9dd374e2e551a2
| 567,681 |
def sdp_term_p(f):
"""Returns True if `f` has a single term or is zero. """
return len(f) <= 1
|
1fbefa0f751d0583f4c20b81289df2b4ca4dfca6
| 47,063 |
def get_dataset_json(met, version):
"""Generated HySDS dataset JSON from met JSON."""
return {
"version": version,
"label": met['data_product_name'],
"starttime": met['sensingStart'],
"endtime": met['sensingStop'],
}
|
7eebf6cb13d6c38a953fdc033b58890f32b2eefd
| 336,552 |
def _allocate_expr_id(allocator, exprmap):
""" Allocate a new expression id checking it is not already used.
Args:
allocator: Id allocator
exprmap: Map of existing expression names
Returns:
New id not in exprmap
"""
id = allocator.allocate()
while id in exprmap:
id = allocator.allocate()
return id
|
98321e169d354e97e650e0ea9a5235315529c1dc
| 105,167 |
import torch
def _make_square(mat):
"""Transform a compact affine matrix into a square affine matrix."""
mat = torch.as_tensor(mat)
shape = mat.size()
if mat.dim() != 2 or not shape[0] in (shape[1], shape[1] - 1):
raise ValueError('Input matrix should be Dx(D+1) or (D+1)x(D+1).')
if shape[0] < shape[1]:
addrow = torch.zeros(1, shape[1], dtype=mat.dtype, device=mat.device)
addrow[0, -1] = 1
mat = torch.cat((mat, addrow), dim=0)
return mat
|
a95064218ef26d89920066525283466716aa7739
| 422,967 |
def udfize_def_string(code: str) -> str:
"""Given an unindented code block that uses 'input' as a parameter, and output as a
return value, returns a function as a string."""
return """\
def udf(input):
{}
return output
""".format(
" ".join(line for line in code.splitlines(True))
)
|
71084f68ff268eaaa2eec2f8f22394e963fdd894
| 39,858 |
import requests
def send_query(query_dict):
"""Query ChEMBL API
Parameters
----------
query_dict : dict
'query' : string of the endpoint to query
'params' : dict of params for the query
Returns
-------
js : dict
dict parsed from json that is unique to the submitted query
"""
query = query_dict['query']
params = query_dict['params']
url = 'https://www.ebi.ac.uk/chembl/api/data/' + query + '.json'
r = requests.get(url, params=params)
r.raise_for_status()
js = r.json()
return js
|
0708e2672c8c2a9571661661e0bef062718993c2
| 538,602 |
def FTCS(Uo, diffX, diffY=None):
"""Return the numerical solution of dependent variable in the model eq.
This routine uses the explicit Forward Time/Central Space method
to obtain the solution of the 1D or 2D diffusion equation.
Call signature:
FTCS(Uo, diffX, diffY)
Parameters
----------
Uo: ndarray[float], =1d, 2d
The dependent variable at time level, n within the entire domain.
diffX : float
Diffusion number for x-component of the parabolic/diffusion
equation.
diffY : float, Default=None for 1-D applications
Diffusion number for y-component of the parabolic/diffusion
equation.
Returns
-------
U: ndarray[float], =1d, 2d
The dependent variable at time level, n+1 within the entire domain.
"""
shapeU = Uo.shape # Obtain Dimension
U = Uo.copy() # Initialize U
if len(shapeU) == 1:
U[1:-1] = (
Uo[1:-1] + diffX*(Uo[2:] - 2.0*Uo[1:-1] + Uo[0:-2])
)
elif len(shapeU) == 2:
U[1:-1, 1:-1] = (
Uo[1:-1, 1:-1]
+ diffX*(Uo[2:, 1:-1] - 2.0*Uo[1:-1, 1:-1] + Uo[0:-2, 1:-1])
+ diffY*(Uo[1:-1, 2:] - 2.0*Uo[1:-1, 1:-1] + Uo[1:-1, 0:-2])
)
return U
|
4b02749f3f50a2cff74abb75146159289d42b99e
| 706,387 |
from typing import List
def _format_active_bus_response(response: dict) -> List:
"""
Formats response with currently active buses.
Args:
response: not processed response with currently active buses.
Returns:
list of dicts with active buses data.
"""
return response['result']
|
728e82cdb6de7190da35e645d1cb93350531475a
| 458,716 |
from typing import Type
from typing import Any
def is_new_type(type_: Type[Any]) -> bool:
"""
Check whether type_ was created using typing.NewType
"""
# isinstance(type_, test_type.__class__) and hasattr(type_, "__supertype__")
return type_.__name__ == "Unique"
|
562578502db4ff873eda6e0b0e137e041f048043
| 558,772 |
def rect_center(rect):
"""Return the centre of a rectangle as an (x, y) tuple."""
left = min(rect[0], rect[2])
top = min(rect[1], rect[3])
return (left + abs(((rect[2] - rect[0]) / 2)),
top + abs(((rect[3] - rect[1]) / 2)))
|
dc9060634c66bfa5fdf22db40604fab077ba35e8
| 254,993 |
def get_label(audio_config):
"""Returns label corresponding to which features are to be extracted
e.g:
audio_config = {'mfcc': True, 'chroma': True, 'contrast': False, 'tonnetz': False, 'mel': False}
get_label(audio_config): 'mfcc-chroma'
"""
features = ["mfcc", "chroma", "mel", "contrast", "tonnetz"]
label = ""
for feature in features:
if audio_config[feature]:
label += f"{feature}-"
return label.rstrip("-")
|
5f8b0bbe9966fd50e34e5bdb23cf915970f2170f
| 82,793 |
def effective_authority(request):
"""
Return the authority associated with an request.
This will try the auth client first, then will return the results of
`default_authority()`.
"""
if request.identity and request.identity.auth_client:
return request.identity.auth_client.authority
# We could call the method directly here, but instead we'll go through the
# request method attached below. This allows us to benefit from caching
# if the method has been called before. Also if the request method ever
# points to a new function, we don't have to update.
return request.default_authority
|
648c51d3afda3eb324e413bbdc1d8bb6323faada
| 501,709 |
def probSingle(x: int, _: None) -> float:
"""Probability of Dice X=x"""
return 1 / 6
|
7a063e02f4a9bc7344147fd9cff06be30f96418a
| 304,014 |
def eratosthenes_sieve(n):
"""
Sieve of Eratosthenes
Complexity: O(NloglogN)
We can find all the prime number up to specific
point. This technique is based on the fact that
the multiples of a prime number are composite numbers.
That happens because a multiple of a prime number will
always have 1, itself and the prime as a divisor (maybe
even more) and thus, it's not a prime number. A common
rule for sieves is that they have O(logN) complexity.
"""
primes = [True] * (n+1)
primes[0] = False
primes[1] = False
for i in range(2, int(n**0.5) + 1):
if primes[i]:
for j in range(i*i, n+1, i):
primes[j] = False
final_primes = []
for i in range(len(primes)):
if primes[i]:
final_primes.append(i)
return final_primes
|
e4b0446d93d7ad6df8b98ed976a53f77ec21067a
| 70,410 |
def parse_tcp_uri(uri):
"""Parse tcp://<host>:<port>.
"""
try:
if uri[:6] != 'tcp://':
raise ValueError
address, port = uri[6:].split(':')
return address, int(port)
except (ValueError, TypeError):
raise ValueError(
f"Expected URI on the form tcp://<host>:<port>, but got '{uri}'.")
|
76120575341b5cba71304c544fdb5a759ed5fcd2
| 432,712 |
def calculate_maximum_position(velocity: int) -> int:
"""Calculate the maximum position if `velocity` decreases by one after each step"""
final_position = (velocity * (velocity + 1)) // 2 # Gauss summation strikes again
return final_position
|
a883c6596f7248a3b6fee283621af129e984d736
| 123,081 |
def update_sptype(sptypes):
"""
Function to update a list with spectral types to two characters (e.g., M8, L3, or T1).
Parameters
----------
sptypes : np.ndarray
Input spectral types.
Returns
-------
np.ndarray
Updated spectral types.
"""
sptype_list = ['O', 'B', 'A', 'F', 'G', 'K', 'M', 'L', 'T', 'Y']
for i, spt_item in enumerate(sptypes):
if spt_item == 'None':
pass
elif spt_item == 'null':
sptypes[i] = 'None'
else:
for list_item in sptype_list:
try:
sp_index = spt_item.index(list_item)
sptypes[i] = spt_item[sp_index:sp_index+2]
except ValueError:
pass
return sptypes
|
59eaddbea9aeb49f8d65d132839d2ac3f1fa7043
| 388,466 |
import socket
def pick_port(*ports):
"""
Returns a list of ports, same length as input ports list, but replaces
all None or 0 ports with a random free port.
"""
sockets = []
def find_free_port(port):
if port:
return port
else:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sockets.append(s)
s.bind(('localhost', 0))
_, free_port = s.getsockname()
return free_port
ports = list(map(find_free_port, ports))
# Close sockets only now to avoid the same port to be chosen twice
for s in sockets:
s.close()
return ports
|
94a4251145da6687358bc9a2eb478d13e89832e4
| 592,689 |
def ensure_prefix(symbol: str, _prefix: str = 'O:'):
"""
ensuring prefixes in symbol names. to be used internally by forex, crypto and options
:param symbol: the symbol to check
:param _prefix: which prefix to check for. defaults to ``O:`` which is for options
:return: capitalized prefixed symbol.
"""
if symbol.upper().startswith(_prefix) or symbol == '*':
return symbol.upper()
return f'{_prefix}{symbol.upper()}'
|
f711d52f573f8140dd2f8e522d8d8e1f077c865b
| 176,845 |
import math
def get_count_digits(number: int):
"""Return number of digits in a number."""
if number == 0:
return 1
number = abs(number)
if number <= 999999999999997:
return math.floor(math.log10(number)) + 1
count = 0
while number:
count += 1
number //= 10
return count
|
9b9e8cfdce3e348234f1a293a2593178b9c90d0f
| 248,661 |
import math
def block32_ceil_num_bytes(curr_len):
"""Returns the number of bytes (n >= curr_len) at the next 32-bit boundary"""
num_blks = float(curr_len) / 4.0
num_blks_pad = int( math.ceil( num_blks ))
num_bytes_pad = num_blks_pad * 4
return num_bytes_pad
|
4cd257aaee029479cfcad605aa6ab4f4ca6ba0f3
| 568,131 |
from typing import Any
from pathlib import Path
def r(obj: Any, ignoreintkey: bool = True) -> str:
"""Convert a python object into R repr
Examples:
>>> True -> "TRUE"
>>> None -> "NULL"
>>> [1, 2] -> c(1, 2)
>>> {"a": 1, "b": 2} -> list(a = 1, b = 2)
Args:
ignoreintkey: When keys of a dict are integers, whether we should
ignore them. For example, when `True`, `{1: 1, 2: 2}` will be
translated into `"list(1, 2)"`, but `"list(`1` = 1, `2` = 2)"`
when `False`
Returns:
Then converted string representation of the object
"""
if obj is True:
return 'TRUE'
if obj is False:
return 'FALSE'
if obj is None:
return 'NULL'
if isinstance(obj, str):
if obj.upper() in ['+INF', 'INF']:
return 'Inf'
if obj.upper() == '-INF':
return '-Inf'
if obj.upper() == 'TRUE':
return 'TRUE'
if obj.upper() == 'FALSE':
return 'FALSE'
if obj.upper() == 'NA' or obj.upper() == 'NULL':
return obj.upper()
if obj.startswith('r:') or obj.startswith('R:'):
return str(obj)[2:]
return repr(str(obj))
if isinstance(obj, Path):
return repr(str(obj))
if isinstance(obj, (list, tuple, set)):
return 'c({})'.format(','.join([r(i) for i in obj]))
if isinstance(obj, dict):
# list allow repeated names
return 'list({})'.format(','.join([
'`{0}`={1}'.format(
k,
r(v)) if isinstance(k, int) and not ignoreintkey else \
r(v) if isinstance(k, int) and ignoreintkey else \
'`{0}`={1}'.format(str(k).split('#')[0], r(v))
for k, v in sorted(obj.items())]))
return repr(obj)
|
5c907ee0725ac49958f01ee0fe59f2b9deb7a4fd
| 95,546 |
def _dump_multipoint(obj, fmt):
"""
Dump a GeoJSON-like MultiPoint object to WKT.
Input parameters and return value are the MULTIPOINT equivalent to
:func:`_dump_point`.
"""
coords = obj['coordinates']
mp = 'MULTIPOINT (%s)'
points = (' '.join(fmt % c for c in pt) for pt in coords)
# Add parens around each point.
points = ('(%s)' % pt for pt in points)
mp %= ', '.join(points)
return mp
|
cdea05b91c251b655e08650807e3f74d3bb5e77b
| 889 |
import json
def serialize_json_data(data, ver):
"""
Serialize json data to cassandra by adding a version and dumping it to a
string
"""
dataOut = data.copy()
dataOut["_ver"] = ver
return json.dumps(dataOut)
|
1e2bdc63204c7b64044056c15c34e7a4bb62e919
| 667,286 |
async def get_modification_stats(db, index_id):
"""
Get the number of modified otus and the number of changes made for a specific index.
:param db: the application database client
:type db: :class:`~motor.motor_asyncio.AsyncIOMotorClient`
:param index_id: the id of the index to return counts for
:type index_id: str
:return: the modified otu count and change count
:rtype: Tuple[int, int]
"""
query = {
"index.id": index_id
}
return {
"change_count": await db.history.count(query),
"modified_otu_count": len(await db.history.distinct("otu.id", query))
}
|
cbeadb2e7d194b57a9b47e664f3d1cbdbe412bf7
| 635,669 |
def transform_mac_address_to_string_mac_address(string_mac_address):
"""
It transforms a MAC address from raw string format("\x00\x11\x22\x33\x44\x55") to a human readable
string("00:11:22:33:44:55").
"""
return ':'.join('%02x' % ord(b) for b in string_mac_address)
|
43a3996a0f89638356f3f9f9e3e3500fd90d6389
| 454,221 |
def sheet_as_dict(worksheet):
"""
Take an xsrd worksheet and convert it to a dict, using the first
row as a header (to create keys for the subsequent rows).
"""
keys = worksheet.row_values(0)
value_range = range(1, worksheet.nrows)
def to_dict(values):
return dict(zip(keys, values))
return [to_dict(worksheet.row_values(n)) for n in value_range]
|
d3d48c30444e4059fcb358f3bc3990f92f4374f4
| 619,551 |
def node_below_adjacent_elements(node, surface):
"""
node_below_adjacent_elements determines if a node is below any element adjacent to it in the surface.
Consider the following layout:
*-*-*-* Here, the nodes are shown as * and node (0,0) as X. Elements are shown as o and neighboring
|O|O|o| elements to node X are O. This function determines if a node (i,j,k) is adjacent to or beneath
*-x-*-* any of the elements for which it could be a vertex. As four elements share a "corner", we need
|O|O|o| to check to see if the node is at the highest element position or below for any corner.
*-*-*-*
:param node: index of a node
:param surface: mesh of element heights
:return: boolean
"""
(i, j, k) = node
maximum = 0
for location in [(i - 1, j - 1), (i, j - 1), (i - 1, j), (i, j)]:
if 0 <= i < surface.shape[0] and 0 <= j < surface.shape[1]:
maximum = max(maximum, surface[location])
return k <= maximum + 1
|
71d0e2765f57095fae713e7afd8df108a3dfb490
| 657,254 |
def sound_match(sound, features):
"""
Match a sound by a subset of features.
.. note::
The major idea of this function is to allow for the convenient matching of
some sounds by defining them in terms of a part of their features alone.
E.g., [m] and its variants can be defined as ["bilabial", "nasal"], since
we do not care about the rest of the features.
"""
for feature in features:
if not set(feature).difference(sound.featureset):
return True
return False
|
ab11449691e1d496e76c9a01d3b7c75c3498ba93
| 360,929 |
def IsYaml(path):
"""Is path a yaml file or not."""
return path.endswith('.yaml')
|
974b7b9cbf0e515ed815dddf33bb3bc9b68042a0
| 549,182 |
def round_channels(channels, divisor=8):
"""
Round weighted channel number (make divisible operation).
Parameters:
----------
channels : int or float
Original number of channels.
divisor : int, default 8
Alignment value.
Returns:
-------
int
Weighted number of channels.
"""
rounded_channels = max(
int(channels + divisor / 2.0) // divisor * divisor, divisor)
if float(rounded_channels) < 0.9 * channels:
rounded_channels += divisor
return rounded_channels
|
605bf4f3e291541c9bd9eea1d4f346fe672c0083
| 539,205 |
import pathlib
import importlib
def config_dict_from_python_fpath(fpath: str = 'config.py', include_dunder_keys: bool = False) -> dict:
"""Use importlib and pathlib to take a string file path of a python config
file and return a dictionary of the config values for key:value.
By default the config dictionary removes default dunder methods of a python file.
Location of fpath must be within a python module.
Parameters
----------
fpath : str
String fpath of the python file to use as a config dict
include_dunder_keys : bool = False
Whether to include dunder values of file as config keys.
Default is False (i.e. not included in config dict)
Returns
-------
config_dict: dict
A dictionary containing the variables set in the python
file at 'fpath' as keys and values as respective values
Example
-------
config = config_dict_from_python_fpath('config.py')
> config
> {'config_val_1':'A test string', config_val_2':1234}
"""
# Turn string locaiton into path
config_loc_path = pathlib.Path(fpath)
# Get path as positive slash divided string
# split it on '/' until the last part (the file)
# Add the stem of the file name (remove extension)
# Join on '.' so that it can be imported using importlib
import_string = '.'.join(config_loc_path.as_posix().split(
'/')[:-1]+[config_loc_path.stem])
try:
config_dict = importlib.import_module(import_string).__dict__
except ModuleNotFoundError as e:
print(
f'Could not import file at "{config_loc_path.as_posix()}", are you sure this file exists here?')
raise e
if not include_dunder_keys:
default_dunders = ['__name__', '__doc__', '__package__', '__loader__',
'__spec__', '__file__', '__cached__', '__builtins__']
config_dict = {key: value for key,
value in config_dict.items() if key not in default_dunders}
return config_dict
|
c2e705d00a7a076b18e27c39ddd39ea8c4efadd3
| 190,982 |
from typing import Counter
def build_vocab(tokenized_src_trg_pairs):
"""
Build the vocabulary from the training (src, trg) pairs
:param tokenized_src_trg_pairs: list of (src, trg) pairs
:return: word2idx, idx2word, token_freq_counter
"""
token_freq_counter = Counter()
for src_word_list, trg_word_lists in tokenized_src_trg_pairs:
token_freq_counter.update(src_word_list)
for word_list in trg_word_lists:
token_freq_counter.update(word_list)
# Discard special tokens if already present
special_tokens = ['<pad>', '<bos>', '<eos>', '<unk>', '<sep>']
num_special_tokens = len(special_tokens)
for s_t in special_tokens:
if s_t in token_freq_counter:
del token_freq_counter[s_t]
word2idx = dict()
idx2word = dict()
for idx, word in enumerate(special_tokens):
# '<pad>': 0, '<bos>': 1, '<eos>': 2, '<unk>': 3
word2idx[word] = idx
idx2word[idx] = word
# 根据词频排序
sorted_word2idx = sorted(token_freq_counter.items(), key=lambda x: x[1], reverse=True)
sorted_words = [x[0] for x in sorted_word2idx]
for idx, word in enumerate(sorted_words):
word2idx[word] = idx + num_special_tokens
for idx, word in enumerate(sorted_words):
idx2word[idx + num_special_tokens] = word
return word2idx, idx2word, token_freq_counter
|
28bcb5faa8976380873d9ea9c74b2eecd3bb4c8b
| 231,302 |
def request_info(request):
""" Return commonly used information from a django request object.
user_agent, remote_ip, location, resolution.
"""
user_agent = request.META.get('HTTP_USER_AGENT', '')
remote_ip = request.META.get('REMOTE_ADDR', '')
location = request.POST.get('location', 'No Location')
resolution = 'No Resolution'
if request.POST.get('resolution[viewport][width]', ''):
resolution = "viewport( width: " + \
request.POST.get('resolution[viewport][width]', '') + \
", height: " + \
request.POST.get('resolution[viewport][height]', '') + ") " + \
"screen( width: " + \
request.POST.get('resolution[screen][width]', '') + \
", height: " + \
request.POST.get('resolution[screen][height]', '') + ")"
return (user_agent, remote_ip, location, resolution)
|
83f5b201602f619d2eba939ca4ee14a2b537d43b
| 463,305 |
def float_sec_to_int_sec_nano(float_sec):
"""
From a floating value in seconds, returns a tuple of integer seconds and
nanoseconds
"""
secs = int(float_sec)
nsecs = int((float_sec - secs) * 1e9)
return (secs, nsecs)
|
671a38791ae12ff4d006f9d262303d3e0f94f2c1
| 364,227 |
def HINGED_PROPERTIES(ELEMENTS):
"""
This function creates an array with the hinge properties per node.
Input
ELEMENTS | Elements properties | Py Numpy array
| Node 0 ... Node (N_NODES - 1), Material ID, |
| Geometry ID, Hinge ID node 1, Hinge ID node 2 |
Output:
HINGES | Hinge properties per node | Py Numpy array[N_NODES x 2]
| 0 - No hinge |
| 1 - Yes hinge |
"""
HINGES = ELEMENTS[:, 4:]
return HINGES
|
80a604bda28a69f40c6b8028d92b62249eb0607b
| 615,492 |
def strftime(datetime, formatstr):
"""
Uses Python's strftime with some tweaks
"""
# https://github.com/django/django/blob/54ea290e5bbd19d87bd8dba807738eeeaf01a362/django/utils/dateformat.py#L289
def t(day):
"English ordinal suffix for the day of the month, 2 characters; i.e. 'st', 'nd', 'rd' or 'th'"
if day in (11, 12, 13): # Special case
return 'th'
last = day % 10
if last == 1:
return 'st'
if last == 2:
return 'nd'
if last == 3:
return 'rd'
return 'th'
formatstr = formatstr.replace('%t', t(datetime.day))
return datetime.strftime(formatstr).lstrip("0").replace(" 0", " ")
|
bc748022e5e85c52c70f781c2c5b3bdfdaa1ecc6
| 624,647 |
def xor(a, b):
"""
Returns the exclusive or (XOR) of the two input bits.
"""
assert a in [0, 1]
assert b in [0, 1]
return (a + b) % 2
|
c98f871b64244846e5a04058b54ce871c70428a9
| 244,864 |
from datetime import datetime
def time_of_day(start: datetime) -> str:
"""Get time of day period"""
s = start
if s.hour < 4:
return "Night"
if s.hour < 9:
return "Morning"
if s.hour < 16:
return "Day"
if s.hour < 21:
return "Evening"
return "Night"
|
eb0325d0ed4d42db1bdbe11b3479561fa3e06b02
| 464,295 |
def _scan_real_end_loop(bytecode, setuploop_inst):
"""Find the end of loop.
Return the instruction offset.
"""
start = setuploop_inst.next
end = start + setuploop_inst.arg
offset = start
depth = 0
while offset < end:
inst = bytecode[offset]
depth += inst.block_effect
if depth < 0:
return inst.next
offset = inst.next
|
9cff8ab77563a871b86cdbb14236603ec58e04b6
| 706,067 |
def get_d_max(tasks):
"""
Get the maximum relative deadline among the given periodic tasks.
Parameters
----------
tasks : list of pSyCH.task.Periodic
Periodic tasks among which the maximum relative deadline needs to be
computed.
Returns
-------
float
Maximum relative deadline among for the give tasks.
"""
return max([task.d for task in tasks])
|
7d60d0ff7f850a03a83bc992dd5e3828816991d2
| 231,626 |
import copy
def _normalize_barcodes(items):
"""Normalize barcode specification methods into individual items.
"""
split_items = []
for item in items:
if item.has_key("multiplex"):
for multi in item["multiplex"]:
base = copy.deepcopy(item)
base["description"] += ": {0}".format(multi["name"])
del multi["name"]
del base["multiplex"]
base.update(multi)
split_items.append(base)
elif item.has_key("barcode"):
item.update(item["barcode"])
del item["barcode"]
split_items.append(item)
else:
item["barcode_id"] = None
split_items.append(item)
return split_items
|
6f576d7789cc045b81abe8535942cf0c0abd912a
| 21,213 |
def normalize_stdout(stdout):
"""Make subprocess output easier to consume
Decode bytes to str, strip unnecessary newlines produced by most commands.
:param stdout: return value of `subprocess.check_output` or similar
>>> normalize_stdout(b'/foo/bar\n')
'/foo/bar'
"""
return stdout.decode().strip()
|
0cf202b7611e672de0f681d72873908081256967
| 231,716 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.