content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import subprocess
import os
def fetch_student(org, course, student, directory, token=None):
"""Fetch course repository for `student` from `org`
The repository will be cloned into a sub-directory in `directory`.
Returns the directory in which to find the students work.
"""
# use ssh if there is n... | 11bccb939f3e6197a55eaf848933a19e1ec21cd5 | 626,943 |
import re
def camel_to_underscore(camelcase):
"""
Convert a camelcased string to underscore_delimited (tweaked from this StackOverflow answer)
http://stackoverflow.com/questions/1175208/elegant-python-function-to-convert-camelcase-to-camel-case
"""
s1 = re.sub('(^/_)([A-Z][a-z]+)', r'\1_\2', camel... | d4a11003232f52c5e412cdebb759be63be402f2f | 626,944 |
import torch
def prepare_device(numberOfGpusToBeUsed):
"""
Function to setup GPU device if available.
The function gets the indices of the GPU devices that are used for DataParallel.
Parameters
----------
numberOfGpusToBeUsed : int
Number of GPUs to be used
... | 1ff00c41937421c6894dde80cb1145e443906156 | 626,945 |
def handles_url( url ):
"""
Does this storage driver handle this kind of URL?
"""
return ".s3.amazonaws.com" in url | e74d7365ffd07da6ba9c9988ea00432d28b99c1a | 626,946 |
def get_default_parameters():
"""
Get the default RADEX parameters as a dictionary, this largely serves as an example for the
input required for :func:`run`.
molfile can be a complete path to a collisional datafile in the LAMDA database format or one of the files
listed by :func:`list_data_files`.
... | 7c4f414a5c698c24ea6627a979df5d7323f8c5aa | 626,947 |
import os
def _indexes_to_secondary_files(gresources, genome_build):
"""Convert a list of genome indexes into a single file plus secondary files.
This ensures that all indices are staged together in a single directory.
"""
out = {}
for refname, val in gresources.items():
if isinstance(val... | 3866e00928585d8d8a014e5432b635063ae7f4a8 | 626,948 |
def after(node, values, positions, places=False):
"""
Returns the set of all nodes that are after the given node.
"""
n = node[positions["_n"]]
if places is not False:
try:
return [values[n + places]]
except IndexError:
return list()
sent_len = node[posit... | 45a5bfcac0d9d41902dd9c8231f976f1164cb03e | 626,949 |
def grep(pattern, filename):
"""Very simple grep that returns the first matching line in a file.
String matching only, does not do REs as currently implemented.
"""
try:
# for line in file
# if line matches pattern:
# return line
return next((L for L in open(filename) ... | 0804b7584618be4cde4f63b7331f6881cbb9c468 | 626,950 |
def analytic_convolution_gaussian(mu1,covar1,mu2,covar2):
"""
The analytic vconvolution of two Gaussians is simply the sum of the two mean vectors
and the two convariance matrixes
--- INPUT ---
mu1 The mean of the first gaussian
covar1 The covariance matrix of of the first gaussian... | dfb79017a71500704235f0a734b5589cd3d0fc2a | 626,952 |
def retrieve_fcd_snapshot(content, datastore, vdisk, snapshot):
"""
Retrieves the managed object for the fcd snapshot specified
Sample Usage:
retrieve_fcd_snapshot(content, datastore, vdisk, "Snapshot Name")
"""
# Set vStorageObjectManager
storage = content.vStorageObjectManager
# Ret... | d87fd6ba96c3ab1a753c5c7fc81d823d112b230d | 626,953 |
def remove_empty(dictionary):
"""Removes empty entries from a dictionary."""
for key in list(dictionary.keys()):
if dictionary.get(key) is None:
del dictionary[key]
return dictionary | 3b54f3fd97560ebead9ba32f44ea301e066a1440 | 626,954 |
def expand_columns(df, names, sep="_"):
"""
Expands a dataframe's columns into a multi-level index
Parameters
----------
df : pandas.DataFrame
names : list of string
The names for the new column levels.
sep : str (default = '_')
Character(s) on which the column labels will b... | 997753f21d8de153b8352f673a403160c7034ca9 | 626,955 |
def interactive_strategy(score, opponent_score):
""" Пример интерактивной стратегии """
print('Current score:', score, 'to', opponent_score)
while True:
response = input('How many dice will you roll? ')
try:
result = int(response)
except ValueError:
print('Ple... | b0ac7a36c74ac618d0e56a78cd68935a89ece521 | 626,956 |
import torch
def div_func(inputs: torch.Tensor, other: float, unsqueeze_dim: int = 1):
"""
Overview:
Divide ``inputs`` by ``other`` and unsqueeze if needed.
Arguments:
- inputs (:obj:`torch.Tensor`): the value to be unsqueezed and divided
- other (:obj:`float`): input would be divi... | 76fcea6458b713d164e1bc0ab9551b59bad3a2c0 | 626,957 |
def get_r_a():
"""床下の平面形状(アスペクト比等)を考慮した係数(無次元)
Args:
Returns:
float: 床下の平面形状(アスペクト比等)を考慮した係数(無次元)
"""
return 1.02 | 6d5872c32ccb4b607a3b6d23c8ec175faa934dcd | 626,958 |
import json
def read_json_file(path):
"""
Read an entire file in one go.
"""
with open(path) as f:
return json.load(f) | 3f81c6f03b3fac536947393173692fc31b42ac47 | 626,959 |
import yaml
import os
def load_config(filepath):
"""Return dictionary with settings and final CSV path"""
with open(filepath) as file:
config = yaml.full_load(file)
root_dir = config['dir']['root'] # project root
final_dir = config['dir']['final_data'] # final data dir from root
filename = config['project... | f19f88d19ba454ae9d9f6cddcf54f276a040b7b4 | 626,960 |
def compute_overall_annoyance(artifacted_blocks):
"""Calculating the total visibility of the image and return the values as int type."""
annoyance = 0
if len(artifacted_blocks) != 0:
for block in artifacted_blocks:
annoyance += block.annoyance
return annoyance / len(artifacted_bl... | 969094f2fd12f707a6835d4c9aa123027b8ee552 | 626,961 |
import copy
import math
def traverse(path, start, waypoint):
""" Traverse the given path, giving the final position """
current = copy.copy(start)
# do stuff
for action,dist in path:
if action == "N":
waypoint[1] += dist
elif action == "S":
waypoint[1] -= dist
... | ebee370d9d13f50549ef6bbffc529a9b47978f6f | 626,962 |
def parse_namefile_ini(line):
"""
Parse a line from a .ini file to get the described file location
Parameters
----------
line : str
Line from the .ini file, containing the location of a file
of interest.
Returns
-------
processed_line : str
... | 800f3551f37e40a2e9a9ca1d11695be4d1adfe77 | 626,963 |
def Tk_(xT): # pragma: no cover
"""
:param xT - temperature (C):
:return:
"""
return xT + 273.2 | b7234018c313d2dc9dacd083766f40a71d6f57b8 | 626,964 |
def cols_to_reduce_uniques(df, column_threshold_dict):
"""Reduce the number of unique values by creating a column of X values and the rest marked "Others".
Args:
column_threshold_dict:
df: Pandas DataFrame.
columns: Dictionary of column and threshold, i.e. {'col1' : 1000, 'col2' : 3000}... | 2e188a4e66c8186bafd4c2e07ea050a507160546 | 626,965 |
def get_version(cluster_id, version, client):
"""Requests a certain version of certain cluster."""
return client.get_cluster_version(str(cluster_id), version) | 68dbecf21d82dbcde39a6b8eb473ec7689da5049 | 626,966 |
import os
def create_or_fake_local_code(aiida_local_code_factory):
"""
Create or fake a local code.
This is old consider using mock-code_factory of aiida-testing instead
"""
def _get_code(executable, exec_relpath, entrypoint):
_exe_path = os.path.abspath(exec_relpath)
# if path ... | 93d54eff7c5db5cea61f9d7470a4b76123bd000a | 626,967 |
def normalize(vals):
"""normalize a series of values using min/max normalization"""
return (vals-vals.min())/(vals.max()-vals.min()) | 95288d79b4100a031c60dbd2eb03e20b9aff6490 | 626,968 |
def prepare_args(args):
"""
Prepare arguments to be used as the API expects it
:param args: demisto args
:return: transformed args
"""
args = dict((k.replace("-", "_"), v) for k, v in list(args.items()))
if "is_public" in args:
args["is_public"] = args["is_public"] == "True"
retu... | eaf0d7f7f30390d02481ff01e9eea4a7b3262ef2 | 626,969 |
def centre(images):
"""Mapping from {0, 1, ..., 255} to {-1, -1 + 1/127.5, ..., 1}."""
return images / 127.5 - 1 | 73ea422309ffc4c3b90d2f1798ce45e34cc035d1 | 626,971 |
def bounce_easeout(pos):
"""
Easing function for animations: Bounce Ease Out
"""
if pos < 4 / 11.0:
return (121 * pos * pos) / 16.0
if pos < 8 / 11.0:
return (363 / 40.0 * pos * pos) - (99 / 10.0 * pos) + (17 / 5.0)
if pos < 9 / 10.0:
return (4356 / 361.0 * pos * pos) - (... | 9974d6e57291350378bb10757397504755a2e17d | 626,972 |
def filter_traceback_list(tl):
"""
Returns the subset of `tl` that originates in creator-written files, as
opposed to those portions that come from Ren'Py itself.
"""
rv = [ ]
for t in tl:
filename = t[0]
if filename.endswith(".rpy") and not filename.replace("\\", "/").startswi... | 0fa40c64f8c423c5acebf34d0609f32338620808 | 626,973 |
def createDictOfWordCounts(myList):
""" Creates a sorted list of words containing the number of times each
word appeared.
"""
''' Testing:
(test 1)
>>>listOfWords = ['dog', 'cat', 'bird', 'dog', 'dog', 'cat']
>>>createDictOfWordCounts(listOfWords)
{'bird': 1, 'dog': 3... | b2a97f413f88a1588f89b2205c7c663ce1b5b448 | 626,974 |
def poly_eval_horner(coefs, x):
"""
Evaluates the polynomial whose coefficients are given in coefs on the value x
using the Horner's method. This function is much faster than regular polynomial evaluation.
Polynomial coefficient are stored in coefs from the lowest power to the highest.
x is required... | 4dd16ba8e73510b74a1d18e8a38dbe0ae0ac70d8 | 626,975 |
import os
import fnmatch
def find_files(path, pattern=None):
"""
Finds all files in the specified directory that match the specified
pattern.
:param path: Path to a directory to search for files in.
:param pattern: Pattern to match filenames against. Can be an iterable to
s... | c4cef79ac5ffd88866f6e033e1b3b83660660e45 | 626,976 |
from typing import List
def binary_search(lst: List[int], x: int) -> bool:
"""
Pre: A is a sorted list (non-decreasing order).
4 Post: Returns True if and only if x is in A.
"""
if lst == []:
return False
elif len(lst) == 1:
return lst[0] == x
else:
m = len(lst) /... | 42762460ee3b9d52f0abf14897769f6f37ccdaab | 626,977 |
import torch
def magic_box(x):
"""DiCE operation that saves computation graph inside tensor
See ``Implementation of DiCE'' section in the DiCE Paper for details
Args:
x (tensor): Input tensor
Returns:
1 (tensor): Tensor that has computation graph saved
References:
https://g... | 6fce807076e8f51c565e86af76956523e40caafa | 626,978 |
def serialize_results(results : dict) -> str:
"""Serialize a results dict into something usable in markdown."""
n_first_col = 20
ans = []
for k, v in results.items():
s = k + " "*(n_first_col-len(k))
s = s + f"| {v[0]*100:.1f} | {v[1]*100:.1f} |"
ans.append(s)
return "\n".j... | c64ba7bbf898e3085290615d163401b7c2382ca6 | 626,979 |
import math
def _get_new_lambda_candidate(lower_bound, upper_bound):
"""Update current lambda so that it lies within its bounds.
Args:
lambdas_new (namedtuple): Named tuple containing the current candidate
value for the damping factor lambda, its lower bound and upper bound.
Returns:... | 2170881516f01bbef770037de33beba7158ba77c | 626,981 |
def loadMovieLensTest(filename='u1.test'):
"""Load test data
"""
str1 = './ml-100k/'
movie_data = {}
for line in open(str1 + filename, 'r'):
(user, movieid, rating, ts) = line.split('\t')
movie_data.setdefault(user, {})
movie_data[user][movieid] = float(rating)
return m... | 890cb84c1f95f71d89a78e66bd5ee14c94f6f253 | 626,982 |
import pickle
import base64
def decode(something):
"""
Decodes from base-64 pickled object.
"""
return pickle.loads(base64.b64decode(something)) | dfaffa998e30d395afe3b7ae6a620b656ead585a | 626,984 |
def retreive_filename(path):
"""
Truncates absolute file directory and returns file name.
Parameters
----------
path : 1-dimensional string containing absolute directory of a file,
in /<dir>/<filename>.<foramt> format.
Returns
-------
filename : <filename> portion of the given file... | 0841fada4380280c6ac85fe617bca0d1b47a702c | 626,985 |
def get_element_attribute(element, attribute: str) -> str:
"""
Find a text in an XML element.
Args:
element (Element): XML element.
attribute (str): the attribute of the element.
"""
if attribute in element.attrib:
return element.attrib.get(attribute, "")
else:
... | c46cfaf894704b478738baedbebfd749c39c5922 | 626,986 |
def is_density_matrix(input):
"""Determine if the input array can be a density matrix.
Args:
input (array): input array.
Returns:
bool: whether input can be a density matrix.
"""
return input.shape[-1] == 2 and input.shape[-2] == 2 | 42608dc18a075279c66fae801fced6b118dfea14 | 626,987 |
import bz2
import pickle
def read_pickle(filepath, compressed=False):
""" Reads the summarized background from a compressed binary file
Parameters
----------
filepath:
Filepath to compressed file
compressed:
Whether to use bz2 compression. Defaults to False
"""
if compress... | b2fd35ed131f4dbedaaf9b8d3904291012b54b6f | 626,988 |
def ss_stat(vals, r, m=0):
"""Calculates sum-sum test statistic.
Use the sum-sum test statistic to determine whehter there is
significant support for the existence of DKs in dataset.
This is most effective for the multiple dispersed outliers case.
**Best for inward testing procedures.
Pros... | f489c36653236ae1e72e481527370e428fddc8be | 626,990 |
def test_step(x, model, estimator, **config):
"""Test the `model` given the mini-batch of observations `x` and the gradient estimator/evaluator `estimator`"""
loss, diagnostics, output = estimator(model, x, backward=False, **config)
return diagnostics | f1af20d3ecdcf9f9b7a2c4213fc51aa2b6660b0b | 626,992 |
def get_task_version(taskf):
"""return a version for a taskf.
This is wrapper around taskf.get_version() that will not raise
an exception if a tool is not installed but will return None
instead.
"""
try:
version = taskf().get_version()
except Exception as ex:
msg = str(ex)
... | cfafc774fa969a0eb3acad13f3acdf47b8de722e | 626,993 |
def as_bool(x):
"""
Returns True if the given string in lowercase equals "true",
False otherwise.
"""
return True if x.lower() == "true" else False | abb90349a44c8e8c433d7a360809624b47b1f66b | 626,994 |
def lengthOfLIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
dp = [1] * (len(nums) + 1)
for i in range(len(nums)):
for j in range(i):
if nums[j] < nums[i]:
# from j -> i dp[i]+1
dp[i] = max(dp[i], dp[j... | 21393395ddbc07ae26282cf0e1a6159b775cf2da | 626,995 |
from typing import Union
import re
import operator
def condition_matches(value: Union[int, float], format_: str) -> bool:
"""
Return true if the value matches the condition in the pattern.
"""
match = re.search(r"\[(>|>=|<|<=|=)(\d*(?:\.\d*)?)\]", format_)
if not match:
return True
op... | bd12e5ded2d01c9e6b99e89e7747d59dea1d9ac4 | 626,997 |
import yaml
import requests
import sys
import time
def check_repo_exist(added_repo):
"""
Check whether a repository exists
:param added_repo: target repository
:return: True/False if the repository exists/not exists
"""
with open('retry.yaml', 'r') as fp:
retry_conf = yaml.load(fp.read... | c36f907fd5bbb47331951902fd601d057c45e29b | 626,998 |
import argparse
def parse_arguments():
"""Parse given command line arguments."""
text_server = "MySQL server you want to connect to"
text_user = ("Username used for authentication with the MySQL"
"instance (default:root)")
text_database = "MySQL database you want to export data from"... | daa852f66c94c0bdc740a08f6777562675ed847b | 626,999 |
def update(ls, new_number):
"""
Given a tuple of original list and sorted list, add the new number to the
lists and drop the oldest number. Return the updated tuple. (they are also
updated by reference).
"""
(numbers, sorted_numbers) = ls
drop = numbers[0]
numbers = numbers[1:] + [new_number]
sorted_n... | 2b44fca8cc7074616093d80e38a32d3d8f3965a7 | 627,000 |
import random
def is_pause() -> bool:
"""Checks if the computer should pause typing for a while.
Similar to `is_typo()`, but is not based on any research.
The chances of taking a small pause has been determined
by testing different combinations of `is_pause()` and
`pause_time()`.
Returns:
... | a287682361921bf273ea0b61c0c60a77904afdf1 | 627,001 |
def size_color_unique_id(unique_id=999999999):
""" Return an interpolated color for a given byte size.
"""
#r1 = size[-3:]
#g1 = size[-6:-3]
#b1 = size[-9:-6]
red = (unique_id >> 16) & 0xff
green = (unique_id >> 8) & 0xff
blue = unique_id & 0xff
try:
red = int( floa... | fcd323195e40e05f20d24480744aaa1e501db54c | 627,002 |
def wrap(text, width):
"""
A word-wrap function that preserves existing line breaks. Expects that
existing line breaks are posix newlines.
Preserve all white space except added line breaks consume the space on
which they break the line.
Don't wrap long words, thus the output text may have line... | 4790fe4e837305a9ab49bc211b6cf4e9be3b5af9 | 627,003 |
def task2(a):
"""
Function that calculates square value of argument
Input: one integer
Output: one integer
"""
return a**2
#return iloczyn | 19afd47664de55e3bb23ed405e26fcfcbbab0fa3 | 627,004 |
import subprocess
def win_menu(clients, l=10):
"""
Displays a window menu using dmenu. Returns window id.
"""
dmenu = subprocess.Popen(['/usr/bin/dmenu','-i','-l', str(l)],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
menu_str = '\n'.join(sorted(clients.keys()))
# Pop... | e696eae65949f88d06c31ef9ae601d79e75f9f57 | 627,006 |
import re
def get_sentences(input_text):
"""Splits the input into sentences based on punctuation"""
sentences = []
tokens = re.split(r'([\.\!\?]+)', input_text) # Splits on and captures punctuation marks
for i, token in enumerate(tokens):
if i > 0 and re.match(r'([\.\!\?]+)', token): #... | babad89ac24c646d8dff133ceae81bef1f75e36f | 627,007 |
def bucopt(self, method="", nmode="", shift="", ldmulte="", rangekey="",
**kwargs):
"""Specifies buckling analysis options.
APDL Command: BUCOPT
Parameters
----------
method
Mode extraction method to be used for the buckling analysis:
LANB - Block Lanczos
SUBSP... | 0c1256711940b6511ff6a7e6a5aa9ab0b0d2d625 | 627,008 |
def hamming_distance(a, b):
"""
:param a: 圖片1的hash值
:param b: 圖片2的hash值
:return: 返回兩個圖片hash值的漢明距離
"""
hm_distance = bin(a ^ b).count('1')
# print(hm_distance)
return hm_distance | 74ca65ef4b77d7f5989259b25a02b06e3291e308 | 627,009 |
def getNthFromLast(head, n):
"""
Take two pointers one starting from head the other starting from the nth
node, so when the latter node reaches the end the former would have reached
the Lenth-n nodes
"""
ptr = head
c = 0
while ptr and c < n:
# We want the nptr to reach the l... | e80afde6f7e5ca9ec5011ac4a3a3bc3ff684ebca | 627,010 |
def compareNodes(node_1, node_2):
"""
Compares two nodes to check if they are equal
:param node_1: The first node to check
:type node_1: Node type
:param node_2: The second node to check
:type node_2: Node type
:returns: True or False
:rtype: Boo... | 2b7c1d2d748cd4732eff1fd7677c10fc1fff2bd4 | 627,011 |
def function_to_decorate(path):
""" For use in TestCheckPathIsValidDecorator unit tests"""
return path | 32d897a0ba415eb0c2e18c68f6e4df5a52e2a332 | 627,012 |
def normalise(src_array):
"""
Normalise srcArray from 0 to 1
"""
out_array = src_array.copy()
out_array -= out_array.min()
out_array /= out_array.max()
return out_array | 4227a0aaf6163cad93c77d44d3e4aa955f3aac33 | 627,013 |
from datetime import datetime
def now() -> datetime:
"""Return the datetime object of the current time.
:return: datetime object represeting current time
"""
return datetime.now().astimezone() | e1ca72a8cf22b1614a406a3d44148fb509d262a8 | 627,014 |
def jarManifest(target, source, env, for_signature):
"""Look in sources for a manifest file, if any."""
for src in source:
contents = src.get_text_contents()
if contents[:16] == "Manifest-Version":
return src
return '' | 83bdb3cd01e83f3ba949e2a9faa11f8c98d1589a | 627,015 |
def correct_time_dilation(df):
"""Short summary.
Parameters
----------
df : Pandas DataFrame
The dataframe containing the photometry of all events.
Returns
-------
Pandas DataFrame
The same dataframe with undilated times.
"""
for idx, row in df.iterrows():
... | b7aae7a26279d5629a367cf49e898a5543981dd9 | 627,016 |
import os
def get_cloudlogbase_config() -> str:
"""Returns the log definition config file
To be passed into the initialisation of spine-aws-common classes to provide
log message definitions"""
cwd: str = os.path.dirname(__file__)
return os.path.join(cwd, "list_reconciliation_logs.cfg") | 4b0e6d0ce66dbcf865beccdfd4d158316e1dc968 | 627,018 |
def _GetLowerBoundBuildNumber(
lower_bound_build_number,
upper_bound_build_number,
# The default window is the number of builds
# Findit will look back for an analysis.
default_build_number_window_size=500):
"""Determines the lowest bound build number relative to an upper bound.
Args:
lower... | 4d148de8dcae8123feb8095871f6a1f622694d25 | 627,019 |
def get_related_fields(model):
"""
Returns all the fields of `model` that hold the link between referencing objects
and the referenced object (`model`).
:param model: orphaned model class
:returns: list of fields of `model` that hold references via dependent objects
"""
return [
f f... | b5abe1e4bf4e0ada8cf60d113fb472d59f67b98b | 627,021 |
def weekend_integration_1_SS_idx_rule(M):
"""
The index for type 1 weekend-tour type integration constraints is
(day, week, window, tour type).
:param M: Model
:return: Constraint index rule
"""
return [(j, w, i, t) for j in M.DAYS
for w in M.WEEKS
for i in M.WINDOW... | 4b0e1e8c64097592fdf43ae9bc43ac547c0eebde | 627,022 |
def cmp(x, y):
"""
The 3-way comparison function as a pseudo-global.
x < y --> returns a negative number
x == y --> returns 0
x > y --> returns a positive number
Though not officially part of the ordinal API,
it is so important for performance here
that we justify making it publicly a... | e22df37e38afad45632a2e199049f0b1b4aac1a7 | 627,023 |
def convertir_yiq_a_ycbcr(y,i,q):
"""
Parameters
----------
y,i,q:float
valores del espacio de color YIQ
Returns
-------
y,cb,cr:float
valores del espacio de color YCbCr
"""
#Se hace aqui la conversión intermedia
r = y+0.955*i+0.618*q
v = y-0.271*i-0.645*q
a = y-1.11*i+1.7*q
#... | 07bc950dfacbb70c7df6275977c201fdb139e17a | 627,024 |
import yaml
def load_config(filename: str) -> dict:
"""
Load a configuration file as YAML
"""
with open(filename) as fh:
config = yaml.safe_load(fh)
return config | da7f02c638f1ccb684b39d3b2b24d7e4e8587f08 | 627,025 |
import torch
from typing import Tuple
def normalize_sizes(y_pred: torch.Tensor, y_true: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""Normalize tensor sizes
Args:
y_pred (torch.Tensor): the output of the model
If a 3-dimensional tensor, reshapes to a matrix
y_true (torch.... | 13d551034f96a84f2215a92f60f2a7649c906bee | 627,026 |
import argparse
def build_parser():
"""
Builds the parser for reading the command line arguments
:return: Argument parser
"""
parser = argparse.ArgumentParser(description='Print one or multiple bag keys')
parser.add_argument('-b', '--bag', help='Bag file to read',
required=True, type=str)
... | 76814c3ee11b5526e8ba84ffd6365885a2e86b8b | 627,027 |
import math
def cos_anneal(e0, e1, t0, t1, e):
""" ramp from (e0, t0) -> (e1, t1) through a cosine schedule based on e \in [e0, e1] """
alpha = max(0, min(1, (e - e0) / (e1 - e0))) # what fraction of the way through are we
alpha = 1.0 - math.cos(alpha * math.pi/2) # warp through cosine
t = alpha * t1 ... | e6f1eee3b35e6b85d4dc301e6aa8b63b180c407e | 627,028 |
def aggregate_actions_and_lengths(actions_per_frame):
"""Identify the actions in a video and count how many frames they last for.
Given a list of actions (e.g. ['a', 'a', 'a', 'b', 'b']) summarise the actions and count their lifespan. For
the example input just given, the function returns (['a', 'b'], [3, ... | d0c433957e30cbafc5b24c38ce6b5df7696378e8 | 627,029 |
def get_cap(assets):
"""
Converts assets into corresponding market capitalization category.
Returns the market capitalization category based on the provided net assets
or market capitalization value.
Parameters
----------
assets : int
Net Assets of mutual funds or Exchange Traded F... | ef5f8b5ab5c3aec75d19fc72bb410d4bc1570d3a | 627,032 |
def find_complement(dna):
"""
:param dna: str, DNA consequence provided by user to be compared
:return: str, complement DNA consequence for given DNA consequence
"""
complement = ''
for i in range(len(dna)):
ch = dna[i]
if ch == 'A':
complement += 'T'
elif ch... | 4b1a03fb997c4a642622a56cf68ea8d6eb38bcef | 627,034 |
from functools import reduce
def make_table(grid):
"""
Borrowed from http://stackoverflow.com/a/12539081/5088990
:param grid: List of lists
:return:
"""
def _table_div(num_cols, col_width, header_flag):
if header_flag == 1:
return num_cols * ('+' + (col_width) * '=') + '+\... | 1d1748bf298cf72ab7384639e2fc22b5b8261ea0 | 627,035 |
def get_name_from_attributes(variant):
"""Generates ProductVariant's name based on its attributes."""
values = [
attributechoice_value.title
for attributechoice_value in variant.attribute_map.values()
]
return " / ".join(values) | f6bf117fb38b05d2a08eae4ce178e19381ebcdeb | 627,036 |
import operator
import pkgutil
def _get_modules_names(package):
"""Get names of modules in package"""
return sorted(
map(operator.itemgetter(1),
pkgutil.walk_packages(package.__path__,
'{0}.'.format(package.__name__)))) | c81066f5d35da3474a4e1790db3ba64ada9f688f | 627,037 |
def insert_sort(input_list):
"""Insert sort function."""
if isinstance(input_list, list):
for i in range(len(input_list) - 1):
for j in range(i + 1, 0, -1):
if input_list[j] < input_list[j - 1]:
temp = input_list[j]
input_list[j] = inpu... | 7f8d2ec558cda16de3043d4d42144abed6305a01 | 627,038 |
from functools import reduce
from operator import add
def fitness(individual, target):
"""
Calculutes the fitness of an individual, lower is better
:param individual: individual to calculate fitness
:param target: the target value to achieve
"""
result = reduce(add, individual, 0)
return a... | 4bb7e0bbefad871879cb2d5109f675b437d99f9c | 627,039 |
import sys
def append_results(a, results, result_column):
"""
Used exclusively by get_column
Parameters
-----------
a: parameter from get_column
results:
result_column: parameter from from get_column
Returns
--------
append results to output in get_column
"""
if type... | 6ed9e7916df438b176ab759ba8c0b07cf96506ba | 627,040 |
import sys
import site
import os
def binaries_directory():
"""Return the installation directory, or None"""
if '--user' in sys.argv:
paths = (site.getusersitepackages(),)
else:
py_version = '%s.%s' % (sys.version_info[0], sys.version_info[1])
paths = (s % (py_version) for s in (
... | cc491d23e118b3cd89a727a496092e15a9ec4e15 | 627,041 |
import re
def natkey(element):
"""Help natsorted compare elements by splitting elements into tuples
containing strings and numbers
"""
def intize(e):
try:
return int(e)
except ValueError:
return e
return [intize(e)
for e in re.split('([?!0-9... | acf958f79d85d907582a27696e1850a183b2b1e7 | 627,043 |
import re
def isprintascii(value):
"""
Return whether or not given value contains printable ASCII chars only. Empty string is valid.
If the value contains printable ASCII chars only, this function returns ``True``, otherwise ``False``.
Examples::
>>> isprintascii('1234abcDEF')
True
... | 1bcc755a0169d6427bf6bde4bfe6658ce4fa3189 | 627,044 |
def transform_to_bool(value):
"""
Transforms a certain set of values to True or False.
True can be represented by '1', 'True' and 'true.'
False can be represented by '1', 'False' and 'false.'
Any other representation will be rejected.
"""
if value in ['1', 'true', 'True']:
return Tr... | dd648d94be143ee9e896097851ce35bb3bfd0c3b | 627,045 |
import json
def _get_options(options_file=None):
""" Read in options_file as JSON.
:param options_file: filename to return
:type options_file: str
:return: options as dictionary
:rtype: dict
"""
if options_file is not None:
with open(options_file, 'r') as opt_fil... | 9011175e8583541982f761a9f60375a0bdca88c1 | 627,046 |
import re
def clean_jsonp_callback(callback):
""" Returns JSONP callback function name or None.
Callback function names can contain alphanumeric characters as well
as periods (.) and brackets ([ and ]), allowing names like "one.two[3]".
"""
callback = re.sub('[^a-zA-Z0-9\._\[\]]', '', callback)
... | 361603e3eb8a29f285d8ce97ec4a1c1a030d6c56 | 627,047 |
def type_compliance(variable, *args):
""" Private: internal library function, not intended for public use. """
return_list = []
for arg in args:
if isinstance(variable, arg):
return_list.append(True)
else:
return_list.append(False)
return True if True in return_li... | fa80d9bebdbab5f368c6b77c690718e5e0774e90 | 627,048 |
def get_bowtie2_index_files(base_index_name):
""" This function returns a list of all of the files necessary for a Bowtie2 index
that was created with the given base_index_name.
Args:
base_index_name (string): the path and base name used to create the bowtie2 index
Returns:
... | 534d8c1a442571a441f37fb943898b53a4fce706 | 627,049 |
def order_heuristic(mgr, var_priority = None):
"""
Most signifiant bits are ordered first in BDD.
var_priority is a list of variable names. Resolves ties if two bits, are of the same priority, it resolves based.
e.g. var_priority = ['x','y','z'] would impose an order ['x_0', 'y_0', 'z_0']
"""
... | 55c8beebddf49dde574f65530b88453dfa2fb60a | 627,050 |
def scale(n, float_round=None):
"""
High-order function to scale result to arbitrary value.
f = scale(10)
f(5) -> 50
if float_round
f = scale(0.1, 2)
f(10) -> 10.2
:param n: Scaling factor
:param float_round: Number of decimal places
:return: Callable, performing scaling
:r... | 9c2cefd79d81476fba07bc3e8057fe5b4f2cce82 | 627,051 |
from typing import List
def create_readable_data(data: List[int]) -> List[list]:
"""Create a program readable sudoku puzzle given a list of numbers
=== Attributes ===
data: a list of numbers containing sudoku puzzle
=== Returns ===
a readable sudoku puzzle
"""
result = [[data[col + 9 * r... | 152fe696ac81f5822ed4d2a76862a623959bb8a2 | 627,052 |
from typing import List
from typing import Any
from typing import Callable
from typing import Set
def dagroots(sorted_nodes:List[Any],
inbounds:Callable[[Any],Set[Any]])->Set[Any]:
""" Return a set of root nodes of a DAG. DAG should be topologically sorted.
"""
nonroots=set()
acc=set()
for node... | b1c618824cea5c1b438b9d70f5e1c971efebb8ed | 627,053 |
import functools
import numpy
import unittest
def for_dtypes(dtypes, name='dtype'):
"""Decorator for parameterized dtype test.
Args:
dtypes(list of dtypes): dtypes to be tested.
name(str): Argument name to which specified dtypes are passed.
This decorator adds a keyword argument specif... | f35285b8dbee51982274dd02c5c5c8ebbdf1dc95 | 627,056 |
def get_wordlist(filepath):
"""Read all words from a file and return them as a list"""
with open(filepath, 'r') as f:
return [
l for l in (l.strip() for l in f.readlines())
if l and l[0] not in ';#'] | ce750cb835253ab536915fe7eb9051152c74b480 | 627,057 |
def paste_sampled_transform(buildState):
"""
APPLIES: IMAGE
Erase mask pixels that intersect the change mask if the purpose is remove, indicating
that the change represented by those mask pixels is no longer visible.
Please note that the paste sample operation has its own mask and probe, thus al... | 735d223e96bb3aa8b59105ee775945362c7e55df | 627,058 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.