content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from datetime import datetime
def str2datetime(input_date):
"""Transform a string to datetime object.
Args:
input_date (str): String date of the format Y-m-d. It can
also be 'today' which will return today's date.
Returns:
(`datetime.datetime`)
"""
if input_date == "today":
return datetime.today()
else:
return datetime.strptime(input_date, "%Y-%m-%d") | 7e842bfc73b6d9c5e9d800bc5d39990f508e6461 | 100,798 |
import attr
def IntParameter(default, unit=None, **kwargs):
"""Adds an integer parameter.
Args:
default (int): Default value.
unit (optional, str): Unit to record in metadata.
Default: None.
"""
if unit is not None:
kwargs["metadata"] = dict(unit=str(unit))
return attr.ib(default=default, converter=int, **kwargs) | 37bd867f63021e9781364dff189c170be85542d1 | 100,799 |
def is_view(plugin_type):
"""Decorator to mark a plugin method as being a view.
Views can be called via the '/plugins/' interface of kitchen and should
either return None or a proper Django HTTPResponse object
"""
if callable(plugin_type):
plugin_type.__is_view__ = True
plugin_type.__p_type__ = 'list'
return plugin_type
else:
def inner(func):
func.__is_view__ = True
func.__p_type__ = plugin_type
return func
return inner | a02894af903f1c0eb46b876e9e1f5cff517e627e | 100,804 |
def bool_setting(value):
"""return `True` if the provided (lower-cased) text is one of {'1', 'ok', 'yes', 'true', 'on'}"""
return str(value).lower() in {"1", "ok", "yes", "true", "on"} | 874bc42d2fd6784ba9b3ac3739463fed0cdf4eb5 | 100,807 |
def is_int(s : str) -> bool:
"""
Check if string is an int.
"""
try:
float(s)
except Exception as e:
return False
return float(s).is_integer() | f83b1c7c683807397880f685cf6913d2270f5252 | 100,808 |
def indices(alist,value):
"""
Returns the indices for a given value in a list
"""
ind = [item for item in range(len(alist)) if alist[item] == value]
return ind | db009b670aa70f5cb9087533a41c6e76854e1d22 | 100,810 |
import math
def choose(n, k):
"""Compute the binomial coefficient.
Uses // operator to force integer division.
Arguments:
n (int): Possibilities.
k (int): Unordered outcomes.
Returns:
int, the binomial coefficient.
"""
return math.factorial(n) // (math.factorial(k) * math.factorial(n - k)) | e1d49943e7ae18968a0de9e190fc336c37edb1b2 | 100,812 |
def _test_dist(id1, id2):
"""
Return distance between identifiers id1 and id2.
The identifiers are of the form 'time=some number'.
"""
# extract the numbers using regex:
#t1 = re.search(r"time=(.*)", id1).group(1)
#t2 = re.search(r"time=(.*)", id2).group(1)
t1 = id1[5:]; t2 = id2[5:]
d = abs(float(t1) - float(t2))
return d | 083618ab5ec220940a42223ce0d060df38e8ff43 | 100,816 |
def get_nls_from_nlogo(lines):
"""Gets NetLogo source from an .nlogo file.
The nlogo file format contains a lot of different things, and thus we need to extract the actual NetLogo code from it.
Parameters
----------
lines : list of str
The contents of a file as a list of strings
Returns
-------
lines : list of str
The NetLogo code.
"""
breakline = len(lines)
for i in range(len(lines)):
line = lines[i].strip("\n")
if line.startswith("@#$#@#$#@"):
breakline = i
break
return lines[0:breakline] | 1282b75f22e9001eea7848d5d007be7f2b7c4e8b | 100,826 |
def serialize_record_to_dict(record):
"""Serialize an article record into a dictionary.
Args:
record: The article as an ArticleRecord to be serialized.
Returns:
Dictionary serialization of the input record.
"""
return {
'title': record.get_title(),
'link': record.get_link(),
'source': record.get_source(),
'score': record.get_score(),
'linkWillSearch': record.get_link_will_search()
} | 75a4bf4d3ac3fcab26a461e857a6024b26e8f017 | 100,827 |
def _invert_targets_pairs(targets_pairs, label_encoder):
"""
Given a list of targets pairs of the form 'target1+target2', revert back
to the original labeling by using `label_encoder.inverse_transform`
Parameters
----------
targets_pairs : list or array-like of str
label_encoder : fitted LabelEncoder
Returns
-------
targets_pairs : list of str
the inversed targets_pairs
"""
t1t2 = [l.split('+') for l in targets_pairs]
t1, t2 = zip(*t1t2)
t1 = label_encoder.inverse_transform([int(t) for t in t1])
t2 = label_encoder.inverse_transform([int(t) for t in t2])
return ['+'.join([str(tt1), str(tt2)]) for tt1, tt2 in zip(t1, t2)] | 3ed6ddfab45ebb3486efa6a54e9decda87e1a956 | 100,829 |
import json
def build_categories(obj):
"""Returns a list of categories for object."""
return json.loads(obj.categories) if obj.categories else [] | 7dcbffb70dd3db921f96adc0f09839900542e73e | 100,831 |
def increment_period(value, periods, frequency):
"""Incrementa una fecha en X períodos, según su frecuencia."""
actions = {
"A": lambda: value.replace(years=+periods),
"6M": lambda: value.replace(months=+(6 * periods)),
"Q": lambda: value.replace(months=+(3 * periods)),
"M": lambda: value.replace(months=+periods),
"D": lambda: value.replace(days=+periods),
}
try:
return actions[frequency]()
except KeyError:
raise ValueError("No se reconoce la frecuencia {}".format(frequency)) | 659ca01eb94e2625dbb1228487aa7ae69a97e88c | 100,832 |
from typing import List
from typing import Dict
def select_most_frequent_shingles(matches: List[str],
db: Dict[str, int],
min_count_split: int,
threshold: float):
"""Select the most frequent shingles that matches the wildcard shingle
Parameters:
-----------
matches : List[str]
A list of shingles from the database (`db`) that matches the current
wildcard shingle in the `expandshingle` function.
db: dict
Database with shingles as `key` and their frequencies/counts as `value`
Assumptions:
- Python's `dict` are automatically in alphabetic order but not key
length, i.e. we still need to filter keys by length initially.
- The database `db` is immutable.
Preprocessing: Make sure that each shingle has a sufficient number of
counts/frequencies, e.g. remove shingles that occur less than 20x.
threshold: float (Default: 0.80)
Replace max. `1.0 - threshold` of the least frequent shingles with
the wildcard shingle.
min_count_split: int (Default: 2)
If the combined frequency of all shingles covered by one wildcard
shingle (count sum of the regex query results) is less than the
specified minimum total frequency, then the recursion aborts.
Returns:
--------
selected_shingles : List[str]
The selected most frequent shingles
residual_count : int
The residual counts (of the unselected shingles) that will be
assigned to the wildcard shingle in `expandshingle`
Example:
--------
selected_shingles, residual_count = select_most_frequent_shingles(
matches, db, min_count_split, threshold)
"""
# read only matches
candidates = [item for item in db.items() if item[0] in matches]
# proceed if there at least 2 candidates
if len(candidates) == 0:
return [], 0
if len(candidates) == 1:
return [], candidates[0][1]
# sort by descending frequency
candidates = sorted(candidates, key=lambda item: -item[1])
# compute total counts
total = sum([val for _, val in candidates])
if total < min_count_split:
return [], total
# find most frequent (`val`) shingles (`key`) up to 90% of all matches
# always ignore the least frequent shingle and use the wildcard version
cumpct = 0.0
cumcnt = 0
selected = []
for key, val in candidates[:-1]:
# abort if the sum of selected shingles reached threshold
cumpct += val / total
if cumpct > threshold:
break
# select shingle
cumcnt += val
selected.append(key)
# done
return selected, total - cumcnt | 98db2daa4091109ea3964d7821744df89726722b | 100,833 |
def min_max_voltage(voltage):
"""
outputs the minimum and maximum voltage recorded
:param voltage: (list) array of voltages
:return: tuple of the minimum and maximum voltages
"""
min_voltage = min(voltage)
max_voltage = max(voltage)
min_max_voltages = (min_voltage, max_voltage)
return min_max_voltages | d84407b5159b933c4a89b4e14585c5204982de36 | 100,834 |
def polynomial1D(x, m, b):
"""Return the value of a line with slope m and offset b
x: the independent variable
m: the slope of the line
b: the offset of the line
"""
return (m * x) + b | 4715d16dedcd392e9f534710bb7fe98fc37c9191 | 100,837 |
def update_mol(mol):
"""
Update atom types, multiplicity, and atom charges in the molecule.
Args:
mol (Molecule): The molecule to update.
Returns:
Molecule: the updated molecule.
"""
for atom in mol.atoms:
atom.update_charge()
mol.update_atomtypes(log_species=False, raise_exception=False)
mol.update_multiplicity()
mol.identify_ring_membership()
return mol | cada303bc6530110a55705c7f147664fe00b7128 | 100,838 |
def sort_reference_list(reference_list):
"""Given a reference_list, sort it by number"""
used_reference_list = []
# Remove unused references from list
for reference in reference_list:
if reference.get('number'):
used_reference_list.append(reference)
return sorted(used_reference_list, key=lambda k: k['number']) | d83d5a5064133acb537da535cb3e29fa2d4c44b7 | 100,840 |
def get_value(dct: dict, *keys):
"""access dict with given keys"""
for key in keys:
dct = dct.get(key, {})
return dct | 2e9f5275a400f7eed50213016da02a861a6b4c83 | 100,841 |
def countSuccess(L, diff, hero) :
"""
Counts the number of success for the roll.
Parameters
----------
L: int list
Decreasing sorted list with values between 1 and 10.
diff : int
Difficulty of the roll. A dice is counted as a success if the value of the dice is greater or equal to the difficulty.
hero : optional bool
If the character is a hero, its 10 count two success instead of one, but are cancelled first by a critical failure (a one on another dice).
"""
success = 0
for val in L :
if val == 1 :
success -= 1
elif val == 10 :
if hero :
success += 2
else :
success += 1
elif val >= diff :
success += 1
return success | 342b0b661894117567709b930caf32bf8129e4d8 | 100,846 |
from pathlib import Path
def get_number_of_files_in_dir(directory):
"""
Sums the number of files in a directory
:param directory: Any directory with files
:return: Number of files in directory
"""
directory = Path(directory)
files = directory.iterdir()
total_files = sum(1 for x in files)
return total_files | 2cf080d5f839bd155faa75e6db0d3e3a5cf49127 | 100,851 |
from typing import Optional
from typing import Tuple
def data_row_name_append(data_rows: Optional[Tuple[Optional[int], Optional[int]]]) -> str:
"""String to name of data for selected rows only"""
if data_rows is not None and not all(v is None for v in data_rows):
return f':Rows[{data_rows[0]}:{data_rows[1]}]'
else:
return '' | f8b823a669cf976884098edd56ebf52c528d7378 | 100,852 |
def endpointId_to_entityId(endpointId: str) -> str:
"""Use for converting Alexa endpoint to HA entity id."""
return endpointId.replace("_", ".", 1) | 2290f9c58488172d34a49d1b2756f4bd60c73915 | 100,853 |
def first_int(*args, default=1):
"""Parse the first integer from an iterable of string arguments."""
for arg in args:
try:
return int(arg)
except ValueError:
continue
return default | 262546c0a3db74d4908b314746209ada91eb34b9 | 100,859 |
def get_node_ips_from_config(boot_config):
"""
Returns the IPs of the configured nodes
:param boot_config: the snaps-boot config to parse
:return: a list if IPs for the given nodes
"""
out_hosts = list()
if ('PROVISION' in boot_config
and 'DHCP' in boot_config['PROVISION']
and 'subnet' in boot_config['PROVISION']['DHCP']):
for subnet in boot_config['PROVISION']['DHCP']['subnet']:
if 'bind_host' in subnet:
for bind_host in subnet['bind_host']:
if 'ip' in bind_host:
out_hosts.append(bind_host['ip'])
return out_hosts | 0bc9fc9bc8f5ef577ecf21e0a754f0b3ac1d4e0a | 100,863 |
def host_and_page(url):
""" Splits a `url` into the hostname and the rest of the url. """
url = url.split('//')[1]
parts = url.split('/')
host = parts[0]
page = "/".join(parts[1:])
return host, '/' + page | db035aeeaf2c1ae7b9eb00f00daf5673a9551edf | 100,865 |
from typing import Any
import enum
import dataclasses
def unparse(data: Any) -> Any:
"""
Coerces `data` into a JSON-like or YAML-like object.
Informally, this function acts as the inverse of `parse`. The order of
fields in data classes will be preserved if the implementation of `dict`
preserves the insertion order of keys.
"""
if isinstance(data, enum.Enum):
return data.value
if dataclasses.is_dataclass(data):
new_data = {}
for field in dataclasses.fields(data):
k = field.name
v = getattr(data, field.name)
if v is not field.default or field.default is not None:
new_data[unparse(k)] = unparse(v)
return new_data
if isinstance(data, list):
return [unparse(x) for x in data]
if isinstance(data, dict):
return {unparse(k): unparse(v) for (k, v) in sorted(data.items())}
return data | 4092b7a0438b5ea98a2e31edf3d4c91fe5f9b5b0 | 100,868 |
def evaluate_final(restore, classifier, eval_sets, batch_size):
"""
Function to get percentage accuracy of the model, evaluated on a set of chosen datasets.
restore: a function to restore a stored checkpoint
classifier: the model's classfier, it should return genres, logit values, and cost for a given minibatch of the evaluation dataset
eval_set: the chosen evaluation set, for eg. the dev-set
batch_size: the size of minibatches.
"""
restore(best=True)
percentages = []
length_results = []
for eval_set in eval_sets:
bylength_prem = {}
bylength_hyp = {}
genres, hypotheses, cost = classifier(eval_set)
correct = 0
cost = cost / batch_size
full_batch = int(len(eval_set) / batch_size) * batch_size
for i in range(full_batch):
hypothesis = hypotheses[i]
length_1 = len(eval_set[i]['sentence1'].split())
length_2 = len(eval_set[i]['sentence2'].split())
if length_1 not in bylength_prem.keys():
bylength_prem[length_1] = [0,0]
if length_2 not in bylength_hyp.keys():
bylength_hyp[length_2] = [0,0]
bylength_prem[length_1][1] += 1
bylength_hyp[length_2][1] += 1
if hypothesis == eval_set[i]['label']:
correct += 1
bylength_prem[length_1][0] += 1
bylength_hyp[length_2][0] += 1
percentages.append(correct / float(len(eval_set)))
length_results.append((bylength_prem, bylength_hyp))
return percentages, length_results | 288d2f3780c65dd068a819a1b9ade4b6075c4f9c | 100,872 |
import socket
def set_socket_io_timeouts(transport, seconds, useconds=0):
"""
Set timeout for transport sockets.
Useful with highly concurrent workloads.
Returns False if it failed to set the timeouts.
"""
seconds = (seconds).to_bytes(8, 'little')
useconds = (useconds).to_bytes(8, 'little')
sock = transport.get_extra_info('socket')
try:
sock.setsockopt(
socket.SOL_SOCKET,
socket.SO_RCVTIMEO,
seconds + useconds,
)
sock.setsockopt(
socket.SOL_SOCKET,
socket.SO_SNDTIMEO,
seconds + useconds,
)
return True
except OSError:
return False | 1a7fda1e0517422b75325afba4ad8582e21893ba | 100,875 |
def get_dtypes(df):
"""
Returns all dtypes of variables in dataframe
Parameters
----------
df: Pandas dataframe or series
Returns
-------
Dataframe with all dtypes per column
"""
return df.dtypes | ff730a416b680c0d40564e9167015311c9910b1d | 100,876 |
from typing import Dict
import json
def get_msd_score_matches(match_scores_path: str) -> Dict:
"""
Returns the dictionary of scores from the match scores file.
:param match_scores_path: the match scores path
:return: the dictionary of scores
"""
with open(match_scores_path) as f:
return json.load(f) | 2b339285bffe1adaf032319d22eac5d2ac27cedc | 100,878 |
def complex_vct_str ( vct , format = '%.5g%-+.5gj' ) :
"""Convert vector of complex types to string"""
try :
lst = []
for c in vct :
cc = complex ( c )
item = format % ( cc.real , cc.imag )
lst.append ( cc )
return '[ ' + ', '.join ( lst ) + ' ]'
except TypeError :
pass
return complex_vct_str ( vct , format = '%.5g%-+.5gj' ) | f78775eef475f4d0a785726523710e20cc6f24a2 | 100,879 |
from typing import Union
from pathlib import Path
from typing import Dict
from typing import Any
import json
def load_data_from_json(path: Union[Path, str]) -> Dict[str, Any]:
"""Load ASCII frames from JSON
:param path: JSON file path
:return: ASCII frames
"""
with open(path, 'r') as file:
return json.load(file) | 5223a69d2067b0a0da1e5b7041a78196b67e1a99 | 100,883 |
def make_word_schedule(block):
"""
This function takes the initial 512 bit block and divides it up into 16 x 32 bit words.
It then appends a further 48 x 16 bit words (all set to zero) to bring the word schedule
up to 64 words each of 32 bits.
:param block:
:return:
"""
words = []
for i in range(16):
word = ''
for j in range(i * 32, i * 32 + 32):
word += block[j]
words.append(word)
for i in range(48):
word = ''
for j in range(32):
word += '0'
words.append(word)
return words | 448e327ed91b6c4ec4c876a05c774de47669b0f2 | 100,888 |
def links_to_sets(links):
"""
:param links: Dict of [doc_id, set of connected doc ids]
:return clusters: Frozen set of frozen sets, each frozen set contains doc ids in that cluster
"""
removed = set()
clusters = []
for (pivot, linkage) in links.iteritems():
if pivot not in removed:
clusters.append(frozenset(linkage))
removed.update(linkage)
removed.add(pivot)
clusters = frozenset(clusters)
return clusters | 3b98e65ee8410a3f08387b0c056d28cae7b67635 | 100,890 |
def untar_cmd(src, dest):
""" Create the tar commandline call
Args:
src (str): relative or full path to source tar file
dest (str): full path to output directory
Returns:
str: the tar command ready for execution
Examples:
>>> untar_cmd('my.tar.gz', '/path/to/place')
'tar --directory /path/to/place -xvf my.tar.gz'
"""
return ' '.join(['tar', '--directory', dest, '-xvf', src]) | ae70f62e17d5ddad3777cbac83a78086aa3eb830 | 100,893 |
def excstr(e):
"""Return a string for the exception.
The string will be in the format that Python normally outputs
in interactive shells and such:
<ExceptionName>: <message>
AttributeError: 'object' object has no attribute 'bar'
Neither str(e) nor repr(e) do that.
"""
if e is None:
return None
return '%s: %s' % (e.__class__.__name__, e) | b789621489d37e38e8b3179442f62140e2fce4a6 | 100,894 |
def get_name_no_py(context):
"""return the component name without .py extension (if existing)
Args:
context (dict): complete package and component transformation
Returns:
str: component name without possible .py extension.
Examples:
>>> get_name_no_py({'componentName':"nopy"})
>>> 'nopy'
>>> get_name_no_py({'componentName':"nopy.py"})
>>> 'nopy'
"""
return context['componentName'].replace('.py', '') | f88e71caf172c951510a0a6c94ff2e845768f20b | 100,895 |
import pickle
def load_file(filepath):
"""
Loads a pickle file.
:param filepath: the path of the file to load.
"""
with open(filepath, 'rb') as handle:
data = pickle.load(handle)
return data | 9903be9cd164290cbeebe0cc2cfa950f3c98aba0 | 100,901 |
def normRange(imgarray):
"""
normalize the range of an image between 0 and 1
"""
min1=imgarray.min()
max1=imgarray.max()
if min1 == max1:
return imgarray - min1
return (imgarray - min1)/(max1 - min1) | 70db125a6bc61b1a07c5f2bcdfaeb9c0b1dedfbd | 100,903 |
def check_and_remove_trailing_occurrence(txt_in, occurrence):
"""Check if a string ends with a given substring. Remove it if so.
:param txt_in: Input string
:param occurrence: Substring to search for
:return: Tuple of modified string and bool indicating if occurrence was found
"""
n_occurrence = len(occurrence)
if (txt_in[-n_occurrence:] == occurrence):
txt_out = txt_in[0:-n_occurrence]
flag_found = True
else:
txt_out = txt_in
flag_found = False
return txt_out, flag_found | 09c0214dca7dbdf9ec7d199bb9348411cebe5ac1 | 100,908 |
def TENSOR_1D_FILTER(arg_value):
"""Only keeps 1-D tensors."""
return arg_value.is_tensor and len(arg_value.shape) == 1 | d46b5b45ee4bb46bd3bf85318c4f629ae0ddf8f8 | 100,910 |
def is_bitfield_as_enum_array(parameter: dict) -> bool:
"""Whether the parameter is a bitfield represented as an enum array."""
return "bitfield_as_enum_array" in parameter | fa8764789ea7059c6868f6d9dcef8e34debf9810 | 100,912 |
def typename(value):
"""Return the name of value's type without any module name."""
return type(value).__name__ | d1cb87b480f6b4114165d0063a6982e05ddb5a80 | 100,918 |
import shlex
def CommandListToCommandString(cmd):
"""Converts shell command represented as list of strings to a single string.
Each element of the list is wrapped in double quotes.
Args:
cmd: list of strings, shell command.
Returns:
string, shell command.
"""
return ' '.join([shlex.quote(segment) for segment in cmd]) | 2f262c170a881235c257f94af86155275f54c63f | 100,922 |
def make_friends_list(json_data: dict) -> list:
"""
Returns a list of tuples: [(screen_name, location), ...]
from json data (.json object)
>>> make_friends_list({\
"users": [\
{\
"id": 22119703,\
"id_str": "22119703",\
"name": "Niki Jennings",\
"screen_name": "nufipo",\
"location": "Kyiv"\
}]})
[('nufipo', 'Kyiv')]
"""
friends = []
for friend in json_data['users']:
location = friend['location']
if location != '':
friends.append( (friend['screen_name'], location) )
return friends | 6a0d03e958ba7a697522919391c0099f5144d223 | 100,923 |
def get_interval(value, num_list):
"""
Helper to find the interval within which the value lies
"""
if value < num_list[0]:
return (num_list[0], num_list[0])
if value > num_list[-1]:
return (num_list[-1], num_list[-1])
if value == num_list[0]:
return (num_list[0], num_list[1])
if value == num_list[-1]:
return (num_list[-2], num_list[-1])
for index, num in enumerate(num_list):
if value <= num:
return (num_list[index - 1], num_list[index]) | ac55ce35b809599689182c984f35fe221eb65772 | 100,927 |
def count_morphs(settings):
"""
Count the number of morph sequences,
given the number of key frames and loop switch setting.
"""
return len(settings['keyframes']) - 1 + settings['render']['loop'] | 3b3d61eea48d09272bf427d6acdbba85c0f6af2a | 100,930 |
def cross_v2(vec1, vec2):
"""Return the crossproduct of the two vectors as a Vec2.
Cross product doesn't really make sense in 2D, but return the Z component
of the 3d result.
"""
return vec1.y * vec2.x - vec1.x * vec2.y | d0b6a927af6d175ee2c3cb44aa745b52eb004c67 | 100,936 |
import uuid
def create_random_string(prefix="", l=10):
"""
Creates and returns a random string consisting of *l* characters using a uuid4 hash. When
*prefix* is given, the string will have the format ``<prefix>_<random_string>``.
"""
s = ""
while len(s) < l:
s += uuid.uuid4().hex
s = s[:l]
if prefix:
s = "{}_{}".format(prefix, s)
return s | 57baceacdbf304909c0f94f61102b78b4cdf2758 | 100,938 |
import re
import logging
def get_device(device: str):
"""Get device (cuda and device order) from device name string.
Args:
device: Device name string.
Returns:
Tuple[bool, Optional[int]]: A tuple containing flag for CUDA device and CUDA device order. If the CUDA device
flag is `False`, the CUDA device order is `None`.
"""
# obtain device
device_num = None
if device == 'cpu':
cuda = False
else:
# match something like cuda, cuda:0, cuda:1
matched = re.match(r'^cuda(?::([0-9]+))?$', device)
if matched is None: # load with CPU
logging.warning('Wrong device specification, using `cpu`.')
cuda = False
else: # load with CUDA
cuda = True
device_num = int(matched.groups()[0])
if device_num is None:
device_num = 0
return cuda, device_num | df60ac6a7a5f17c3d2454e67e02ef38804bed6c1 | 100,939 |
from pathlib import Path
def credentials_file() -> Path:
"""
Get path to credentials file.
:return: the path
"""
Path.home().joinpath('.jina').mkdir(parents=True, exist_ok=True)
return Path.home().joinpath('.jina').joinpath('access.yml') | e3e1d8f10252cb060f6422c9e882ee7c975a3f52 | 100,947 |
def merge_sublists(list_of_lists):
"""
merge list of sub_lists into single list
"""
return [ item for sub_list in list_of_lists for item in sub_list] | da21ad66d05634d9da8b96fb966c67389531ef39 | 100,949 |
import logging
def get_logger(name):
"""
Returns a logger with unified format and level set
"""
logging.basicConfig(format='[%(asctime)-15s][%(levelname)-7s] %(message)s',
level=logging.INFO)
logger = logging.getLogger(name)
return logger | 8e0f9f80d7c6cd97246cce55c2e4c3486975d36e | 100,950 |
def plasma_freq(n_e):
"""
Given an electron density parameter (n_e), compute the plasma frequency.
"""
eps0 = 8.8542E-12 #[A*s/(V*m)] Permittivity
e = 1.602E-19 #[C] Elementary charge
me = 9.109E-31 #[kg] Electron rest mass
omega_p = ((e**2)*n_e/(eps0*me))**0.5 #[Hz] Plasma frequency
return omega_p | 265e7ba622b92d409170bc3991c05d887426bba4 | 100,951 |
def get_sg_id(connector, instance):
"""
Get one security groups applied to the given instance.
:param connector: Active EC2Connection
:param instance: EC2Object Instance
:return: EC2Object SecurityGroup
"""
for sg in connector.get_all_security_groups():
for inst in sg.instances():
if inst.id == instance.id:
return sg | 59c02cfea814bf70591b554fb98befe12b4f05ea | 100,955 |
def check_if_excluded(path):
"""
Check if path is one we know we dont care about.
"""
exclusions= [ "src/CMake",
"src/_CPack_Packages",
"src/bin",
"src/archives",
"src/config-site",
"src/cqscore",
"src/exe",
"src/help",
"src/include",
"src/lib",
"src/plugins",
"src/sim",
"src/tools",
"src/third_party_builtin",
"src/java",
"src/svn_bin",
"src/visitpy",
".svn",
"CMakeFiles"]
for e in exclusions:
if path.find("/"+ e ) >=0:
return True
return False | 4fd264142c6d20eb5fd95b7e56108477709e8729 | 100,957 |
def get_rule_tags(rule):
"""Get the tags from a rule"""
if "properties" not in rule:
return []
return rule["properties"].get("tags", []) | f5094bde9fddce706489e45b6d588ff532b36c5e | 100,961 |
def number_to_choice(number):
"""Convert number to choice."""
# If number is 0, give me 'rock'
# If number is 1, give me 'paper'
# If number is 2, give me 'scissors'
random_dict = {0: 'rock', 1: 'paper', 2: 'scissors'}
return random_dict[number] | 0bc60c568395384dc1f734fb61d09fe2bc870e2c | 100,962 |
def split1d(Astart,Aend,Bstart,Bend):
"""For a 1-d pair of lines A and B:
given start and end locations,
produce new set of points for A, split by B.
For example:
split1d(1,9,3,5)
splits the line from 1 to 9 into 3 pieces,
1 to 3
3 to 5
and
5 to 9
it returns these three pairs and a list of whether
those points were inside B.
In this case the list is [False,True,False]
"""
#five options
#1 A and B don't intersect. This shouldn't happen
if (Astart>=Bend) or (Bstart>=Aend):
#Not sure what to do
assert False
#2 B starts first, and ends inside A:
if (Astart>=Bstart) and (Bend<Aend):
#return Astart-Bend Bend-Aend
return [[Astart,Bend],[Bend,Aend]], [True, False]
#3 B extends beyond limits of A in both directions:
if (Bstart<=Astart) and (Bend>=Aend):
#return A
return [[Astart,Aend]], [True]
#4 B starts in A and finishes after A
if (Astart<Bstart) and (Bend>=Aend):
#return Astart-Bstart Bstart-Aend
return [[Astart,Bstart],[Bstart,Aend]], [False,True]
#5 B is inside A
if (Astart<Bstart) and (Bend<Aend):
#return Astart-Bstart Bstart-Bend Bend-Aend
return [[Astart,Bstart],[Bstart,Bend],[Bend,Aend]], [False,True,False] | 84acb04c2cc19d4461d45ba63590eeaa7ca36146 | 100,974 |
def flattenDoc(docString):
""" Take an indented doc string, and remove its newlines and their surrounding whitespace
"""
clean = ''
lines = docString.split('\n')
for line in lines:
clean += line.strip() + ' '
return clean | acac55aa439d091c1270274a918a79f3bdbd912f | 100,977 |
from typing import Sequence
from typing import Any
from typing import List
def _space_list(list_: Sequence[Any]) -> List[str]:
""" Inserts whitespace between adjacent non-whitespace tokens. """
spaced_statement: List[str] = []
for i in reversed(range(len(list_))):
spaced_statement.insert(0, list_[i])
if i > 0 and not list_[i].isspace() and not list_[i-1].isspace():
spaced_statement.insert(0, " ")
return spaced_statement | b1a7e7d2e8f755ed43ac0b818d6b394ed4433e3c | 100,984 |
import math
def ligand_rmsd(pose1, pose2):
"""Calculate RMSD of two ligands
Args:
pose1 (pose): Pose 1
pose2 (pose): Pose 2
Returns:
float: RMSD score
"""
# define ligand residue id of pose 1
ref_res_num = 0
for j in range(1, pose1.size() + 1):
if not pose1.residue(j).is_protein():
ref_res_num = j
break
pose1_rsd = pose1.conformation().residue(ref_res_num)
inp_res_num = 0
for j in range(1, pose2.size() + 1):
if not pose2.residue(j).is_protein():
inp_res_num = j
break
pose2_rsd = pose2.conformation().residue(inp_res_num)
j = 1
dist_sum = 0
for i in range(1, pose1_rsd.nheavyatoms() + 1):
if j <= pose2_rsd.nheavyatoms():
x_dist = (pose1_rsd.atom(i).xyz()[
0] - pose2_rsd.atom(i).xyz()[0]) ** 2
y_dist = (pose1_rsd.atom(i).xyz()[
1] - pose2_rsd.atom(i).xyz()[1]) ** 2
z_dist = (pose1_rsd.atom(i).xyz()[
2] - pose2_rsd.atom(i).xyz()[2]) ** 2
dist_sum += x_dist + y_dist + z_dist
j += 1
rmsd = math.sqrt(dist_sum / pose1_rsd.nheavyatoms())
return rmsd | b466e524e7bfa184dc01976d4787eb482407a52f | 100,998 |
import time
def profile(f, *args, **kwargs):
"""
Execute f and return the result along with the time in seconds.
"""
now = time.perf_counter()
# execute and determine how long it took
return f(*args, **kwargs), time.perf_counter() - now | d28916962164eaa72df0b35cda4685d0c026584b | 101,000 |
def BFS(graph, s, t, parent):
"""
Populates parent with nodes to visit and returns true if there are nodes left to visit
Args:
graph: an array of arrays of integers where graph[a][b] = c is the max flow, c, between a and b.
s: Source of the graph
t: Sink or "end" of the graph
parent: Array holding the nodes to visit
"""
# Start with none of the nodes visited
visited = [False] * len(graph)
# Begin queue at source. Will hold all nodes yet to visit
queue = []
queue.append(s)
# "Visited" aka will visit source node
visited[s] = True
# While there are still nodes in queue
while queue:
# Current searching node
u = queue.pop(0)
# Check each possible connection
for ind in range(len(graph[u])):
# If that connection hasn't been visited and is recieving source
if visited[ind] is False and graph[u][ind] > 0:
# Add the connection to the queue of ones to search
queue.append(ind)
# Set it to being visited
visited[ind] = True
# Add the search to the parent
parent[ind] = u
return True if visited[t] else False | db01bf4893d29e7840e7a96738d8aefbd145f865 | 101,002 |
import re
def remove_quotes(path_string):
# type: (str) -> str
"""
Removes Quotes from a Path (e.g. Space-Protection)
:type path_string: str
:param path_string:
:rtype: str
:return: unquoted path
"""
return re.sub('\"', '', path_string) | a818e1636b1936e5c961763acf39bd4d71e9a51a | 101,004 |
import re
def make_title_site_similarity_function(site):
"""Curry the title_site_similarity function to only require a title."""
def remove_non_alphanumerics(word):
"""Returns the `word` with nonalphanumerics (and underscores)."""
return re.sub(r'[^\w]', '', word)
def title_site_similarity(title_part):
"""What portion of the words in the title part are in the site?
Don't count very common words like "the" towards the score.
http://www.world-english.org/english500.htm
"""
common_words = ['the', 'of', 'to', 'and', 'a', 'in', 'is', 'it']
result = 0.0
words = re.split(r'[. ]', title_part)
words = [word for word in words if word not in common_words]
for word in words:
word = word.lower()
word = remove_non_alphanumerics(word)
if word and word in site:
result += 1.0 / len(words)
return result
return title_site_similarity | e8fd6b10476ceb2339d69bc869018badca2ff459 | 101,007 |
def merge(left, right):
"""Merge two lists in ascending order."""
lst = []
while left and right:
if left[0] < right[0]:
lst.append(left.pop(0))
else:
lst.append(right.pop(0))
if left:
lst.extend(left)
if right:
lst.extend(right)
return lst | c2e815e14f8e81be9dff97cc0004d49a86e6d7fc | 101,012 |
def generator_single_int_tuple(random, args):
"""
Function to generate a new individual using the integer tuple representation.
The function returns a set of tuples values with a maximum of *candidate_max_size* elements.
Args:
random: the random number generator object
args (dict): keyword arguments
Returns:
set: a new individual where each element is composed by a tuple.
Notes:
Required arguments in args:
- *candidate_max_size* : number of integer values which compose a individual.
- *_ec* : configuration of evolutionary computation. The argument bounder is required to get the maximum value allowed for the individual values.
"""
size = random.randint(1, args["candidate_max_size"])
# first element of array has the lowers bounds and second element the upper bounds.
bounder = args["_ec"].bounder
tuples={}
for i in range(size):
id1 = random.randint(bounder.lower_bound[0], bounder.upper_bound[0])
id2 = random.randint(bounder.lower_bound[1], bounder.upper_bound[1])
if id1 not in tuples.keys():
tuples[id1] = id2
return {(a, b) for a, b in tuples.items()} | 36f607fb83f524b90389f825c79653f238b7f7bc | 101,020 |
def continued_fraction_recursive(N, D, k, i):
"""
Recursively computes the i-th term of a generalized finite continued
fraction. Use the wrapper function continued_fraction(N, D, k) instead
of this one.
@type N: function(int)
@param N: a function that returns the numerator in the i-th term
@type D: function(int)
@param D: a function that returns the denominator in the i-th term
@type k: int
@param k: total number of terms
@type i: int
@param i: index of this term
"""
if i == k:
return 1
return N(i) / (D(i) + continued_fraction_recursive(N, D, k, i + 1)) | 15e24b820cd3d4b24fdfc70ba93fde45207a9aaa | 101,021 |
def compose_line(title, file_stem):
""" Composes the line to be written to the index in md format """
index_line = f'* [{title}]({file_stem}.html)' + '\n'
return index_line | a015bea14f365641ea89baa8fab8fed72fbfb4f9 | 101,022 |
def is_multiply_of(value, multiply):
"""Check if value is multiply of multiply."""
return value % multiply == 0 | 613dbc0eb8c508f7f9238675628b08e9e9d734a8 | 101,027 |
import re
def alphanum_key(s):
"""Order files in a 'human' expected fashion."""
key = re.split(r'(\d+)', s)
key[1::2] = list(map(int, key[1::2]))
return key | e1545b791aecf6fd215048620eb6c05a23df30d8 | 101,030 |
def get_scope(request):
"""
Utility method to return the scope of a pytest request
:param request:
:return:
"""
if request.node is request.session:
return 'session'
elif hasattr(request.node, 'function'):
return 'function'
else:
return 'module' | 3b7364bcf9ccc95f958e7c82f1cf92571f38d3e4 | 101,033 |
def get_box_status(boxes, status="running"):
"""
Take a list of instances and return those that match the 'status' value
:param boxes: The list of boxes (instances) to search through
:param status: The status you are searching for
:return: A list of instances that match the status value passed
"""
box_list = []
for box in boxes:
if box["Instances"][0]["State"]["Name"] == status:
box_list.append(box)
return box_list | d47866fb6210ba261d04c8c004505ff684d6a599 | 101,038 |
def soft_thresholding_operator(z, l):
"""
Soft-thresholding operator.
"""
if z > l:
val = z - l
elif z < -l:
val = z + l
else:
val = 0
return val | 53b15c766f8b248858d758b81b96d8c594e5efb4 | 101,039 |
def extract_wiki_link(entry, lang):
"""
Extract the associated wikipedia link to an entry in a specific language
:param entry: entry data
:param lang: lang of wikipedia link, you want to extract
:return:
"""
if "sitelinks" in entry:
siteLinks = entry['sitelinks']
key = '{0}wiki'.format(lang)
if key in siteLinks:
return siteLinks[key]["url"]
return None | f281ae13231fb6d7762d56fff1d465cab6b60d3e | 101,051 |
def get_num_from_bond(bond_symbol: str) -> int:
"""Retrieves the bond multiplicity from a SMILES symbol representing
a bond. If ``bond_symbol`` is not known, 1 is returned by default.
:param bond_symbol: a SMILES symbol representing a bond.
:return: the bond multiplicity of ``bond_symbol``, or 1 if
``bond_symbol`` is not recognized.
"""
if bond_symbol == "=":
return 2
elif bond_symbol == "#":
return 3
else:
return 1 | 3464439e14b4f5f9667809b8cd0ad7fc04b3ef20 | 101,053 |
import json
def load_params(param_file):
"""loads a json parameter file."""
with open(param_file) as json_file:
return json.load(json_file) | 14e246119ca61c50a960a6f50ef1c631a5cf23d8 | 101,058 |
from datetime import datetime
def to_isoformat(item: str) -> str:
"""Compute the ISO formatted representation of a timestamp.
Args:
item:
The timestamp to be formatted.
Returns:
The ISO formatted representation of the timestamp.
"""
if item is not None:
return datetime.fromtimestamp(float(item)).isoformat() | a73975c6815dae314648276717d16ebefd6c0212 | 101,065 |
from datetime import datetime
def get_timestamp(timestamp_format="%Y%m%d_%H%M%S"):
"""Return timestamp with the given format."""
return datetime.now().strftime(timestamp_format) | b5a53d49df7c52598e9a171936e351869ef5cf6b | 101,066 |
from textwrap import dedent
def chomptxt(s: str) -> str:
"""
dedents a triple-quoted indented string, and replaces all single newlines with spaces.
replaces all double newlines (\\n\\n) with single newlines
Converts this:
txt('''
hello
world
here's another
line
''')
into this:
`hello world\\nhere's another line`
"""
res = dedent(s)
res = res.replace("\n\n", "[PRESERVEDNEWLINE]")
res = res.replace("\n", " ")
res = res.replace("[PRESERVEDNEWLINE]", "\n")
return res.strip() | bfc908bbdc33243e5e07cab6573a189df83731fe | 101,070 |
import tempfile
def serialize(figure: tempfile._TemporaryFileWrapper) -> bytes:
"""
Serialize a figure that has been rendered
Parameters
----------
figure
figure
"""
with open(figure.name, "rb") as f:
return f.read() | d8e10d2149bc25a53ebba7edf19213bd10997c8e | 101,071 |
import string
import random
def idGenerator(size=16, chars=string.digits + string.ascii_letters + string.digits):
"""
Generate random string of size "size" (defaults to 16)
"""
return ''.join(random.choice(chars) for _ in range(size)) | 4e4351d68d6276d168c8d02e5daf9826ed05672e | 101,075 |
from functools import reduce
def get_gpu_distribution(runs, available):
"""
Finds how to distribute the available runs to perform the given number of runs.
Parameters
----------
runs : int
number of reconstruction requested
available : list
list of available runs aligned with the GPU id list
Returns
-------
distributed : list
list of runs aligned with the GPU id list, the runs are equally distributed across the GPUs
"""
all_avail = reduce((lambda x,y: x+y), available)
distributed = [0] * len(available)
sum_distr = 0
while runs > sum_distr and all_avail > 0:
# balance distribution
for i in range(len(available)):
if available[i] > 0:
available[i] -= 1
all_avail -= 1
distributed[i] += 1
sum_distr += 1
if sum_distr == runs:
break
return distributed | 3b26f5bdb51fb28f7d99c21299d677de02c62305 | 101,081 |
def _read_lock_file(lockfile):
"""
Read the pid from a the lock file.
"""
lock = open(lockfile, 'r')
pid = lock.read()
lock.close()
return pid | 7d9d8583ed393839607acf95275f52e0ec260d7f | 101,082 |
import math
def get_distance(x1: int, y1: int, x2: int, y2: int) -> float:
"""
it returns the distance between two points
:param x1: int
:param y1: int
:param x2: int
:param y2: int
:return: float
"""
return math.sqrt(((x1 - x2) ** 2 + (y1 - y2) ** 2)) | ce3bb0cb85564205b83830b2532713938328c142 | 101,083 |
def to_base_2(x):
"""x is a positive integer. Returns a list that is x in base 2.
For instance, 22 becomes [1, 0, 1, 1, 0] and 0 becomes []"""
x = int(x)
result = []
while x > 0:
if x % 2:
result.append(1)
else:
result.append(0)
x = x // 2
result.reverse()
return result | 9215db8c2ad05cd44fd8b23636816c0f257f6502 | 101,088 |
def problem_errors(assignment) -> dict:
""" Takes an assignment object and returns a
dictionary of each of the problems in the
assignment and the number of errors all
students made on that problem.
"""
problems = {}
problem_number = 1
for problem in assignment.problems.all():
problems[problem_number] = len(problem.errors.all())
problem_number += 1
return problems | 26b0999796e5da00fb10a9b81392b6499a40be49 | 101,089 |
import math
def convert_degs_to_rads(deg):
"""convert degrees into radians"""
return deg * (math.pi / 180.0) | fade770d3b23449f763d6e6a57aaed2866dbff59 | 101,093 |
def get_track_terms(track_fn):
"""Returns list of track terms in the file"""
with open(track_fn, 'rb') as fin:
terms = fin.readlines()
terms = [term.strip().lower() for term in terms]
terms = list(set(terms))
return terms | 529720364521413a30a1f24323ff3101baa03563 | 101,095 |
def uniq(lst):
""" Take a sorted list and return a list with
duplicates removed. Also return the length of
the contracted list:
>>> uniq([1,3,7,7,8,9,9,9,10])
([1, 3, 7, 8, 9, 10], 6)
>>> uniq([1,1,1,1,1,1,1,1])
([1], 1)
>>> uniq([1,1,1,2,2,3,3,3])
([1, 2, 3], 3)
>>> uniq([1,3,7])
([1, 3, 7], 3)
"""
lst2 = lst[:]
last = lst2[0]
i=1
while i<len(lst2):
current = lst2[i]
if current == last:
del lst2[i]
else:
last = current
i+=1
return (lst2, len(lst2)) | e9fcb16e1bf105cd0141e0ae92eedec21d729bd6 | 101,097 |
import math
def getRotationMatrix(eulerAngles):
"""
From OpenCMISS-Zinc graphics_library.cpp, transposed.
:param eulerAngles: 3-component field of angles in radians, components:
1 = azimuth (about z)
2 = elevation (about rotated y)
3 = roll (about rotated x)
:return: 9-component rotation matrix varying fastest across, suitable for pre-multiplying [x, y, z].
"""
cos_azimuth = math.cos(eulerAngles[0])
sin_azimuth = math.sin(eulerAngles[0])
cos_elevation = math.cos(eulerAngles[1])
sin_elevation = math.sin(eulerAngles[1])
cos_roll = math.cos(eulerAngles[2])
sin_roll = math.sin(eulerAngles[2])
return [
cos_azimuth*cos_elevation,
cos_azimuth*sin_elevation*sin_roll - sin_azimuth*cos_roll,
cos_azimuth*sin_elevation*cos_roll + sin_azimuth*sin_roll,
sin_azimuth*cos_elevation,
sin_azimuth*sin_elevation*sin_roll + cos_azimuth*cos_roll,
sin_azimuth*sin_elevation*cos_roll - cos_azimuth*sin_roll,
-sin_elevation,
cos_elevation*sin_roll,
cos_elevation*cos_roll,
] | daee39fc5ce0d25cbbc1d8e928f1c6d6e5834f7f | 101,098 |
def get_top_row(listing):
"""
returns the top row of given listing's info
"""
top_row = listing.find('div', {'class':'_1tanv1h'}).text # _167gordg
top_row = top_row.split(' in ')
# what are we looking at?
what_it_is = top_row[0]
# where is it?
where_it_is = top_row[1]
return what_it_is, where_it_is | 45d21fc8e4f7701b218c926d4e5f5971b6499953 | 101,100 |
def input_list(size: int) -> list[int]:
"""
input_list:
Creates a list and aks user to fill it up.
Args:
size (int): Size of the list
Returns:
list: The list which has been created by the user.
"""
# creating an empty list
store: list[int] = []
# iterating till the range
for _ in range(0, size):
element = int(input())
# adding the element
store.append(element)
return store | b101e0f1d53da45a6bade6d41fad7e83a606085e | 101,102 |
def gimmeTHATcolumn(array,k):
"""Extracts the k-column of an 2D-array, returns list with those column-elements"""
helparray = []
for i in range(len(array)):
helparray.append(array[i][k])
return helparray | 49ab71be1cabe21ea80996ea60606b4c737104b3 | 101,104 |
import struct
def decode(arg_fmt, arg_fileHandler):
""" Using the struct module, read/decode a segment of binary data into a type indicated by the input format """
sfmt = struct.calcsize(arg_fmt)
return struct.unpack(arg_fmt, arg_fileHandler.readline(sfmt)) | e889153b2f9ef988d9842c6d85c0ab6c01db5f91 | 101,115 |
from pathlib import Path
def get_json_schema_path() -> str:
"""Return the path to the JSON schema."""
return str(Path(__file__).resolve().parent / "music.schema.json") | f8202616e2be775b0a893322f5f726c7444d9fd1 | 101,117 |
def set_time_resolution(datetime_obj, resolution):
"""Set the resolution of a python datetime object.
Args:
datetime_obj: A python datetime object.
resolution: A string indicating the required resolution.
Returns:
A datetime object truncated to *resolution*.
Examples:
.. code-block:: python
from typhon.utils.time import set_time_resolution, to_datetime
dt = to_datetime("2017-12-04 12:00:00")
# datetime.datetime(2017, 12, 4, 12, 0)
new_dt = set_time_resolution(dt, "day")
# datetime.datetime(2017, 12, 4, 0, 0)
new_dt = set_time_resolution(dt, "month")
# datetime.datetime(2017, 12, 1, 0, 0)
"""
if resolution == "year":
return set_time_resolution(datetime_obj, "day").replace(month=1, day=1)
elif resolution == "month":
return set_time_resolution(datetime_obj, "day").replace(day=1)
elif resolution == "day":
return datetime_obj.replace(hour=0, minute=0, second=0, microsecond=0)
elif resolution == "hour":
return datetime_obj.replace(minute=0, second=0, microsecond=0)
elif resolution == "minute":
return datetime_obj.replace(second=0, microsecond=0)
elif resolution == "second":
return datetime_obj.replace(microsecond=0)
elif resolution == "millisecond":
return datetime_obj.replace(
microsecond=int(datetime_obj.microsecond / 1000) * 1000
)
else:
raise ValueError("Cannot set resolution to '%s'!" % resolution) | 449d5ac691ea04ce2a19fb825743d081add5990c | 101,120 |
def comma_separated_positions(text):
"""
Start and end positions of comma separated text items.
Commas and trailing spaces should not be included.
>>> comma_separated_positions("ABC, 2,3")
[(0, 3), (5, 6), (7, 8)]
"""
chunks = []
start = 0
end = 0
for item in text.split(","):
space_increment = 1 if item[0] == " " else 0
start += space_increment # Is there a space after the comma to ignore? ", "
end += len(item.lstrip()) + space_increment
chunks.append((start, end))
start += len(item.lstrip()) + 1 # Plus comma
end = start
return chunks | 6203ac8839be7718742426474ec093cdce5b58c3 | 101,123 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.