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 == "... | 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))
ret... | 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.... | 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) *... | 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:]
... | 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
-------
li... | 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... | 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 La... | 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": lam... | 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... | 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)
retu... | 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,... | 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_r... | 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... | 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 file... | 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_ro... | 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']
... | 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 t... | 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 gi... | 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_byte... | 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 ) +... | 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:
... | 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 = []
f... | 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:
... | 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')
... | 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 No... | 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"})... | 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... | 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(segmen... | 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",\
... | 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... | 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... | 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 i... | 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... | 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():
... | 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",
... | 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 ... | 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_[... | 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 pose... | 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
... | 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_similarit... | 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): keyw... | 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
... | 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
... | 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}w... | 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
... | 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 datetim... | 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
... | 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 ... | 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.r... | 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(... | 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... | 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 m... | 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 wha... | 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... | 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:
.. ... | 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(","):
... | 6203ac8839be7718742426474ec093cdce5b58c3 | 101,123 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.