content
stringlengths 39
14.9k
| sha1
stringlengths 40
40
| id
int64 0
710k
|
---|---|---|
def contains_message(response, message):
"""
Inspired by django's self.assertRaisesMessage
Useful for confirming the response contains the provided message,
"""
if len(response.context['messages']) != 1:
return False
full_message = str(list(response.context['messages'])[0])
return message in full_message | 4afcdba84603b8b53095a52e769d0a8e3f7bbb17 | 4,037 |
import re
def since(version):
"""A decorator that annotates a function to append the version
of skutil the function was added. This decorator is an adaptation of PySpark's.
Parameters
----------
version : str, float or int
The version the specified method was added to skutil.
Examples
--------
>>> @since('0.1.5')
... def some_fun():
... '''Some docstring'''
... return None
...
>>>
>>> some_fun.__doc__ # doctest: +SKIP
'Some docstring\n\n.. versionadded:: 0.1.5'
.. versionadded:: 0.1.5
"""
indent_p = re.compile(r'\n( +)')
def deco(f):
indents = indent_p.findall(f.__doc__)
indent = ' ' * (min(len(m) for m in indents) if indents else 0)
f.__doc__ = f.__doc__.rstrip() + "\n\n%s.. versionadded:: %s" % (indent, version)
return f
return deco | e6b29b5e4c67ba4a213b183a0b79a1f16a85d81c | 4,038 |
def striptag(tag):
"""
Get the short representation of a fully qualified tag
:param str tag: a (fully qualified or not) XML tag
"""
if tag.startswith('{'):
return tag.rsplit('}')[1]
return tag | f0193e3f792122ba8278e599247439a91139e72b | 4,039 |
def equal(* vals):
"""Returns True if all arguments are equal"""
if len(vals) < 2:
return True
a = vals[0]
for b in vals[1:]:
if a != b:
return False
return True | dbd947016d2b84faaaa7fefa6f35975da0a1b5ec | 4,041 |
def get_command(tool_xml):
"""Get command XML element from supplied XML root."""
root = tool_xml.getroot()
commands = root.findall("command")
command = None
if len(commands) == 1:
command = commands[0]
return command | 8d50b2675b3a6089b15b5380025ca7def9e4339e | 4,043 |
import re
def ParseTimeCommandResult(command_result):
"""Parse command result and get time elapsed.
Args:
command_result: The result after executing a remote time command.
Returns:
Time taken for the command.
"""
time_data = re.findall(r'real\s+(\d+)m(\d+.\d+)', command_result)
time_in_seconds = 60 * float(time_data[0][0]) + float(time_data[0][1])
return time_in_seconds | fc92d4b996716ddb2253bf4eb75ed9860c43b2d7 | 4,047 |
def get_grains_connected_to_face(mesh, face_set, node_id_grain_lut):
"""
This function find the grain connected to the face set given as argument.
Three nodes on a grain boundary can all be intersected by one grain
in which case the grain face is on the boundary or by two grains. It
is therefore sufficient to look at the set of grains contained by any
three nodes in the face set and take the intersection of these sets.
:param mesh: The mesh
:type mesh: :class:`Mesh`
:param face_set: The face set to find grains connected to
:type: face_set: :class:`ElementSet`
:return: The grain identifiers that intersect the face.
:rtype: list of ints
"""
grains_connected_to_face = []
grains = face_set.name[4:].split("_")
if len(grains) == 2:
return [int(g) for g in grains]
triangle_element = mesh.elements[face_set.ids[0]]
for node_id in triangle_element.vertices:
grains_with_node_id = node_id_grain_lut[node_id]
grains_connected_to_face.append(set(grains_with_node_id))
return list(set.intersection(*grains_connected_to_face)) | cb4adff2d6ffe3c32e2a1fc8058e6ad1fed9b2c9 | 4,050 |
def argmin(x):
"""
Returns the index of the smallest element of the iterable `x`.
If two or more elements equal the minimum value, the index of the first
such element is returned.
>>> argmin([1, 3, 2, 0])
3
>>> argmin(abs(x) for x in range(-3, 4))
3
"""
argmin_ = None
min_ = None
for (nItem, item) in enumerate(x):
if (argmin_ is None) or (item < min_):
argmin_ = nItem
min_ = item
return argmin_ | 8d6778182bf3c18ffa6ef72093bf19a818d74911 | 4,051 |
def find_spot(entry, list):
"""
return index of entry in list
"""
for s, spot in enumerate(list):
if entry==spot:
return s
else:
raise ValueError("could not find entry: "+ str(entry)+ " in list: "+ str(list)) | e218822e5e56a62c40f5680751c1360c56f05f4a | 4,052 |
def geom_to_tuple(geom):
"""
Takes a lat/long point (or geom) from KCMO style csvs.
Returns (lat, long) tuple
"""
geom = geom[6:]
geom = geom.replace(" ", ", ")
return eval(geom) | 003f25a0ebc8fd372b63453e4782aa52c0ad697c | 4,054 |
def get_reg_part(reg_doc):
"""
Depending on source, the CFR part number exists in different places. Fetch
it, wherever it is.
"""
potential_parts = []
potential_parts.extend(
# FR notice
node.attrib['PART'] for node in reg_doc.xpath('//REGTEXT'))
potential_parts.extend(
# e-CFR XML, under PART/EAR
node.text.replace('Pt.', '').strip()
for node in reg_doc.xpath('//PART/EAR')
if 'Pt.' in node.text)
potential_parts.extend(
# e-CFR XML, under FDSYS/HEADING
node.text.replace('PART', '').strip()
for node in reg_doc.xpath('//FDSYS/HEADING')
if 'PART' in node.text)
potential_parts.extend(
# e-CFR XML, under FDSYS/GRANULENUM
node.text.strip() for node in reg_doc.xpath('//FDSYS/GRANULENUM'))
potential_parts = [p for p in potential_parts if p.strip()]
if potential_parts:
return potential_parts[0] | 33f4c2bb9a4e2f404e7ef94a3bfe3707a3b1dd93 | 4,056 |
def group_masses(ip, dm: float = 0.25):
"""
Groups masses in an isotope pattern looking for differences in m/z greater than the specified delta.
expects
:param ip: a paired list of [[mz values],[intensity values]]
:param dm: Delta for looking +/- within
:return: blocks grouped by central mass
:rtype: list
"""
num = 0
out = [[[], []]]
for ind, val in enumerate(ip[0]):
out[num][0].append(ip[0][ind])
out[num][1].append(ip[1][ind])
try:
if ip[0][ind + 1] - ip[0][ind] > dm:
num += 1
out.append([[], []])
except IndexError:
continue
return out | 918fc4f20fee7c2955218e3c435f9e672dc55f7d | 4,066 |
import math
def point_based_matching(point_pairs):
"""
This function is based on the paper "Robot Pose Estimation in Unknown Environments by Matching 2D Range Scans"
by F. Lu and E. Milios.
:param point_pairs: the matched point pairs [((x1, y1), (x1', y1')), ..., ((xi, yi), (xi', yi')), ...]
:return: the rotation angle and the 2D translation (x, y) to be applied for matching the given pairs of points
"""
x_mean = 0
y_mean = 0
xp_mean = 0
yp_mean = 0
n = len(point_pairs)
if n == 0:
return None, None, None
for pair in point_pairs:
(x, y), (xp, yp) = pair
x_mean += x
y_mean += y
xp_mean += xp
yp_mean += yp
x_mean /= n
y_mean /= n
xp_mean /= n
yp_mean /= n
s_x_xp = 0
s_y_yp = 0
s_x_yp = 0
s_y_xp = 0
for pair in point_pairs:
(x, y), (xp, yp) = pair
s_x_xp += (x - x_mean)*(xp - xp_mean)
s_y_yp += (y - y_mean)*(yp - yp_mean)
s_x_yp += (x - x_mean)*(yp - yp_mean)
s_y_xp += (y - y_mean)*(xp - xp_mean)
rot_angle = math.atan2(s_x_yp - s_y_xp, s_x_xp + s_y_yp)
translation_x = xp_mean - (x_mean*math.cos(rot_angle) - y_mean*math.sin(rot_angle))
translation_y = yp_mean - (x_mean*math.sin(rot_angle) + y_mean*math.cos(rot_angle))
return rot_angle, translation_x, translation_y | 2d691bbf04d14e3e5b0f9273a7501d934bd0eef4 | 4,069 |
def bind_port(socket, ip, port):
""" Binds the specified ZMQ socket. If the port is zero, a random port is
chosen. Returns the port that was bound.
"""
connection = 'tcp://%s' % ip
if port <= 0:
port = socket.bind_to_random_port(connection)
else:
connection += ':%i' % port
socket.bind(connection)
return port | 5613bae6726e2f006706b104463917e48d7ab7ca | 4,071 |
def update_target_graph(actor_tvars, target_tvars, tau):
""" Updates the variables of the target graph using the variable values from the actor, following the DDQN update
equation. """
op_holder = list()
# .assign() is performed on target graph variables with discounted actor graph variable values
for idx, variable in enumerate(target_tvars):
op_holder.append(
target_tvars[idx].assign(
(variable.value() * tau) + ((1 - tau) * actor_tvars[idx].value())
)
)
return op_holder | 15f0d192ff150c0a39495b0dec53f18a8ae01664 | 4,072 |
def extract_shebang_command(handle):
"""
Extract the shebang_ command line from an executable script.
:param handle: A file-like object (assumed to contain an executable).
:returns: The command in the shebang_ line (a string).
The seek position is expected to be at the start of the file and will be
reset afterwards, before this function returns. It is not an error if the
executable contains binary data.
.. _shebang: https://en.wikipedia.org/wiki/Shebang_(Unix)
"""
try:
if handle.read(2) == b'#!':
data = handle.readline()
text = data.decode('UTF-8')
return text.strip()
else:
return ''
finally:
handle.seek(0) | 27174f96f2da3167cf7a7e28c4a2f1cec72c773c | 4,076 |
def create_graph(num_islands, bridge_config):
"""
Helper function to create graph using adjacency list implementation
"""
adjacency_list = [list() for _ in range(num_islands + 1)]
for config in bridge_config:
source = config[0]
destination = config[1]
cost = config[2]
adjacency_list[source].append((destination, cost))
adjacency_list[destination].append((source, cost))
#print("adjacency_list",adjacency_list)
return adjacency_list | b961f5ee2955f4b8de640152981a7cede8ca80b0 | 4,078 |
def get_timepoint( data, tp=0 ):
"""Returns the timepoint (3D data volume, lowest is 0) from 4D input.
You can save memory by using [1]:
nifti.dataobj[..., tp]
instead: see get_nifti_timepoint()
Works with loop_and_save().
Call directly, or with niftify().
Ref:
[1]: http://nipy.org/nibabel/images_and_memory.html
"""
# Replicating seg_maths -tp
tp = int(tp)
if len(data.shape) < 4:
print("Data has fewer than 4 dimensions. Doing nothing...")
output = data
else:
if data.shape[3] < tp:
print("Data has fewer than {0} timepoints in its 4th dimension.".format(tp))
output = data
else:
output = data[:,:,:,tp]
return output
# elif len(data.shape) > 4:
# print("Data has more than 4 dimensions! Assuming the 4th is time ...")
# End get_timepoint() definition | f5a718e5d9f60d1b389839fc0c637bee32b500bf | 4,079 |
def method_from_name(klass, method_name: str):
"""
Given an imported class, return the given method pointer.
:param klass: An imported class containing the method.
:param method_name: The method name to find.
:return: The method pointer
"""
try:
return getattr(klass, method_name)
except AttributeError:
raise NotImplementedError() | 97274754bd89ede62ee5940fca6c4763efdbb95c | 4,080 |
def convert(origDict, initialSpecies):
"""
Convert the original dictionary with species labels as keys
into a new dictionary with species objects as keys,
using the given dictionary of species.
"""
new_dict = {}
for label, value in origDict.items():
new_dict[initialSpecies[label]] = value
return new_dict | 5143f31acd1efdf1790e68bade3a1f8d8977bcde | 4,083 |
def command_ltc(bot, user, channel, args):
"""Display current LRC exchange rates from BTC-E"""
r = bot.get_url("https://btc-e.com/api/2/ltc_usd/ticker")
j = r.json()['ticker']
return bot.say(channel, "BTC-E: avg:$%s last:$%s low:$%s high:$%s vol:%s" % (j['avg'], j['last'], j['low'], j['high'], j['vol'])) | 7aa411b6708e54b09cf2b9aef9c8b01899b95298 | 4,085 |
def union_exprs(La, Lb):
"""
Union two lists of Exprs.
"""
b_strs = set([node.unique_str() for node in Lb])
a_extra_nodes = [node for node in La if node.unique_str() not in b_strs]
return a_extra_nodes + Lb | 2bd634a22b27314f6d03c8e52c0b09f7f4b692db | 4,087 |
import re
import itertools
def compile_read_regex(read_tags, file_extension):
"""Generate regular expressions to disern direction in paired-end reads."""
read_regex = [re.compile(r'{}\.{}$'.format(x, y))\
for x, y in itertools.product(read_tags, [file_extension])]
return read_regex | e677b8ff622eb31ea5f77bc662845ba0aef91770 | 4,088 |
from typing import List
def get_bank_sizes(num_constraints: int,
beam_size: int,
candidate_counts: List[int]) -> List[int]:
"""
Evenly distributes the beam across the banks, where each bank is a portion of the beam devoted
to hypotheses having met the same number of constraints, 0..num_constraints.
After the assignment, banks with more slots than candidates are adjusted.
:param num_constraints: The number of constraints.
:param beam_size: The beam size.
:param candidate_counts: The empirical counts of number of candidates in each bank.
:return: A distribution over banks.
"""
num_banks = num_constraints + 1
bank_size = beam_size // num_banks
remainder = beam_size - bank_size * num_banks
# Distribute any remainder to the end
assigned = [bank_size for x in range(num_banks)]
assigned[-1] += remainder
# Now, moving right to left, push extra allocation to earlier buckets.
# This encodes a bias for higher buckets, but if no candidates are found, space
# will be made in lower buckets. This may not be the best strategy, but it is important
# that you start pushing from the bucket that is assigned the remainder, for cases where
# num_constraints >= beam_size.
for i in reversed(range(num_banks)):
overfill = assigned[i] - candidate_counts[i]
if overfill > 0:
assigned[i] -= overfill
assigned[(i - 1) % num_banks] += overfill
return assigned | 7a515b1e7762d01b7f7a1405a943f03babe26520 | 4,091 |
def datetime_to_hours(dt):
"""Converts datetime.timedelta to hours
Parameters:
-----------
dt: datetime.timedelta
Returns:
--------
float
"""
return dt.days * 24 + dt.seconds / 3600 | e7373cbb49e21340fef1590a655059fd39c6ce88 | 4,104 |
import http
def build_status(code: int) -> str:
"""
Builds a string with HTTP status code and reason for given code.
:param code: integer HTTP code
:return: string with code and reason
"""
status = http.HTTPStatus(code)
def _process_word(_word: str) -> str:
if _word == "OK":
return _word
return _word.capitalize()
reason = " ".join(_process_word(word) for word in status.name.split("_"))
text = f"{code} {reason}"
return text | 9730abf472ddc3d5e852181c9d60f8c42fee687d | 4,109 |
def benedict_bornder_constants(g, critical=False):
""" Computes the g,h constants for a Benedict-Bordner filter, which
minimizes transient errors for a g-h filter.
Returns the values g,h for a specified g. Strictly speaking, only h
is computed, g is returned unchanged.
The default formula for the Benedict-Bordner allows ringing. We can
"nearly" critically damp it; ringing will be reduced, but not entirely
eliminated at the cost of reduced performance.
Parameters
----------
g : float
scaling factor g for the filter
critical : boolean, default False
Attempts to critically damp the filter.
Returns
-------
g : float
scaling factor g (same as the g that was passed in)
h : float
scaling factor h that minimizes the transient errors
Examples
--------
.. code-block:: Python
from filterpy.gh import GHFilter, benedict_bornder_constants
g, h = benedict_bornder_constants(.855)
f = GHFilter(0, 0, 1, g, h)
References
----------
Brookner, "Tracking and Kalman Filters Made Easy". John Wiley and
Sons, 1998.
"""
g_sqr = g**2
if critical:
return (g, 0.8 * (2. - g_sqr - 2*(1-g_sqr)**.5) / g_sqr)
return (g, g_sqr / (2.-g)) | ca40941b4843b3d71030549da2810c9241ebdf72 | 4,111 |
import re
def remove_special_message(section_content):
"""
Remove special message - "medicinal product no longer authorised"
e.g.
'me di cin al p ro du ct n o lo ng er a ut ho ris ed'
'me dic ina l p rod uc t n o l on ge r a uth ori se d'
:param section_content: content of a section
:return: content of a section without special message
"""
# string as it is present in the section content
SPECIAL_MESSAGE1 = 'me di cin al p ro du ct n o lo ng er a ut ho ris ed'
SPECIAL_MESSAGE2 = 'me dic ina l p ro du ct no lo ng er au th or ise d'
SPECIAL_MESSAGE3 = 'me dic ina l p rod uc t n o l on ge r a uth ori se d'
SPECIAL_MESSAGE4 = 'me dic ina l p ro du ct no lo ng er au tho ris ed'
SPECIAL_MESSAGE5 = 'me dic ina l p ro du ct no lo ng er a ut ho ris ed'
SPECIAL_MESSAGE6 = 'me dic ina l p rod uc t n o l on ge r a uth ori sed'
SPECIAL_MESSAGE7 = 'm ed ici na l p ro du ct no lo ng er a ut ho ris ed'
SPECIAL_MESSAGE8 = 'm ed ici na l p ro du ct no lo ng er au th or ise d'
SPECIAL_MESSAGE9 = 'med icin al pro du ct no lo ng er au tho ris ed'
SPECIAL_MESSAGE_ARRAY = [SPECIAL_MESSAGE1, SPECIAL_MESSAGE2, SPECIAL_MESSAGE3, SPECIAL_MESSAGE4,
SPECIAL_MESSAGE5, SPECIAL_MESSAGE6, SPECIAL_MESSAGE7, SPECIAL_MESSAGE8,
SPECIAL_MESSAGE9]
# in case message present in section content
for SPECIAL_MESSAGE in SPECIAL_MESSAGE_ARRAY:
section_content = section_content.replace(SPECIAL_MESSAGE, '')
# remove multiple consecutive spaces
section_content = re.sub(' +', ' ', section_content)
return section_content | 37d9cbd697a98891b3f19848c90cb17dafcd6345 | 4,114 |
def apply_function_elementwise_series(ser, func):
"""Apply a function on a row/column basis of a DataFrame.
Args:
ser (pd.Series): Series.
func (function): The function to apply.
Returns:
pd.Series: Series with the applied function.
Examples:
>>> df = pd.DataFrame(np.array(range(12)).reshape(4, 3), columns=list('abc'))
>>> ser = df['b']
>>> f = lambda x: '%.1f' % x
>>> apply_function_elementwise_series(ser, f)
0 1.0
1 4.0
2 7.0
3 10.0
Name: b, dtype: object
"""
return ser.map(func) | d2af0a9c7817c602b4621603a8f06283f34ae81a | 4,115 |
def BitWidth(n: int):
""" compute the minimum bitwidth needed to represent and integer """
if n == 0:
return 0
if n > 0:
return n.bit_length()
if n < 0:
# two's-complement WITHOUT sign
return (n + 1).bit_length() | 46dcdfb0987268133d606e609d39c641b9e6faab | 4,116 |
import socket
def tcp_port_open_locally(port):
"""
Returns True if the given TCP port is open on the local machine
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex(("127.0.0.1", port))
return result == 0 | f5c801a5016085eedbed953089742e184f514db5 | 4,120 |
def wrap(text, width=80):
"""
Wraps a string at a fixed width.
Arguments
---------
text : str
Text to be wrapped
width : int
Line width
Returns
-------
str
Wrapped string
"""
return "\n".join(
[text[i:i + width] for i in range(0, len(text), width)]
) | 793840a1cae51397de15dd16051c5dfffc211768 | 4,121 |
def get_list_channels(sc):
"""Get list of channels."""
# https://api.slack.com/methods/channels.list
response = sc.api_call(
"channels.list",
)
return response['channels'] | d31271bcc065b4a212e298c6283c4d658e5547da | 4,129 |
def lowercase_words(words):
"""
Lowercases a list of words
Parameters
-----------
words: list of words to process
Returns
-------
Processed list of words where words are now all lowercase
"""
return [word.lower() for word in words] | b6e8658f35743f6729a9f8df229b382797b770f6 | 4,137 |
def isempty(s):
"""
return if input object(string) is empty
"""
if s in (None, "", "-", []):
return True
return False | 9c3ffd6ab818e803c1c0129588c345361c58807f | 4,139 |
def clamp(val, min_, max_):
"""clamp val to between min_ and max_ inclusive"""
if val < min_:
return min_
if val > max_:
return max_
return val | 31f2441ba03cf765138a7ba9b41acbfe21b7bda7 | 4,140 |
def get_ip(request):
"""Determines user IP address
Args:
request: resquest object
Return:
ip_address: requesting machine's ip address (PUBLIC)
"""
ip_address = request.remote_addr
return ip_address | 84e1540bc8b79fd2043a8fb6f107f7bcd8d7cc8c | 4,141 |
from typing import Generator
import pkg_resources
def get_pip_package_list(path: str) -> Generator[pkg_resources.Distribution, None, None]:
"""Get the Pip package list of a Python virtual environment.
Must be a path like: /project/venv/lib/python3.9/site-packages
"""
packages = pkg_resources.find_distributions(path)
return packages | 9e73e27c2b50186dedeedd1240c28ef4f4d50e03 | 4,151 |
def _get_reverse_complement(seq):
"""
Get the reverse compliment of a DNA sequence.
Parameters:
-----------
seq
Returns:
--------
reverse_complement_seq
Notes:
------
(1) No dependencies required. Pure python.
"""
complement_seq = ""
for i in seq:
if i == "C":
complement_seq += "G"
elif i == "G":
complement_seq += "C"
elif i == "A":
complement_seq += "T"
elif i == "T":
complement_seq += "A"
elif i == "N":
complement_seq += "N"
reverse_complement_seq = complement_seq[::-1]
return reverse_complement_seq | 31408767c628ab7b0e6e63867e37f11eb6e19560 | 4,152 |
def check_table(conn, table, interconnect):
"""
searches if Interconnect exists in table in database
:param conn: connect instance for database
:param table: name of table you want to check
:param interconnect: name of the Interconnect you are looking for
:return: results of SQL query searching for table
"""
cur = conn.cursor()
sql_search = "SELECT * \
FROM %s \
WHERE Interconnect='%s'" % (table, interconnect)
found = cur.execute(sql_search).fetchone()
return found | 0888146d5dfe20e7bdfbfe078c58e86fda43d6a5 | 4,153 |
def read_tab(filename):
"""Read information from a TAB file and return a list.
Parameters
----------
filename : str
Full path and name for the tab file.
Returns
-------
list
"""
with open(filename) as my_file:
lines = my_file.readlines()
return lines | 8a6a6b0ec693130da7f036f4673c89f786dfb230 | 4,155 |
def int2(c):
""" Parse a string as a binary number """
return int(c, 2) | dd1fb1f4c194e159b227c77c4246136863646707 | 4,156 |
def properties(classes):
"""get all property (p-*, u-*, e-*, dt-*) classnames
"""
return [c.partition("-")[2] for c in classes if c.startswith("p-")
or c.startswith("u-") or c.startswith("e-") or c.startswith("dt-")] | 417562d19043f4b98068ec38cc010061b612fef3 | 4,157 |
def _setter_name(getter_name):
""" Convert a getter name to a setter name.
"""
return 'set' + getter_name[0].upper() + getter_name[1:] | d4b55afc10c6d79a1432d2a8f3077eb308ab0f76 | 4,158 |
def thumbnail(img, size = (1000,1000)):
"""Converts Pillow images to a different size without modifying the original image
"""
img_thumbnail = img.copy()
img_thumbnail.thumbnail(size)
return img_thumbnail | 4eb49869a53d9ddd42ca8c184a12f0fedb8586a5 | 4,161 |
def repetitions(seq: str) -> int:
"""
[Easy] https://cses.fi/problemset/task/1069/
[Solution] https://cses.fi/paste/659d805082c50ec1219667/
You are given a DNA sequence: a string consisting of characters A, C, G,
and T. Your task is to find the longest repetition in the sequence. This is
a maximum-length substring containing only one type of character.
The only input line contains a string of n characters.
Print one integer, the length of the longest repetition.
Constraints: 1 ≤ n ≤ 10^6
Example
Input: ATTCGGGA
Output: 3
"""
res, cur = 0, 0
fir = ''
for ch in seq:
if ch == fir:
cur += 1
else:
res = max(res, cur)
fir = ch
cur = 1
return max(res, cur) | 4dde2ec4a6cd6b13a54c2eafe4e8db0d87381faa | 4,177 |
def get_lines(filename):
"""
Returns a list of lines of a file.
Parameters
filename : str, name of control file
"""
with open(filename, "r") as f:
lines = f.readlines()
return lines | 1307b169733b50517b26ecbf0414ca3396475360 | 4,182 |
def normalize_type(type: str) -> str:
"""Normalize DataTransfer's type strings.
https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransfer-getdata
'text' -> 'text/plain'
'url' -> 'text/uri-list'
"""
if type == 'text':
return 'text/plain'
elif type == 'url':
return 'text/uri-list'
return type | 887c532218a7775ea55c6a39953ec244183af455 | 4,183 |
def filterLinesByCommentStr(lines, comment_str='#'):
"""
Filter all lines from a file.readlines output which begins with one of the
symbols in the comment_str.
"""
comment_line_idx = []
for i, line in enumerate(lines):
if line[0] in comment_str:
comment_line_idx.append(i)
for j in comment_line_idx[::-1]:
del lines[j]
return lines | 8a6ce56187afc2368ec81d11c38fe7af2eacb14f | 4,184 |
def GetFlagFromDest(dest):
"""Returns a conventional flag name given a dest name."""
return '--' + dest.replace('_', '-') | 021ab8bca05afbb2325d865a299a2af7c3b939c9 | 4,187 |
def ganache_url(host='127.0.0.1', port='7445'):
"""Return URL for Ganache test server."""
return f"http://{host}:{port}" | 9de6e2c26c0e1235a14c8dd28040fcdfb8a36a7f | 4,188 |
def unwrap(func):
"""
Returns the object wrapped by decorators.
"""
def _is_wrapped(f):
return hasattr(f, '__wrapped__')
unwrapped_f = func
while (_is_wrapped(unwrapped_f)):
unwrapped_f = unwrapped_f.__wrapped__
return unwrapped_f | 17aa0c8cc91578fd1187784ad0396ed91c5ec9b8 | 4,189 |
def tlam(func, tup):
"""Split tuple into arguments
"""
return func(*tup) | 0e3a9b93b36795e6c11631f8c8852aba59724f88 | 4,191 |
def get_N_intransit(tdur, cadence):
"""Estimates number of in-transit points for transits in a light curve.
Parameters
----------
tdur: float
Full transit duration
cadence: float
Cadence/integration time for light curve
Returns
-------
n_intransit: int
Number of flux points in each transit
"""
n_intransit = tdur//cadence
return n_intransit | d126b5590a8997b8695c1a86360421f2bf4b8357 | 4,195 |
def extract_keys(keys, dic, drop=True):
"""
Extract keys from dictionary and return a dictionary with the extracted
values.
If key is not included in the dictionary, it will also be absent from the
output.
"""
out = {}
for k in keys:
try:
if drop:
out[k] = dic.pop(k)
else:
out[k] = dic[k]
except KeyError:
pass
return out | 15a66fff5207df18d8ece4959e485068f1bd3c9c | 4,196 |
import sqlite3
def getStations(options, type):
"""Query stations by specific type ('GHCND', 'ASOS', 'COOP', 'USAF-WBAN')
"""
conn = sqlite3.connect(options.database)
c = conn.cursor()
if type == "ALL":
c.execute("select rowid, id, name, lat, lon from stations")
else:
c.execute("select rowid, id, name, lat, lon from stations where type = ?",(type,))
stations = []
for r in c:
stations.append(r)
conn.close()
return stations | 59d45a79542e68cd691cf848f3d4fe250389732c | 4,197 |
import random
import string
def random_string_fx() -> str:
"""
Creates a 16 digit alphanumeric string. For use
with logging tests.
Returns:
16 digit alphanumeric string.
"""
result = "".join(random.sample(string.ascii_letters, 16))
return result | 835c2dc2716c6ef0ad37f5ae03cfc9dbe2e16725 | 4,200 |
def report_cots_cv2x_bsm(bsm: dict) -> str:
"""A function to report the BSM information contained in an SPDU from a COTS C-V2X device
:param bsm: a dictionary containing BSM fields from a C-V2X SPDU
:type bsm: dict
:return: a string representation of the BSM fields
:rtype: str
"""
report = ""
for key in bsm.keys():
report += key + "\t\t\t" + str(bsm[key]) + "\n"
report += "\n"
return report | df0aa5ae4b50980088fe69cb0b776abbf0b0998d | 4,203 |
import random
def random_function(*args):
"""Picks one of its arguments uniformly at random, calls it, and returns the result.
Example usage:
>>> random_function(lambda: numpy.uniform(-2, -1), lambda: numpy.uniform(1, 2))
"""
choice = random.randint(0, len(args) - 1)
return args[choice]() | 3f8d11becc52fde5752671e3045a9c64ddfeec97 | 4,205 |
def is_rescue_entry(boot_entry):
"""
Determines whether the given boot entry is rescue.
:param BootEntry boot_entry: Boot entry to assess
:return: True is the entry is rescue
:rtype: bool
"""
return 'rescue' in boot_entry.kernel_image.lower() | ba456c2724c3ad4e35bef110ed8c4cc08147b42c | 4,208 |
import math
def rad_to_gon(angle: float) -> float:
"""Converts from radiant to gon (grad).
Args:
angle: Angle in rad.
Returns:
Converted angle in gon.
"""
return angle * 200 / math.pi | cbf7070a9c3a9796dfe4bffe39fdf2421f7279ed | 4,210 |
def detected(numbers, mode):
"""
Returns a Boolean result indicating whether the last member in a numeric array is the max or
min, depending on the setting.
Arguments
- numbers: an array of numbers
- mode: 'max' or 'min'
"""
call_dict = {'min': min, 'max': max}
if mode not in call_dict.keys():
print('Must specify either max or min')
return
return numbers[-1] == call_dict[mode](numbers) | b0a5b19e7d97db99769f28c4b8ce998dbe318c5b | 4,211 |
from typing import Any
def fqname_for(obj: Any) -> str:
"""
Returns the fully qualified name of ``obj``.
Parameters
----------
obj
The class we are interested in.
Returns
-------
str
The fully qualified name of ``obj``.
"""
if "<locals>" in obj.__qualname__:
raise RuntimeError(
"Can't get fully qualified name of locally defined object. "
f"{obj.__qualname__}"
)
return f"{obj.__module__}.{obj.__qualname__}" | 6d4e5db255715c999d1bb40533f3dbe03b948b07 | 4,215 |
def symbol_size(values):
""" Rescale given values to reasonable symbol sizes in the plot. """
max_size = 50.0
min_size = 5.0
# Rescale max.
slope = (max_size - min_size)/(values.max() - values.min())
return slope*(values - values.max()) + max_size | a33f77ee8eeff8d0e63035c5c408a0788b661886 | 4,216 |
def hexColorToInt(rgb):
"""Convert rgb color string to STK integer color code."""
r = int(rgb[0:2],16)
g = int(rgb[2:4],16)
b = int(rgb[4:6],16)
color = format(b, '02X') + format(g, '02X') + format(r, '02X')
return int(color,16) | 59b8815d647b9ca3e90092bb6ee7a0ca19dd46c2 | 4,218 |
def insert_at_index(rootllist, newllist, index):
""" Insert newllist in the llist following rootllist such that newllist is at the provided index in the resulting llist"""
# At start
if index == 0:
newllist.child = rootllist
return newllist
# Walk through the list
curllist = rootllist
for i in range(index-1):
curllist = curllist.child
# Insert
newllist.last().child=curllist.child
curllist.child=newllist
return rootllist | 767cde29fbc711373c37dd3674655fb1bdf3fedf | 4,219 |
def priority(n=0):
"""
Sets the priority of the plugin.
Higher values indicate a higher priority.
This should be used as a decorator.
Returns a decorator function.
:param n: priority (higher values = higher priority)
:type n: int
:rtype: function
"""
def wrapper(cls):
cls._plugin_priority = n
return cls
return wrapper | 58ab19fd88e9e293676943857a0fa04bf16f0e93 | 4,221 |
def sanitize_option(option):
"""
Format the given string by stripping the trailing parentheses
eg. Auckland City (123) -> Auckland City
:param option: String to be formatted
:return: Substring without the trailing parentheses
"""
return ' '.join(option.split(' ')[:-1]).strip() | ece0a78599e428ae8826b82d7d00ffc39495d27f | 4,222 |
import pickle
def from_pickle(input_path):
"""Read from pickle file."""
with open(input_path, 'rb') as f:
unpickler = pickle.Unpickler(f)
return unpickler.load() | 4e537fcde38e612e22004007122130c545246afb | 4,229 |
def get_only_metrics(results):
"""Turn dictionary of results into a list of metrics"""
metrics_names = ["test/f1", "test/precision", "test/recall", "test/loss"]
metrics = [results[name] for name in metrics_names]
return metrics | 1b0e5bb8771fdc44dcd22ff9cdb174f77205eadd | 4,230 |
def pkcs7_unpad(data):
"""
Remove the padding bytes that were added at point of encryption.
Implementation copied from pyaspora:
https://github.com/mjnovice/pyaspora/blob/master/pyaspora/diaspora/protocol.py#L209
"""
if isinstance(data, str):
return data[0:-ord(data[-1])]
else:
return data[0:-data[-1]] | 4b43b80220e195aa51c129b6cbe1f216a94360cd | 4,233 |
def _chk_y_path(tile):
"""
Check to make sure tile is among left most possible tiles
"""
if tile[0] == 0:
return True
return False | cf733c778b647654652ae5c651c7586c8c3567b8 | 4,235 |
import re
def alphanum_key(string):
"""Return a comparable tuple with extracted number segments.
Adapted from: http://stackoverflow.com/a/2669120/176978
"""
convert = lambda text: int(text) if text.isdigit() else text
return [convert(segment) for segment in re.split('([0-9]+)', string)] | 0e5e3f1d6aa43d393e1fb970f64e5910e7dc53fc | 4,236 |
def weight_point_in_circle(
point: tuple,
center: tuple,
radius: int,
corner_threshold: float = 1.5
):
"""
Function to decide whether a certain grid coordinate should be a full, half or empty tile.
Arguments:
point (tuple): x, y of the point to be tested
center (tuple): x, y of the origin (center) point
radius (int): radius of certainly empty tiles, does not include half tiles
corner_threshold (float): threshold that decides if the tile should be a half tile instead of empty
Returns:
int: the type of the tested tile
0 if empty tile
1 if full tile
2 if half tile
"""
diff_x, diff_y = map(lambda x, y: abs(x - y), center, point) # subtract point from center then abs for both x and y
if (diff_y > radius) or (diff_x > radius):
return 0 # eliminate any obviously out of bounds tiles
# precalculate pythagoras distance squared
dist_squared = (diff_x * diff_x) + (diff_y * diff_y)
# precalculate radius sqaured
radius_squared = radius * radius
# precalculate rounded distance
rounded_distance = round(dist_squared)
if rounded_distance < radius_squared: # distance within radius
return 1 # full tile
elif rounded_distance < radius_squared * corner_threshold and diff_x < radius: # distance on edge
return 2 # half tile
# outside of any thresholds
return 0 | db0da5e101184975385fb07e7b22c5e8a6d4fd47 | 4,251 |
def get_arrival_times(inter_times):
"""Convert interevent times to arrival times."""
return inter_times.cumsum() | 7197fc6315d3eaca118ca419f23aed7c0d7cd064 | 4,254 |
def contains_vendored_imports(python_path):
"""
Returns True if ``python_path`` seems to contain vendored imports from botocore.
"""
# We're using a very rough heuristic here: if the source code contains
# strings that look like a vendored import, we'll flag.
#
# Because Python is dynamic, there are lots of ways you could be
# importing the vendored modules that wouldn't be caught this way, but:
#
# 1. Doing it in a complete foolproof way is incredibly complicated, and
# I don't care that much.
# 2. If you're writing your Lambda code in a deliberately obfuscated way,
# you have bigger problems than vendor deprecations.
#
# In practice, Python imports are usually near the top of the file, so we
# read it line-by-line. This means if we find an import, we can skip
# reading the rest of the file.
#
with open(python_path, "rb") as python_src:
for line in python_src:
if (
b"import botocore.vendored" in line
or b"from botocore.vendored import " in line
):
return True
return False | 90ed6939d7f43cac29eb66c3e27e911b9cc62532 | 4,255 |
def precip_units(units):
"""
Return a standardized name for precip units.
"""
kgm2s = ['kg/m2/s', '(kg/m^2)/s', 'kg/m^2/s', 'kg m^-2 s^-1',
'kg/(m^2 s)', 'kg m-2 s-1']
mmday = ['mm/day', 'mm day^-1']
if units.lower() in kgm2s:
return 'kg m^-2 s^-1'
elif units.lower() in mmday:
return 'mm day^-1'
else:
raise ValueError('Unknown units ' + units) | e5f94c3dd41b68d2e7b6b7aa1905fd5508a12fab | 4,258 |
def read_user(msg):
"""Read user input.
:param msg: A message to prompt
:type msg: ``str``
:return: ``True`` if user gives 'y' otherwhise False.
:rtype: ``bool``
"""
user_input = input("{msg} y/n?: ".format(msg=msg))
return user_input == 'y' | 662e95002130a6511e6e9a5d6ea85805f6b8f0f5 | 4,261 |
def stringify_parsed_email(parsed):
"""
Convert a parsed email tuple into a single email string
"""
if len(parsed) == 2:
return f"{parsed[0]} <{parsed[1]}>"
return parsed[0] | 6552987fe6a06fdbb6bd49e5d17d5aadaae3c832 | 4,267 |
def base_to_str( base ):
"""Converts 0,1,2,3 to A,C,G,T"""
if 0 == base: return 'A'
if 1 == base: return 'C'
if 2 == base: return 'G'
if 3 == base: return 'T'
raise RuntimeError( 'Bad base: %d' % base ) | f1c98b7c24fae91c1f809abe47929d724c886168 | 4,268 |
def is_array_of(obj, classinfo):
"""
Check if obj is a list of classinfo or a tuple of classinfo or a set of classinfo
:param obj: an object
:param classinfo: type of class (or subclass). See isinstance() build in function for more info
:return: flag: True or False
"""
flag = False
if isinstance(obj, classinfo):
pass
elif all(isinstance(item, classinfo) for item in obj):
flag = True
return flag | 5fecce974b5424cff7d5e6a4a9f9bd1482e10e85 | 4,276 |
from textwrap import dedent
def make_check_stderr_message(stderr, line, reason):
"""
Create an exception message to use inside check_stderr().
"""
return dedent("""\
{reason}:
Caused by line: {line!r}
Complete stderr: {stderr}
""").format(stderr=stderr, line=line, reason=reason) | a6510e8036ab27e6386e6bc8e6c33727849282c0 | 4,277 |
def list_in_list(a, l):
"""Checks if a list is in a list and returns its index if it is (otherwise
returns -1).
Parameters
----------
a : list()
List to search for.
l : list()
List to search through.
"""
return next((i for i, elem in enumerate(l) if elem == a), -1) | 494d9a880bcd2084a0f50e292102dc8845cbbb16 | 4,280 |
def _GenerateGstorageLink(c, p, b):
"""Generate Google storage link given channel, platform, and build."""
return 'gs://chromeos-releases/%s-channel/%s/%s/' % (c, p, b) | e5e4a0eb9e27b0f2d74b28289c8f02dc0454f438 | 4,285 |
def _has_desired_permit(permits, acategory, astatus):
"""
return True if permits has one whose
category_code and status_code match with the given ones
"""
if permits is None:
return False
for permit in permits:
if permit.category_code == acategory and\
permit.status_code == astatus:
return True
return False | 4cac23303e2b80e855e800a7d55b7826fabd9992 | 4,287 |
def get_input(request) -> str:
"""Get the input song from the request form."""
return request.form.get('input') | de237dc0ad3ce2fa6312dc6ba0ea9fe1c2bdbeb3 | 4,294 |
def get_gs_distortion(dict_energies: dict):
"""Calculates energy difference between Unperturbed structure and most favourable distortion.
Returns energy drop of the ground-state relative to Unperturbed (in eV) and the BDM distortion that lead to ground-state.
Args:
dict_energies (dict):
Dictionary matching distortion to final energy, as produced by organize_data()
Returns:
(energy_difference, BDM_ground_state_distortion)
"""
if len(dict_energies['distortions']) == 1:
energy_diff = dict_energies['distortions']['rattled'] - dict_energies['Unperturbed']
if energy_diff < 0 :
gs_distortion = 'rattled' #just rattle (no BDM)
else:
gs_distortion = "Unperturbed"
else:
lowest_E_RBDM = min(dict_energies['distortions'].values()) #lowest E obtained with RBDM
energy_diff = lowest_E_RBDM - dict_energies['Unperturbed']
if lowest_E_RBDM < dict_energies['Unperturbed'] : #if energy lower that with Unperturbed
gs_distortion = list(dict_energies['distortions'].keys())[list(dict_energies['distortions'].values()).index( lowest_E_RBDM )] #BDM distortion that lead to ground-state
else:
gs_distortion = "Unperturbed"
return energy_diff, gs_distortion | 2f23103ccac8e801cb6c2c4aff1fb4fc08341e78 | 4,300 |
from typing import Counter
def get_vocabulary(list_):
"""
Computes the vocabulary for the provided list of sentences
:param list_: a list of sentences (strings)
:return: a dictionary with key, val = word, count and a sorted list, by count, of all the words
"""
all_the_words = []
for text in list_:
for word in text:
all_the_words.append(word)
vocabulary_counter = Counter(all_the_words)
vocabulary_sorted = list(map(lambda x: x[0], sorted(vocabulary_counter.items(), key=lambda x: -x[1])))
return vocabulary_sorted, vocabulary_counter | d6c357a5768c2c784c7dfe97743d34795b2695c0 | 4,310 |
import math
def split(value, precision=1):
"""
Split `value` into value and "exponent-of-10", where "exponent-of-10" is a
multiple of 3. This corresponds to SI prefixes.
Returns tuple, where the second value is the "exponent-of-10" and the first
value is `value` divided by the "exponent-of-10".
Args
----
value : int, float
Input value.
precision : int
Number of digits after decimal place to include.
Returns
-------
tuple
The second value is the "exponent-of-10" and the first value is `value`
divided by the "exponent-of-10".
Examples
--------
.. code-block:: python
si_prefix.split(0.04781) -> (47.8, -3)
si_prefix.split(4781.123) -> (4.8, 3)
See :func:`si_format` for more examples.
"""
negative = False
digits = precision + 1
if value < 0.:
value = -value
negative = True
elif value == 0.:
return 0., 0
expof10 = int(math.log10(value))
if expof10 > 0:
expof10 = (expof10 // 3) * 3
else:
expof10 = (-expof10 + 3) // 3 * (-3)
value *= 10 ** (-expof10)
if value >= 1000.:
value /= 1000.0
expof10 += 3
elif value >= 100.0:
digits -= 2
elif value >= 10.0:
digits -= 1
if negative:
value *= -1
return value, int(expof10) | 776ded073807773b755dcd7ab20c47d1f33ca1e1 | 4,312 |
def load_secret(name, default=None):
"""Check for and load a secret value mounted by Docker in /run/secrets."""
try:
with open(f"/run/secrets/{name}") as f:
return f.read().strip()
except Exception:
return default | 1aac980ad6bc039964ef9290827eb5c6d1b1455f | 4,321 |
import re
def convert_as_number(symbol: str) -> float:
"""
handle cases:
' ' or '' -> 0
'10.95%' -> 10.95
'$404,691,250' -> 404691250
'$8105.52' -> 8105.52
:param symbol: string
:return: float
"""
result = symbol.strip()
if len(result) == 0:
return 0
result = re.sub('[%$, *]', '', result)
return float(result) | cea1d6e894fa380ecf6968d5cb0ef1ce21b73fac | 4,323 |
import operator
def most_recent_assembly(assembly_list):
"""Based on assembly summaries find the one submitted the most recently"""
if assembly_list:
return sorted(assembly_list, key=operator.itemgetter('submissiondate'))[-1] | 1d7ecf3a1fa862e421295dda0ba3d89863f33b0f | 4,327 |
def evenly_divides(x, y):
"""Returns if [x] evenly divides [y]."""
return int(y / x) == y / x | dbf8236454e88805e71aabf58d9b7ebd2b2a6393 | 4,333 |
def compOverValueTwoSets(setA={1, 2, 3, 4}, setB={3, 4, 5, 6}):
"""
task 0.5.9
comprehension whose value is the intersection of setA and setB
without using the '&' operator
"""
return {x for x in (setA | setB) if x in setA and x in setB} | 2b222d6c171e0170ace64995dd64c352f03aa99b | 4,336 |
def is_numpy_convertable(v):
"""
Return whether a value is meaningfully convertable to a numpy array
via 'numpy.array'
"""
return hasattr(v, "__array__") or hasattr(v, "__array_interface__") | 163da2cf50e2172e1fc39ae8afd7c4417b02a852 | 4,341 |
from datetime import datetime
def get_fake_datetime(now: datetime):
"""Generate monkey patch class for `datetime.datetime`, whose now() and utcnow() always returns given value."""
class FakeDatetime:
"""Fake datetime.datetime class."""
@classmethod
def now(cls):
"""Return given value."""
return now
@classmethod
def utcnow(cls):
"""Return given value."""
return now
return FakeDatetime | f268640c6459f4eb88fd9fbe72acf8c9d806d3bc | 4,342 |
def compress_pub_key(pub_key: bytes) -> bytes:
"""Convert uncompressed to compressed public key."""
if pub_key[-1] & 1:
return b"\x03" + pub_key[1:33]
return b"\x02" + pub_key[1:33] | 05824112c6e28c36171c956910810fc1d133c865 | 4,346 |
def _(text):
"""Normalize white space."""
return ' '.join(text.strip().split()) | f99f02a2fe84d3b214164e881d7891d4bfa0571d | 4,347 |
def _infer_title(ntbk, strip_title_header=True):
"""Infer a title from notebook metadata.
First looks in metadata['title'] and if nothing is found,
looks for whether the first line of the first cell is an H1
header. Optionally it strips this header from the notebook content.
"""
# First try the notebook metadata, if not found try the first line
title = ntbk.metadata.get('title')
# If the first line of the ontebook is H1 header, assume it's the title.
if title is None:
first_cell_lines = ntbk.cells[0].source.lstrip().split('\n')
if first_cell_lines[0].startswith('# '):
title = first_cell_lines.pop(0).strip('# ')
if strip_title_header is True:
ntbk.cells[0].source = '\n'.join(first_cell_lines)
return title | e8152f0c160d2cb7af66b1a20f4d95d4ea16c703 | 4,349 |
def get_recommendations(commands_fields, app_pending_changes):
"""
:param commands_fields:
:param app_pending_changes:
:return: List of object describing command to run
>>> cmd_fields = [
... ['cmd1', ['f1', 'f2']],
... ['cmd2', ['prop']],
... ]
>>> app_fields = {
... 'f2': {'field': 'f2', 'user': 'api', 'updated': '00:00'}
... }
>>> from pprint import pprint
>>> pprint(get_recommendations(cmd_fields, app_fields))
[{'command': 'cmd1', 'field': 'f2', 'updated': '00:00', 'user': 'api'}]
"""
recommended_cmds = []
for cmd in commands_fields:
cmd_name = cmd[0]
cmd_fields = cmd[1]
for field in cmd_fields:
if field in app_pending_changes.keys():
recommended_cmds.append({
'command': cmd_name,
'field': field,
'user': app_pending_changes[field]['user'],
'updated': app_pending_changes[field]['updated'],
})
break
return recommended_cmds | 03fa583a5d4ea526cfeaa671418488218e1b227f | 4,354 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.