content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def non_async_test_task():
"""
This is a mock task used to test that creating a task without using create_async_task does not result
in a Task object being created or updated.
"""
return 42 | c873b50eef4be06f902b0a79b988563b6cd68d70 | 649,019 |
def format_number(num: float) -> str:
"""
Format strings at limited precision
:param num: anything that can print as a float.
:return: str
I've read articles that recommend no more than four digits before and two digits
after the decimal point to ensure good svg rendering. I'm being generous a... | 26bb37ab8b417a44c53c2b1c3b14961075472d0c | 649,020 |
def compare_filenames(file_list1, file_list2):
"""
Compare elements in 2 lists.
:param file_list1:
:param file_list2:
:return:
"""
return set(file_list1).difference(file_list2) | f5d55616edf9a0fd57246796cdb7e0861e9b8709 | 649,021 |
def get_attribute_values(elements,name):
""" returns a list of attributes 'name' from a list of elements """
attribute_values = []
for element in elements:
attributes = element.attributes
for n in range(attributes.length):
attribute = attributes.item(n)
if attribute.n... | 953ae221b0dd88812fc9b59e5dc86add9d9ededb | 649,022 |
def _get_request(context):
"""
Fetch the request from the context.
This enforces the use of the template :class:`~django.template.RequestContext`,
and provides meaningful errors if this is omitted.
"""
assert 'request' in context, "The fluent_pages_tags library requires a 'request' object in the... | f710014c47e32bafc06ec4da20284f1c04e4862b | 649,023 |
def vals_are_multiples(num, vals, digits=4):
"""decide whether every value in 'vals' is a multiple of 'num'
(vals can be a single float or a list of them)
Note, 'digits' can be used to specify the number of digits of accuracy
in the test to see if a ratio is integral. For example:
... | 3ffc25020c87c41a1b2d678b71081d73d7613874 | 649,024 |
import os
def within_docker() -> bool:
"""Detect I'm in a Docker or not."""
return os.path.exists("/.dockerenv") or os.getenv("CI") == "1" | d0b30d8e0319044434752971dcd22500cd62b35a | 649,025 |
def skyblock_auctions_ended():
"""
Returns SkyBlock auctions which ended in the last 60 seconds (More precisely,
whatever time is defined in the "Cache-Control" header of the response).
Parameters: (None)
Example Response:
```json
{
"success": true,
"lastUpdated": 1607456... | cf581478616161472cc51419827e2604acdd0630 | 649,026 |
import re
def match(frag, s, exact):
"""Match a search string frag with string s.
This is how we match document titles/names.
"""
if not exact:
return re.search(frag, s, re.IGNORECASE)
return re.match(f"^{frag}$", s) | ab0b58607437acd43d46cf86ecb92294c857d541 | 649,027 |
def createDic(data):
"""
列表生成集合
"""
data_set = []
for k in data:
for v in k:
if [v] not in data_set:
data_set.append([v])
data_set.sort()
return map(frozenset, data_set) | fd0fabb2bdf53ac450a06d3d8f7fa925ee192c43 | 649,028 |
def parse_callback(callback, reduce=True):
"""
Parses callbacks for CellRenderers: it splits the
callback from its arguments if present. Additionally this method will
not create singleton argument lists, but pass them as a single argument.
Returns the callback and its argu... | b925a0e82ee8046e48594fb6f8a99a5aaa017ded | 649,029 |
def _ComputeIpv4NumHosts(network_size):
"""Derives the number of hosts in an IPv4 network from the size.
"""
return 2 ** (32 - network_size) | 64733cc341f5eb0772a7d2df1753f6f67ac3f7f8 | 649,030 |
import os
def is_in_dir(filepath, directory):
"""Returns true if `filepath` is in `directory`."""
path = os.path.abspath(filepath)
# Make 'directory' end with '/' (os.sep) to detect that '/a/foo.py' is not in '/a/f' etc.
directory = os.path.join(os.path.abspath(directory), "")
return os.path.commo... | 58dfa6c05c82fd37b9abb811f0d6cf5e6326ec2e | 649,031 |
def linear(u, v, d):
"""
Linear interpolation.
Args:
u (float)
v (float)
d (float): the relative distance between the two to return.
Returns:
float. The interpolated value.
"""
return u + d*(v-u) | ab92ed03b61ac902dcec1630b41dd317b11efc3a | 649,032 |
def _merge_tokens(token_1: str, token_2: str) -> str:
"""Fast, whitespace safe merging of tokens."""
if len(token_2) == 0:
text = token_1
elif len(token_1) == 0:
text = token_2
else:
text = token_1 + " " + token_2
return text | ff8bd1bef06e39b55545dc784022cd19a935ee17 | 649,033 |
import pickle
def read_pickle(filename):
""" Function that reads pickled data and returns it in memory
INPUTS:
filename (str): name of pickle file to be read
OUTPUTS:
unserialized_data (?): data read from pickle file, can be nearly any form
"""
with open(filename, 'rb') as handle:
unserialized_data ... | 9ad5b81f5217ac4e4a205d71027bc50919fa47d4 | 649,034 |
def str_to_bytes(string):
"""Encode a string in bytes."""
return string.encode("utf-8") | 04b62d54b59dceadcda9b137e08f327ec7805170 | 649,035 |
def in_polygon(x, y, vertices):
"""
Determine if a point (x,y) is inside a polygon with given vertices
Ref: https://www.eecs.umich.edu/courses/eecs380/HANDOUTS/PROJ2/InsidePoly.html
"""
n_pts = len(vertices)
i = 0
j = n_pts - 1
c = False
while i < n_pts:
if (
# ... | d0250dc1bf43f5f3a40323565a6b9f47b3d98c66 | 649,036 |
import base64
def bytes_to_b64str(data_bytes) -> str:
"""Convert binary to base64-encoded string."""
encoded_bytes = base64.b64encode(data_bytes)
return encoded_bytes.decode("ascii") | 64d098db96391a9749d36f9953b9e9b4b00750c6 | 649,037 |
def get_raw_star_directory(path4starfiles, scene, shutters, noise, redo=True):
"""
This function returns a list of the directories (positions 1 and 2) to be studied.
# Paths to Scenes 1 and 2 local directories: /Users/pena/Documents/AptanaStudio3/NIRSpec/TargetAcquisition/PFforMaria
path_scene1_slow = "... | fd43ded950bf82a3a5c50f447510e9f9d9ca0672 | 649,038 |
def calc_pident_ignore_gaps(a, b):
"""
calculate percent identity
"""
m = 0 # matches
mm = 0 # mismatches
for A, B in zip(list(a), list(b)):
if A == '-' or A == '.' or B == '-' or B == '.':
continue
if A == B:
m += 1
else:
mm += 1
t... | 5d0c26f893b6ab27816a32d752231ac80cdb1826 | 649,039 |
def lr3(step: int, base_lr: float) -> float:
"""Stronger aggression lr scheduler."""
lr = base_lr
_lr = lr * 0.9 ** (step // 25)
return max(_lr, lr * 1e-3) | 3cb233164f86b7ff93afb9eca290e83416d70dd8 | 649,040 |
def split_data(data):
"""
Front function to split the data into train/test/validation/others
Args:
data (pd.DataFrame): a pandas dataframe with the data filtered to split
whatever
Returns:
splits (list): a list of pandas dataframe with elements such as:
... | f8700078d4fc117be7075000e7159cdcc6b74640 | 649,042 |
def prepare(data):
"""Restructure/prepare data about merges for output."""
sha = data.get("sha")
commit = data.get("commit")
message = commit.get("message")
tree = commit.get("tree")
tree_sha = tree.get("sha")
return {"message": message, "sha": sha, "tree": {"sha": tree_sha}} | ec5d5a2e6ee5613e0970716083f341d503b95db9 | 649,044 |
import subprocess
def m3c2(commande,params_folder,params_file):
"""
Commande CC pour executer le plugin M3C2
filenames: Names of the LiDAR point clouds used
"""
commande+=" -M3C2 "+params_folder+params_file + " -save_clouds "
subprocess.call(commande)
return True | e097cbe3940a44ceae4f91ad0eb9487268b7b0e4 | 649,045 |
def deserialize(node):
""" Returns an ast instance from an expanded dict. """
if isinstance(node, tuple):
klass, kws = node
return klass(**deserialize(kws))
elif isinstance(node, dict):
d = {}
for k, v in node.items():
d[k] = deserialize(v)
return d
el... | 36010b3dd45b9bd826de49ce6234c34c0df33c6a | 649,046 |
import os
def xform_file(root, buildsub, filename):
"""
Try to find the absolute path of filename by replacing buildsub with root,
or ../.. with root. If the resulting filename is an actual file, return the
new filename. Otherwise, return the original
"""
newFilename = filename.replace(buildsu... | aaf47b4ef256962b6a9dbd460dc94846546880bb | 649,047 |
import collections
def make_counter(pages, func, key):
"""Constructor de contador genérico."""
subgroups = collections.defaultdict(list)
for p in pages:
key_value = key(p)
if key_value:
subgroups[key_value].append(p)
return collections.Counter({k: func(v) for k, v in subgro... | 6c0fdaf10136f93516f46c23ab79fc096d1a7340 | 649,048 |
import random
def _computer_LX(img_w: int, video_w: int) -> int:
"""
通过图片宽度和视频宽度计算水印的起始x轴位置
:param img_w: 图片宽度
:param video_w: 视频宽度
:return: 水印起始x轴位置
"""
LX_low = 30 if img_w + 30 <= video_w else 0
LX_high = 100 if img_w + 100 <= video_w else \
((video_w - img_w) // 4)
if L... | 661f803ba3fa4fd79747f9d6cc15868d768c982b | 649,049 |
def lin_func_2(pars, xvals):
"""Return quadratic function of the form pars[0]*x + pars[1]*x*x"""
return pars[0]*xvals + pars[1]*xvals*xvals | c8d91302a3f542a46fffc5b5b92dc4646215d6cf | 649,050 |
import random
def random_bdays(n):
"""
Returns a list of integers between 1 and 365, with length (n)
"""
t = []
for i in range(n):
bday = random.randint(1, 365)
t.append(bday)
return t | 682b4a1928f3199772b608267bd236670295ef31 | 649,051 |
def create_new_products(user_data, prod_data, range):
"""
Special pre-processing for the YelpNYC since there is no new products (#reviews<5)
:param range: the range of products to be processed
"""
product_list = [(product, len(user)) for (product, user) in prod_data.items()]
sorted_product_list = sorted(product_... | c82c7bfc40a4335241f86b6036503a8830e9c1fc | 649,052 |
def get_category(output, categories):
"""
Return the most probable category/language
from output tensor.
"""
top_n, top_i = output.data.topk(1)
category_i = top_i[0][0]
return categories[category_i], category_i | d3ac9534f2b92ba43ab33c446017015665376609 | 649,053 |
def len_str_list(lis):
"""returns sum of lengths of strings in list()"""
res = 0
for x in lis:
res += len(x)
return res | 789d670b0bbf0dd5ee270e2d00c0047eba3f8b7e | 649,055 |
def available_exceptions():
"""
Purpose:
Available Exceptions That Can Be Generated
Args:
N/A
Return:
available_exceptions (Pytest Fixture (Dict of Exceptions)): Available
Exceptions That Can Be Generated
"""
return {
"ZeroDivisionError": ZeroDivision... | 6739ac6c505e472bf4ca1d1b3e88fc18abbfaea4 | 649,056 |
def remove_redundant_data(df):
"""
This function reduces the size of a dataframe by reducing blocks of
sequential identical data lines greater than 2 to only the earliest
and latest.
:param df: pandas dataframe
:type df: pandas dataframe
:returns: a smaller pandas dataframe
"""
dele... | 8bbe1c585a35417588633d2a48b54feecd8c11bb | 649,057 |
import os
def is_in_unittest():
"""return whether currently in unittest mode"""
return os.getenv('IN_UKNOW_TEST') is not None | a006aba03a19acd916c36b491a51a10e8ceaab29 | 649,058 |
def safe_get_key(dictionary, keys, default):
"""
Examples
--------
>>> d = dict(a=2, b=2, c=dict(d=12, e=45, f=dict(g=32)))
>>> safe_get_key(d, 'a', 1)
2
>>> safe_get_key(d, ['a'], 1)
2
>>> safe_get_key(d, ['asdf'], 1)
1
>>> safe_get_key(d, ['c', 'f', 'g'], 1)
32
>>> ... | 981f882e7aed3bf7643b1cb1335ddca7fc98bc16 | 649,059 |
def create_partitions(aut, partition_list, state_function, obs_events):
"""
Compute the fixed point of the partioning.
@param aut: Automaton being partioned.
@type aut: L{BaseAutomaton}
@param partition_list: Initial state partitions.
@type partition_list: C{list} of C{set} of L{State}
... | a762729601b07bcb433127205fd225904a132b74 | 649,061 |
def load_dataset(path_dataset):
"""Load dataset into memory from text file"""
dataset = []
with open(path_dataset) as f:
words, tags = [], []
# Each line of the file corresponds to one word and tag
for line in f:
if line != '\n':
line = line.strip('\n')
... | af028bd6ad31887a0ec86767720b0f09d55b0604 | 649,062 |
def _denormalize_to_coco_bbox(bbox, height, width):
"""Denormalize bounding box.
Args:
bbox: numpy.array[float]. Normalized bounding box. Format: ['ymin', 'xmin',
'ymax', 'xmax'].
height: int. image height.
width: int. image width.
Returns:
[x, y, width, height]
"""
y1, x1, y2, x2 = bb... | 49545db2914dd52657eceb4dcd94207f29050ae8 | 649,063 |
def findSmallest(arr):
"""[查找最小元素]
Args:
arr ([list]): [数组]
Returns:
[int]: [index]
"""
smallest=arr[0]
smallestIndex=0
for i in range(len(arr)):
if(smallest>arr[i]):
smallest=arr[i]
smallestIndex=i
return smallestIndex | 58e94da03d23bd7f0b16fed332dc67529a69f77c | 649,064 |
def is_instance(list_or_dict) -> list:
"""Converts dictionary to list"""
if isinstance(list_or_dict, list):
make_list = list_or_dict
else:
make_list = [list_or_dict]
return make_list | ebc210367b71f8a14f72270b373b3a95decda189 | 649,065 |
def health() -> dict:
"""Health Check for the server.
Returns:
dict:
Health status in a dictionary.
"""
return {'Message': 'Healthy'} | 90a8184b6d689d236dbfe7c50f33c8de10411222 | 649,066 |
def random_function():
"""Never can't be sure that function is not random"""
return 9 | b34d06e9a9c430948d59a63d74500a3385231ce5 | 649,067 |
def _parse_redis_connection(connection):
"""
Parse redis connection to host, db
:param connection: redis connection
:return: host, db
"""
connection_kwargs = connection.connection_pool.connection_kwargs
return (
connection_kwargs.get('host', 'local'),
connection_kwargs.get('p... | 171e2eeeb9eb9e2ec9719a16d4dec68ac4ba9ef1 | 649,068 |
def get_region_rrn_node_map(nodes):
"""Get regional reference node for each region"""
return nodes.loc[nodes['RRN'] == 1, 'NEM_REGION'].reset_index().set_index('NEM_REGION')['NODE_ID'].to_dict() | 70bb1c11ec86e7d8e6ac31d65958a2aa3b630cea | 649,069 |
from typing import Iterable
from typing import List
def _fmt(a: Iterable) -> List[str]:
"""Formats each element in `a` into strings.
Args:
a (Iterable): Iterable.
Returns:
List[str]: Returns a list with the formatted elements.
"""
return list(map(lambda a: f'{a:.3f}', a)) | 59add8462a3e41faecfcc5e0abcbc122ff669e05 | 649,070 |
import re
def parse(query):
"""This function parse all clauses of the query."""
# SQL keywords
keywords = [
"SELECT ",
"DELETE ",
"INSERT INTO ",
"CREATE TABLE ",
"UPDATE ",
"FROM ",
"INNER ",
"LEFT ",
"OUTER ",
"CROSS ",... | 7208186887365456a6563d6412e01742458ab163 | 649,072 |
def union_coverage(prev_cov, next_cov):
"""
Total coverage of the pattern by merging both the coverages
See http://imgur.com/fJokqsU
:param prev_cov:
:param next_cov:
:return:
"""
new_min = prev_cov.MinCov + next_cov.MinCov - min(prev_cov.MaxCov, next_cov.MaxCov)
new_max = prev_cov.M... | 4135b0f65447a16d9d3067755dd654de5a89780c | 649,073 |
def subset_data(data, col):
"""
Creates list of categories for column used to populate
dropdown menus
:param data: pd.DataFrame
generated from app_wrangling.call_boardgame_data()
:param col: string, column generate list for
:return list(exp_series.unique()): list of strings
"""
... | 718292c77bc35af33164c6176ec065df4f01dc32 | 649,074 |
def lines_to_list(infile):
""" put all words in a file into a list """
nested_list = [line.split() for line in infile]
# nested_list = []
# for line in infile:
# nested_list.append(line.split())
flat_list = [item for inner_list in nested_list for item in inner_list]
# flat_list = []
... | 1398bd382a29f7187773074fa08b8e14b2b31f9e | 649,075 |
def snakeToCamel(name):
"""变量名风格转换,首字母小写"""
words = name.split('_')
return words[0] + ''.join(word.title() for word in words[1:]) | c6804d12e83ea1534aab2720bffddc70f8d8ff38 | 649,076 |
def _1(value):
"""
Integer decoder.
```python
>>> from Tyf import decoders
>>> decoders._1((1, ))
1
>>> decoders._1((1.0, "6", 0b111))
(1, 6, 7)
```
"""
return int(value[0]) if len(value) == 1 else tuple(int(v) for v in value) | a2882998bce36cbb6e7a258bb469944d4bd46f99 | 649,077 |
def test_op(x, y, z):
"""A fake op for testing dispatch of Python ops."""
return x + (2 * y) + (3 * z) | 8050947a02a3a151dddf987821d97d1fd87122b3 | 649,078 |
import math
def MakeIndex(k):
"""
###########################################################################
Generate the index just for k.
###########################################################################
"""
index = [0, int(math.pow(4, k))]
return index | bc3069e21b5722593f7e8843686c82217422ec88 | 649,079 |
import os
def get_name_from_path(path: str, exclude_ext=True) -> str:
"""
>>> get_name_from_path("~/home/test/bla/hallo.md")
'hallo'
>>> get_name_from_path("~/home/Google Drive/Brain 1.0", False)
'Brain 1.0'
"""
base = os.path.basename(path)
if exclude_ext:
split = os.path.spl... | 252b5ea37447fd20f365d81a537973454dac0732 | 649,080 |
def _convert_to_ts(df, country=None):
"""
convert the original clean dataframe to a time series
by aggregating over each day for the given country
"""
## define the columns to group
if country:
cols = ["invoice_date", "country"]
else:
cols = ["invoice_date"]
... | 0470421ed48d6cdffb38f9751a7c287027da4085 | 649,081 |
import argparse
def return_parser():
"""
Returns the argument parser for setup_mae_for_cs.py.
"""
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument(
'filenames', type=str, nargs='+',
help... | 265b0dee8ff847b78bde17d3fde138dbe5b4a046 | 649,082 |
def create_dic(c0, f0, dt, tau, nt, NS=1):
"""
Create a Spinsolve parameter dictionary from a universal dictionary.
Parameters
----------
udic : dict
Universal dictionary of spectral parameters.
Returns
-------
dic : dict
Dictionary of Spinsolve parameters.
"""
... | 69a7d6f4c83553e27290b25a641e1444959a5f10 | 649,083 |
import re
def normalize_newlines(string):
"""Adjust all line endings to be the Linux line break, \\x0a."""
return re.compile("\x0d\x0a|\x0d").sub("\x0a", string) | 971fd278732a043ead47e765a6845862a12c485b | 649,084 |
def parse_years(year_range):
"""Parse year_range into year list.
Args:
year_range: A string in the format aaaa-bbbb.
Returns:
A list of years from aaaa to bbbb, including both ends.
"""
st, ed = year_range.split("-")
st, ed = int(st), int(ed)
return [year for year in range(st... | 836c1108df2451ae16042382a5c7988875487a6a | 649,085 |
def kebab_to_snake(name: str) -> str:
"""Convert `name` from kebab-case to snake_case."""
return name.replace("-", "_").lower() | 7b0d4217a4c85294bf2b6c546387ad05b7eb8fdd | 649,086 |
def tail1(filepath, n):
"""Similate Unix' tail -n, read in filepath, parse it into a list,
strip newlines and return a list of the last n lines"""
with open(filepath) as f:
return [line.strip() for line in f.readlines()[-n:]] | f094e7453e153bd4ed84e9eea705659a10d3e58b | 649,087 |
def is_a(x, n=None):
"""
Check whether a list is a non-decreasing parking function.
If a size `n` is specified, checks if a list is a non-decreasing
parking function of size `n`.
TESTS::
sage: from sage.combinat.non_decreasing_parking_function import is_a
sage: is_a([1,1,2])
... | 2a58f73870b7eaac037f0a974421200fe8cbcebc | 649,088 |
def get_header_text(command_line_arguments):
"""Returns header text describing the argument type and containing the search string if one exists."""
if command_line_arguments.listAthletesFromNOC:
return "The athletes from " + command_line_arguments.listAthletesFromNOC + " are:\n\nAthlete name\n==========... | 208dd5bec083ae449314bfe7b4ff3e5c84d6b19d | 649,089 |
from typing import Any
def bytes_to_string(obj: Any):
"""
Converts a bytes object into a string
:param obj: Any type of object
:return: If the object is of type bytes it returns it's string representation, else returns
the object itself
"""
if isinstance(obj, bytes):
return obj.dec... | 692da29496f71fcbc100625d9c1e9bf95f8d5da9 | 649,090 |
def subsystem_exists(cur, member_id, subsystem_code):
"""Check if subsystem exists in Central Server"""
cur.execute(
"""
select exists(
select * from security_server_clients
where type='Subsystem' and xroad_member_id=%(member_id)s
and subsy... | 78ad656dbbdefc84a67d8cbfeedc84005151d23f | 649,091 |
def parse(string):
"""
This function parses the encoded string for the decoding phase.
This is especially userful when a character shows up
more than nine times in a row.
INPUT: An Encoded String
OUTPUT: A List of List // Parsed Encoded String
"""
if not string or len(string) == 1:
... | 7c444b9c5d1e48282618ae1aee31df61de0bc228 | 649,092 |
import functools
def accumulate(
items,
func=lambda x, y: x + y):
"""
Cumulatively apply the specified function to the elements of the list.
Args:
items (iterable): The items to process.
func (callable): func(x,y) -> z
The function applied cumulatively to the f... | deed252b22eb225ae58535c4b0bcc3571a139917 | 649,093 |
def _center_to_coco_bbox(bbox):
"""
from center format
to (tlx, tly, w, h)
:param bbox:
:return:
"""
tlx = bbox[0] - bbox[2] / 2
tly = bbox[1] - bbox[3] / 2
return [(tlx), (tly), (bbox[2]), (bbox[3])] | 3562de01e117b9ccd435f584f1bf8f2a5b1382e6 | 649,094 |
import six
def make_create_payload(**kwargs):
"""Create payload for upload/check-upload operations."""
payload = {}
# Add non-empty arguments
for k, v in six.iteritems(kwargs):
if v is not None:
payload[k] = v
return payload | 684c6421c2175947377e6de54408d13671928dd3 | 649,095 |
def get_where_value(conds):
"""
[ [where_column, where_operator, where_value],
[where_column, where_operator, where_value], ...
]
"""
where_value = []
for cond in conds:
where_value.append(cond[2])
return where_value | d66b966a30ff3cead02327cad957b7f3a7166c3e | 649,096 |
def draw_subgraph(name, graph, successors=True):
"""Draw (write to disk) a subgraph that starts with or ends with
the specified node.
Keyword arguments:
name -- name of the node to focus on
graph -- graph of paths between bundles
filename -- filename to write subgraph to
successors -- wheth... | a60febbc672477b3e09ed4bdc2228ae31e0d6f45 | 649,097 |
def capitalize_header(key):
""" Returns a capitalized version of the header line such as
'content-type' -> 'Content-Type'.
"""
return "-".join([
item if item[0].isupper() else item[0].upper() + item[1:]
for item in key.split("-")
]) | 9cdb9b8e3fba451a5dccaaab2196780fc6387472 | 649,098 |
import csv
def data_set_from_annotation(annotation_file):
"""
collect annotation files in target dir (target/data/class/image_file)
:param annotation_file: annotation_csv_file
:return: train_set: [image_file_path, label_idx]
test_set: [image_file_path, label_idx]
"""
data_set = li... | db66d4372b7afb0353eb8bb01c970a458ac13d6c | 649,099 |
import torch
def im_to_array_value(image):
"""
Transforms the image to an array of pixel coordinates and the containt
intensity
Parameters
----------
image: Image or 2DArray (N, M)
Image to be transformed
Returns
-------
x_coords: Numpy 1Darray (N*M, 1)
Co... | f6bef2d43242098379c595d5181623da1d26cebf | 649,100 |
def complement_strand(dna):
"""
Finds the reverse complement of a dna.
Args:
dna (str): DNA string (whose alphabet contains the symbols 'A', 'C', 'G', and 'T').
Returns:
str: the reverse complement string of a dna.
"""
reverse_complement = ""
for character in dna[::-1]:
... | 6e54664d9b7cacf8ac07b99129bb27eacea3e9e1 | 649,101 |
def get_grouping_from_another_yang_model(yang_model_name: str,
conf_mgmt) -> list:
""" Get the YANG 'grouping' entity
Args:
yang_model_name - YANG model to search
conf_mgmt - reference to ConfigMgmt class instance,
it have yJs... | 31d6fcfbafe4e8c7a0da73a0909b33017976c602 | 649,102 |
def create_device_name(tracked_asset_pair: str) -> str:
"""Create the device name for a given tracked asset pair."""
return f"{tracked_asset_pair.split('/')[0]} {tracked_asset_pair.split('/')[1]}" | 91e84665ae9eb405cb8dd0d6db249f9809bed450 | 649,103 |
def _fasta_name_to_tuple(x):
"""Fasta names can only be strings. This code gets the tuples back out."""
return tuple(x.split('___')) | 5c0248597e43df2be67cd20fa5294e505cf0bbe7 | 649,105 |
def to_std_dicts(value):
"""Convert nested ordered dicts to normal dicts for better comparison."""
if isinstance(value, dict):
return {k: to_std_dicts(v) for k, v in value.items()}
elif isinstance(value, list):
return [to_std_dicts(v) for v in value]
else:
return value | 0dd423df87438d745782477b8ea1471a8b196c2a | 649,106 |
def process_param(param, offset):
"""Process a single parameter produced by `get_function_parameter_names`."""
# Ignore args with default values, since Rope considers them assignments.
if "=" in param:
return []
# Strip off any type annotation.
first_colon_index = param.find(":")
if fir... | 15ac5d71f9d3deefd218ccaa9d2d93085d673aeb | 649,108 |
def wrap_by_word(text, n):
"""
returns a string where \n is inserted between every n words
:url https://www.reddit.com/r/learnpython/comments/4i2z4u/how_to_add_a_new_line_after_every_nth_word/
"""
a = text.split()
to_return = str()
for i in range(0, len(a), n):
to_return += ' '.join... | a240c7d4901744d24dcfd620543db6b01563c4e5 | 649,109 |
import os
def _NormalizeToUnixPath(path, strip=True):
"""Returns a path with '/' for the directory separator.
The regular expressions used in .gitignore processing use '/' as the directory
separator, but many APIs will convert '/' to '\' on Windows. This method can
be used to ensure consistent name formation... | 1fb9fc8c5ead9c4c980d06a48495ef91ae214ac5 | 649,110 |
def reformat_replace_star_list_with_dash_list(text):
"""
Replaces bullet lists starting with `*` with the lists starting with `-`
:param text: Original text
:return: New text without `*` bullet lists
"""
lines = text.split('\n')
new_text = ''
for line in lines:
if line.strip().s... | d80d1abae6c54daecabf9434e083ec3abd24bcc3 | 649,111 |
def ec_list(mod):
"""
Retuns a list of elasticity coefficients of a model.
The list contains both species and parameter elasticity coefficients and
elasticity coefficients follow the syntax of 'ec_reaction_sp-or-param'.
Parameters
----------
mod : PysMod
The Pysces model contains t... | fe78578aea738e1da379ec9736634d24095b1715 | 649,112 |
def sink_energy(global_params, vehicle, model_df):
"""
Determines how the excess wheel energy will be sunk
"""
wheel_energy_to_sink_mask = model_df["energy_wheel"] < 0
model_df["energy_to_sink"] = 0.0
model_df.loc[wheel_energy_to_sink_mask, "energy_to_sink"] = (
model_df.loc[wheel_energy... | d1482f6c6e2836b682047c92cf446808eba0409d | 649,113 |
def extend_parse(a_parser):
""" extent the basic arg parses by some extra required parameters
:return object:
"""
# SEE: https://docs.python.org/3/library/argparse.html
a_parser.add_argument('--an_executable', type=str, required=True,
help='some extra parameters')
retu... | 37ef71ece395a6c205fbec7cfba3eadffaaac7d7 | 649,114 |
def get_spec_padding(ispec, nspec, bundlesize):
"""
Calculate padding needed for boundary spectra
Args:
ispec: starting spectrum index
nspec: number of spectra to extract (not including padding)
bundlesize: size of fiber bundles; padding not needed on their edges
returns specmi... | 10a7d90e903ea2a7d4c5a6be328d028cb2a7241a | 649,115 |
def fasta2helm(fasta_seq):
"""Converts multi-line FASTA format into HELM strings"""
helm = ''
nnAA = False
amino_symbol = ''
for el in fasta_seq:
if len(helm) > 0 and not nnAA:
helm += "."
if el == "[":
amino_symbol += el
nnAA = True
elif ... | bcab594ee440a3bd0a765639c1d1794efcc4649e | 649,118 |
def patch_channel_map(channel_map, forced_channel_map=None):
"""
For the generated channel map, adds forced identifiers
"""
forced_channel_map = forced_channel_map or {}
patched_channel_map = {}
for channel_initial_name, channel_target_name in channel_map.items():
patched_channel_n... | aaac0ad0f6f80101285823005327c96ead8e3fac | 649,120 |
from typing import Dict
from typing import Any
def remove_unused_flags(user_calc_params: Dict[str, Any]) -> Dict[str, Any]:
"""
Removes unused flags in the INCAR, like EDIFFG if you are doing NSW = 0.
Parameters
----------
user_calc_params
User-specified calculation parameters
Return... | 6772212ab5ab398bc0db750219d98f6489dbcd08 | 649,121 |
def process_index(root, request):
"""
Function to process requests for index view. It generates and returns
nodes.
"""
nodes = root.node_vals
return nodes | dd1468ec1d79b317c3d022770415cc6c900d3d70 | 649,122 |
def bBalancedPar(p):
"""check if parenthesis are balanced no matter the content"""
l = 0
for c in p:
if c == ord(b"("):
l += 1
elif c == ord(b")"):
l -= 1
if l < 0:
return False
if l != 0:
return False
return True | 9480891316cc9661afdaae5bf1a76915d712e34f | 649,123 |
import os
import pickle
def save_pickle(data, filename, path, verbose=False):
"""Saves a pickle file.
Parameters
----------
data: object
Whatever Python object we pass that want it to be written as a Pickle file.
filename: str
Filename to write. Do not include the .pickle extensi... | 9c4573cd7778fe004c4de110f26f58571f942cd8 | 649,124 |
def unary_plus(op):
""":yaql:operator unary +
Returns +op.
:signature: +op
:arg op: operand
:argType op: number
:returnType: number
.. code::
yaql> +2
2
"""
return +op | 75ff2254d46f7d72a1b27c2e9df9e56556a3f32c | 649,125 |
def PrettyNumber(number, spacer=","):
"""
Iterates through an Integer and sets dots
as determined by dot_symb "." or "," every
third digit for better readability.
Example: NumberDotter(123456789)
Output: "123.456.789"
by Max Schmeling
"""
string = str(number)
spaced_list = ... | 99d66c675a1c210fbfbe2e278b1ebf5ba91e5060 | 649,126 |
from typing import Mapping
def delimited_file_to_dict(path : str,
delimiter : str=',') -> Mapping[str,str]:
"""
Returns a dictionary populated by lines from a file where
the first delimited element of each line is the key and
the second delimited element is the value.
... | 7687dfc0e59462455f8b90877d5232a342a6c789 | 649,127 |
def pil_coord_to_tesseract(pil_x, pil_y, tif_h):
""" Convert PIL coordinates into Tesseract boxfile coordinates:
in PIL, (0,0) is at the top left corner and
in tesseract boxfile format, (0,0) is at the bottom left corner.
"""
return pil_x, tif_h - pil_y | 86e2bfd1a49875613234d3cd489ed7b1a90e041e | 649,128 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.