content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import collections
def run_to_label(run):
"""
:param run: string containing parameters
:return: string designed for labels
"""
label = run[:]
replacedict = collections.OrderedDict()
replacedict["original"] = "orig"
replacedict["integration"] = "int"
replacedict["0mean-unnormaliz... | c8c5c4bdc63d1aa7a2122b29bfafea2d67600ff0 | 640,490 |
def is_valid_walk(walk):
"""
You live in the city of Cartesia where all roads are laid out in a perfect grid. You arrived ten minutes too early
to an appointment, so you decided to take the opportunity to go for a short walk. The city provides its citizens
with a Walk Generating App on their phones -- e... | b556810ddfbaaec8e2b2462606c8da58f978e9cf | 640,491 |
def get_department_average_salary_service(department):
"""
Returns department average salary from db
:param department: department
:return: department average salary
"""
average_salary = 0
if department.employees:
for employee in department.employees:
average_salary += em... | 8149ff4cbb2d0c9e00a1fb6e7bd36db7ce7bee79 | 640,492 |
def get_filter_string(filter_dict):
"""
return a string like _F0_B50 for a dict like {'F': 0, 'B': 50}
"""
return "".join(
"_{}{}".format(k, filter_dict[k]) for k in sorted(filter_dict.keys())
) | 9e6274c7aae56589ec5a3fe1c40aed8068d42747 | 640,493 |
import os
def add_directories(names):
"""Git/Mercurial/zip files omit directories, let's add them back."""
res = list(names)
seen = set(names)
for name in names:
while True:
name = os.path.dirname(name)
if not name or name in seen:
break
res.... | 4c02562c8ed3a0faf7df78b252816456a6d5dfc0 | 640,494 |
def get_aic(lnL, Nf):
"""
Provides the Akaike Information Criterion (Akaike, 1973), i.e. AIC.
Parameters
----------
lnL : float
Minus the log-likelihood.
Nf : int
Number of free parameters.
Returns
-------
AIC : float
AIC indicator.
"""
AIC = 2 * (... | 4d995f1d41f78238b15ec00c3ee7b66f5a9dafb8 | 640,496 |
def mk_level(ptype):
"""Convert a Pylint warning "type" to a Sarif level"""
ldict = {'error': 'error',
'warning': 'warning',
'refactor': 'note',
'convention': 'note',
'usage': 'note'}
return ldict.get(ptype, 'note') | 1a48a4839d024ae82653c322916884244db84c5f | 640,497 |
def pretty_user_story(story):
"""Pretty up a user story"""
story['acceptance criteria'] = '\n'.join(story['acceptance criteria'])
return story | 2df43ea1b79212bcdfa0ec777b677b2c2f0aa5cc | 640,498 |
from datetime import datetime
def date(date_string: str) -> datetime:
"""Validate and convert a date from string to datetime.
The date must be in the format MM/DD/YYYY.
"""
return datetime.strptime(date_string, r'%m/%d/%Y') | 26b156470a6780fb42dc2e4a9f45d01305b445af | 640,499 |
import math
def fib3(n):
"""通项法, 复杂度极低, 但在计算机上有精度问题"""
sqrt_5 = math.sqrt(5)
return int(sqrt_5/5.0*(((1+sqrt_5)/2.0)**n-((1-sqrt_5)/2.0)**n)) | 0df807a9835a385409443afde7158dfa4ff6fcef | 640,500 |
def request_json_data(scraper, uri):
"""
A simple helper to return a dict when given the url of a json endpoint
"""
r = scraper.session.get(uri)
if r.status_code != 200:
raise ValueError("Failed to get url '{}' with status code {}.".format(uri, r.status_code))
return r.json() | c4c89dd638a31222b994d11ab6ea9e3b39c2c5dc | 640,501 |
def boxIntersection(b1, b2):
"""
Compute a box small enough to fit inside both input boxes
"""
# easy enough
return tuple(map(max, zip(b1[0], b2[0]))), tuple(map(min, zip(b1[1], b2[1]))) | cc181e1c116a8ea64de9a17bd22a82d7ae9039cd | 640,502 |
def unzip(ls, nout):
"""Unzip a list of lists into ``nout`` outputs."""
out = list(zip(*ls))
if not out:
out = [()] * nout
return out | 4d8e3b2b6ba875b8d072364caf1bdd8605482f0a | 640,503 |
from typing import Union
def has_output_type(cell, output_type: Union[set, str]):
"""
Select cells that have a given output_type
:param cell: Cell object to select
:param output_type: Output Type(MIME type) to select: text/plain, text/html, image/png, ...
:type output_type: str
:return: a boo... | a51214e0b34783c4a51fff82185c191b8c910486 | 640,504 |
import os
def functional_tests_enabled():
"""Only do functional tests if the 'FUNCTIONAL' environment variable is
set to 'yes'.
"""
return os.environ.get('FUNCTIONAL', False) == 'yes' | fbf0a9dcc96447fd0db0e1c407de700224c1a568 | 640,505 |
import json
def dumps(object):
""" dumps an object to a json string
:param object: the object to be dumped
:return: a json string represents the object
"""
return json.dumps(object) | 6a6d6c68fca90871d4d732cc9cb2329f4ed5ba5d | 640,506 |
def dig_permutation(m, p):
"""
:param m: matrix dxd
:param p: permutation
:return: matrix m on which the percolation correspondent to the permutation p is digged
"""
a = m.copy()
for i in range(m.shape[0]):
a[i, p[i]] = 0
return a | 9619ac671e682a109e4060e1853f1fbb57c318de | 640,507 |
import os
import json
def read_json(nazwapliku):
"""Funkcja odczytuje dane w formacie json z pliku"""
dane = []
if os.path.isfile(nazwapliku):
with open(nazwapliku, "r") as plik:
dane = json.load(plik)
return dane | 93685917622e68eceadccd6ca2233c8a49e71870 | 640,508 |
def ns(v):
"""Return empty str if bool false"""
return str(v) if bool(v) else '' | 47b4e9fd2857c42aefaaf92aa2590ad8db33abfd | 640,509 |
import os
def config_folder_fixture():
"""Folder with configs"""
return os.path.join(os.path.dirname(os.path.realpath(__file__)), "test_config_files") | 8d0f1e222f7a0dd104616fe95651b5b62c6fd727 | 640,510 |
def utf8len(s):
"""Returns the UTF-8 encoded byte size of a string. `s` is a string parameter."""
return len(s.encode("utf-8")) | 826e179c2fbd6d6e55ef28b92b86a75e51082c4f | 640,511 |
import base64
def convert_bytes_to_base64(data: bytes) -> str:
"""Convert bytes data to base64 for serialization."""
return base64.b64encode(data).decode("ascii") | a810937ffaf0c40d318d02b3838accb294a5c226 | 640,512 |
import logging
def server_error(err):
"""server_error"""
logging.exception('An error occurred during a request.')
return """
An internal error occurred: <pre>{}</pre>
See logs for full stacktrace.
""".format(err), 500 | 036a947e994fd088b4e9ba88262d25185fbcce56 | 640,513 |
import random
def make_solution():
"""make_solution loops until we're able to fill all 81 cells with numbers, while satisfying the sudoku constraints."""
while True:
try:
puzzle = [[0]*9 for i in range(9)] # start with blank puzzle
rows = [set(range(1,10)) for i in range(9)... | 85760a664f92a9c82082e82ff98a9a58a5f6869f | 640,514 |
def hasHandlers(logger):
"""
See if a logger has any handlers.
"""
rv = False
while logger:
if logger.handlers:
rv = True
break
elif not logger.propagate:
break
else:
logger = logger.parent
return rv | 1715836b43a323cdd92cb33dd80981f1cecc172a | 640,515 |
def _translate(messages, language_code):
"""Helper function to assist in handling multiple translations of a message."""
try:
the_message = messages[language_code]
except KeyError:
the_message = messages["en"]
return the_message | 10ca86488ce4c7337cd9c7c0b19a859b618bb913 | 640,516 |
def get_src_folders(platform='msw', test=False):
"""Returns a sorted list of folders to search for C++-files for
inclusion in the Faint-build. Expressed relative to the Faint root
folder.
"""
assert(platform in ('linux', 'msw'))
folders = [
"",
"app/",
"bitmap/",
... | adadbf74e61cb313a8383d3b5adb1e0ce01ee15f | 640,517 |
def values_in_acceptable_entries(sequence, allowed_values) -> bool:
"""Each value in the sequence must be an allowed values. Otherwise, False."""
if len(sequence) == 0:
return True
for item in sequence:
if item not in allowed_values:
return False
return True | c8e1c1aa39cd1d88ed13f48151991d2b0230feb9 | 640,518 |
def lnGauss(x, mu, sigma):
"""
A log-Gaussian.
"""
ivar = 1./sigma**2
return -.5*(x - mu)**2 * ivar | 553bbab19f5e6c9da6b44f9c5278d5fcbedf685c | 640,519 |
def int_or_none(value):
"""
Try to make `value` an int. If the string is not a number,
or empty, return None.
"""
try:
return int(value)
except ValueError:
return None | dde9fce68dc9abdb51a5d21416fd7faca26a63a1 | 640,520 |
import unicodedata
def remove_control_characters(s):
"""
Remove control characters such as SOS and ST from a string.
Exists in many issn.org journal title.
"""
if s:
return "".join(ch for ch in s if unicodedata.category(ch)[0] != "C") | a9a9565fda99bed4db159c47e239d8bbfc4d9fc6 | 640,521 |
def read_pkginfo(filename):
"""
Help us read the pkginfo without accessing __init__
"""
COMMENT_CHAR = '#'
OPTION_CHAR = '='
options = {}
f = open(filename)
for line in f:
if COMMENT_CHAR in line:
line, comment = line.split(COMMENT_CHAR, 1)
if OPTION_CHAR in ... | 013f38d6fc2882201246c500815f9b058a4dcb99 | 640,522 |
def get_tensor_parents_placeholders(tensor):
""" Get all placeholders that is depending the given tensor. """
placeholders_list = []
if tensor.op.type == 'Placeholder':
placeholders_list.append(tensor)
if tensor.op:
for t in tensor.op.inputs:
if not 'read:0' in t.name:
... | fe32db36ca4c299006e82fcef836e88a8ce7b8d0 | 640,523 |
def mean_std(test_list):
"""calculate mean and std
"""
mean = sum(test_list) / len(test_list)
variance = sum([((x - mean) ** 2) for x in test_list]) / len(test_list)
std = variance ** 0.5
return mean, std | ef4d6154dbb1dcc27acd8e98c9c132b42ac2c55a | 640,524 |
def bedtxt2dict(pybed, strand_col=5):
"""
convert bed object to a dict with keys in bed file
From
chr123 123 123 +
To
('chr123', 123, '+') -> 1
:param pybed: bed object
:return:
"""
ret_dict = {}
for t in pybed:
ret = str(t).strip().split('\t')
key = (ret[... | 1e52add179a7c3011d0901c5dc7474765d7b4d89 | 640,525 |
def identify_significant_pairs(list_pairs):
"""Takes in a a list of lists, which include the pairs and the third element of each list is L.O.S.
Args:
list_pairs (list of lists): First element is crypto pair 1, second element crypto pair 2 and third element is L.O.S.
"""
return [x for x in list_... | adfcb73d008ad03996e0814f2cc3800f2fefd3bf | 640,526 |
def word_count(data):
"""
输入一个列表,统计列表中各个元素出现的次数
参数
----
data : list, 需要统计的列表
返回
----
re : dict, 结果hash表,key为原列表中的元素,value为对应的出现次数
"""
re = {}
for item in data:
re[item] = re.get(item, 0) + 1
return re | 57c90aaac8252cb0085bb946c6e66572e2c534bb | 640,527 |
import os
import jinja2
def render(file_path, tags):
"""
Renders a jinja2 styled template file provided by the file_path parameter
with the values in the tags dictionary parameter. The output is a string.
"""
abspath = os.path.abspath(file_path)
if os.path.exists(abspath):
dirname, fil... | 9791ea2bb854d06aa48cddc20c3037187d5ecdfb | 640,528 |
def _floyd_warshall(graph):
"""
Calculate the shortest path between two tokens using the Floyd Warshall
algorithm where the graph is the dependency graph
"""
dist = {}
pred = {}
for u in graph:
dist[u] = {}
pred[u] = {}
for v in graph:
dist[u][v] = float(... | 8fa3cb0a57e7f19e56b0cc50c3984a7cd0763a96 | 640,529 |
def clean_list(a_list):
"""
Apparently the only way to drop all of the unwanted characters
"""
# I don't want these in my title
undesirables = [',', '``', '`', ' `', '` ', "'", '"', '""', "''", '/', '{', '}', '(', ')', '[', ']']
new_list = [x for x in a_list if x not in undesirables]
return ... | bd27f33944b3872e145ac1f6256be26b24f3d646 | 640,530 |
def getRunFilename(sessionId, runId):
"""Return run filename given session and run"""
filename = "patternsData_run-{0:02d}_id-{1}_py.mat".format(runId, sessionId)
return filename | 623ad10430f3a165ab277c069ef75b86c9bf7e66 | 640,532 |
def lambda_handler(event, context):
"""Sample pure Lambda function
"""
return "Hello from a Lambda Image!" | ecf003ce92c2b41055f30fbe26a7bf5392039098 | 640,533 |
import re
def split_authors(authors_list):
"""
:param authors_list A list of authors to further split
:return A cleaner version of the authors list
"""
test_split = re.split(",", authors_list)
splits = [re.split(" ", x) for x in test_split]
final_authors = []
for authors in splits:
... | 9304d1ee30d1960094112c80557c4c40e5db1dab | 640,534 |
def _is_datetime_dtype(obj):
"""Returns True if the obj.dtype is datetime64 or timedelta64
"""
dtype = getattr(obj, 'dtype', None)
return dtype is not None and dtype.char in 'Mm' | b45eb6749ef2703358f9c9fe65d47d5c92543342 | 640,535 |
from pathlib import Path
import zipfile
def extract(
file_path, zip_path, out_path=None, pwd=None, overwrite: bool = False
) -> str:
"""
filepath: str or Path. File to extract \n
zip_path: str or Path of the zip-archive \n
out_path: str or Path. Alternate output-path
pdw: str. Password. Requir... | 6085a44072f97243c228fd6ab795b0e03c6c564f | 640,536 |
def get_selected_scenarios_in_cache(request, proj_id):
"""Given a request and the project id returns the list of selected scenarios"""
if isinstance(proj_id, int):
proj_id = str(proj_id)
selected_scenarios_per_project = request.session.get("selected_scenarios", {})
selected_scenario = selected_s... | 8629cc73a76cc797da335925e9f40f5ac77e8b85 | 640,537 |
from datetime import datetime
def _index_end():
"""Fixture for parametrization of index, series and frame."""
return datetime(2005, 1, 10) | 9da478166bd3b50780b73d15b0ef36cbabdb1177 | 640,538 |
import datetime
def footer():
"""Create footer string."""
license_link = 'https://creativecommons.org/licenses/by/4.0/'
license_image = 'resources/cc-by.png'
license_notice = 'To the extent possible under law, Daniel Teal has' \
' waived all copyright and related or neighboring' \... | 9f5a27c04a95a3437cb673a1933a1c3dd5f08e26 | 640,539 |
import os
def get_reddit_auth_kwargs():
"""Get the authentication kwargs for praw.Reddit from the environment.
Requires the following environment variables to be set:
* CLIENT_ID : the ID of your script application
* CLIENT_SECRET : the secret of your script application
* USERNAME : the username ... | 67e2a4ed7e3285f57082ac389bbbf97359c80e16 | 640,541 |
def filter_method(block, order_by_filter, lte, timestamp):
"""
Returns the block filter or the where filter depending of the block passed
"""
block_ret = ''
order_by_filter_ret = ''
lte_ret = ''
timestamp_ret = ''
if block:
block_ret = "block:{{ number: {number} }}".format(numbe... | d3497bbb806fb1e9dd858b295624e3921243bc4c | 640,542 |
def parse_op_code(op):
"""Return op, mode1, mode2, mode3."""
p100, de = divmod(op, 100)
p1000, c = divmod(p100, 10)
p10000, b = divmod(p1000, 10)
p100000, a = divmod(p10000, 10)
assert op == a * 10000 + b * 1000 + c * 100 + de
return de, c, b, a | 35e2bb86daecccb7791fd16252ac42967444124d | 640,543 |
def find_ids(df, id_column: str):
"""
Reads a dataframe and returns a list of unique data from the id_column.
"""
return list(set(df[id_column])) | 9ff197808ac1f1167f0ac22af59aa1ccb7271920 | 640,546 |
def data_file(request):
"""The path to a data file (set with metafunc.parameterize down below)"""
return request.param | a5dadaf1dfb4cd18c347d790131d5294ad998284 | 640,547 |
def string_compare_rule(mob_param_attributes, hmi_param_attributes):
"""Function checks presence of "minlength"="1" in HMI_API if
"minlength" is omitted in MobileAPI.
Should be checked only for "type"="String"
"""
attr = "minlength"
if attr not in mob_param_attributes:
if attr not in hmi... | 78897f1f0259941da5da533e0b5db16afe434734 | 640,548 |
import re
def contains(v, regex):
"""Removes meta data from regex then checks for a regex match
"""
return re.compile(regex.split('\\;')[0], flags=re.IGNORECASE).search(v) | ffaf2b08102ecd2ae2100cd8d126e8d5a9576683 | 640,549 |
def input_expression():
"""
Возвращает введённую функцию\функции
Returns
-------
expressions : optional - (exp1, exp2) or (exp, )
Кортеж из функции\системы двух функции.
n : int
Колв-во введённых функций.
"""
n = int(input('Введите кол-во уравнений, которые х... | 1d2d654313864624cfc9e2412cb4f11b69dfddad | 640,551 |
def text_in_text(entity, attribute, value):
"""
Return ``True`` if the provided entity has the string provided in
``value`` within its text attribute.
"""
try:
return value.lower() in entity.text.lower()
except (UnicodeDecodeError, TypeError):
# Binary tiddler
return Fals... | 12be5d3cbdb884735e17929c9f365bd8cde391fa | 640,552 |
def denormalize(x, std, mean):
"""Invert normalization, and then convert array into image."""
out = x * std + mean
return out.clamp(0, 1) | 965b117d4ce11f3e97e8404104fe9eedb5819788 | 640,553 |
import re
def unstring(obj):
"""
Attempt to parse string to native integer formats.
One can't simply call int/float in a try/catch because there is a
semantic difference between (for example) 15.0 and 15.
"""
floatreg = "^\\d+.\\d+$"
match = re.findall(floatreg, obj)
if match != []:
... | 79c8f660ca4318c6575688e864ba5bb9284f1629 | 640,554 |
import argparse
def parse_args():
"""
Parse Arguments from component
:return:
"""
parser = argparse.ArgumentParser()
parser.add_argument("--num_samples", help="# samples")
parser.add_argument("--num_features", help="# features")
parser.add_argument("--kernel", help="Kernel")
parse... | 258395442391c555731d8a664607c9615bcd234a | 640,555 |
def select_the_best_mutant(solutions):
""" Return the best solution, to be used as parent for a new
generation of mutant solutions.
"""
return solutions[0][0] | f2f0db8c52d314608e7a9b7d4ff852d0562e9a80 | 640,556 |
import collections
def _collect_sums_into_dictionaries(analyses, use_components, components_to_use):
"""
:param analyses:
:param use_components:
:param components_to_use:
:return:
"""
total_analysis = []
component_sum_dict = collections.OrderedDict()
num_sources_to_use = 0
... | f460a8f851c634a9189e02c7f248ab6474973c35 | 640,557 |
def get_item_thumbnail_url(item):
"""Returns the thumbnail for an enclosure or feedparser entry or raises a
:exc:`KeyError` if none is found."""
if 'media_thumbnail' in item:
return item['media_thumbnail'][0]['url']
blip_thumbnail_src = item.get('blip_thumbnail_src', None)
if blip_thumbnail_... | f6a8440838e02a9ac5c31a1ead5af3858155903f | 640,558 |
from typing import List
from typing import Optional
from typing import cast
def _mask_positional_args(name: str) -> List[Optional[str]]:
"""Create a section name representation that masks names
of positional arguments to retain their order in sorts."""
stable_name = cast(List[Optional[str]], name.split("... | 0590040ea6d5ba1a24886b9ce653322b7a258350 | 640,560 |
import yaml
def taxonomy(resp_json, return_obj, options):
"""Extract specific data on taxa from the subquery."""
# Named taxonomic ranks
with open('swagger_server/lookup/pbdb_taxa_ranks.yaml') as f:
rank_map = yaml.safe_load(f)
for rec in resp_json.get('records', []):
data = dict()
... | c69541c9848cde806af6b590dda6139d8ff836f8 | 640,562 |
import six
import posixpath
def get_fallback_packages(request, package_name, redirect=True):
""" Get all package versions for a package from the fallback_url """
dists = request.locator.get_project(package_name)
pkgs = {}
for version, url_set in six.iteritems(dists.get('urls', {})):
dist = dis... | 3b55f05353711b8a8049d0682cfa0cb744f9ac15 | 640,563 |
def level_list(root):
"""Get full level order traversal of binary tree nodes.
Example:
>>> from leetcode_trees import binarytree
>>> tree = binarytree.tree_from_list([5,1,4,None,None,3,6])
>>> binarytree.print_tree(tree)
___5___
1 _4_
3 6
>>> print(binarytree.level_representation(tree))
[[... | f53c14c5b195a6d0b5364c5258bd2576f1fabe66 | 640,564 |
def wcs(i, crpix, crval, cdelt):
"""calculate coordinates from WCS data"""
return crval + (float(i + 1) - crpix) * cdelt | 51f5ff0d6bacd1a0b778737b0bf7046ed014678a | 640,565 |
from typing import List
def get_requirements() -> List[str]:
"""Read requirements.txt and return the requirements.
Returns:
List[str]: List of requirements.
"""
requirements = []
with open("requirements.txt", "r", encoding="utf8") as file:
for line in file.readlines():
... | aa2c2a7d8053c304d1faebdd47a48794b5f6fada | 640,566 |
def is_nan(x):
"""
Returns `True` if x is a NaN value.
"""
if isinstance(x, float):
return x != x
return False | 342d64791986da9a1c0c0ee706bbc793539d6367 | 640,567 |
def check_edge(e,q,fsm):
"""
checks whether the current state q has an out-edge e. If so returns the state it goes to and the probability; otherwise returns None
Arguments
e : we're checking to see if there's an edge with this label
q : the current state
fsm : the fsm
Returns
... | d55ac87e904c17bbbd4e6a191e6468ce6fed6ac5 | 640,568 |
import os
def is_package(path):
"""Decipher whether a filepath is a Python package"""
return (
os.path.isdir(path) and
os.path.isfile(os.path.join(path, '__init__.py'))
) | 351a64e06656f2e05a598327890aabb8e94f8f77 | 640,569 |
import inspect
import os
def profileTyphon(name):
"""
A decorator to cause this method's frames to show up in vmprof logs.
The method must not accept more than five arguments, including `self`, and
all arguments must be instances or ints. In addition, the method cannot
accept kwargs.
"""
... | 77b34238b75a9760b1dfbabfead4ab7050f4aebe | 640,570 |
def total_rows(cursor, table_name, print_out=False):
""" Returns the total number of rows in the database """
cursor.execute('SELECT COUNT(*) FROM {}'.format(table_name))
count = cursor.fetchall()
if print_out:
print('\n[+] Total rows in database: {}'.format(count[0][0]))
return count[0][0] | cbd6d97e241d3f9b7043d26d2cd224a68dc90cef | 640,571 |
import time
def format_date( unixTime ):
""" format epoch time stamp as string """
return time.strftime("%Y/%m/%d %H:%M", time.gmtime(unixTime)) | 5f2d1f167a0a4245dca471d590490069a73df84e | 640,572 |
def sort_fragments_by_elf10wbo(frags):
"""
Sort fragments by ELF10 WBO. This helps with plotting all distributions so the distributions of the different
clusters are together
Parameters
----------
frags : dict
{'smiles': {'ensamble': , 'individual_confs': []}
Returns
-------
... | 1b2ad490f47421a5ca2695b0713b0ead59f6f58f | 640,573 |
import argparse
def create_parser():
"""
Create argument parser
"""
parser = argparse.ArgumentParser(description="Process some integers.")
parser.add_argument("metadata", type=str,
help="Input metadata (.tsv)")
parser.add_argument("model_prefix", type=str,
... | 505509ed7c554cfd84fcfe9e294ab9f53c3f6c43 | 640,575 |
import binascii
def crc_ihex(hexstr):
"""Calculate crc for given Intel HEX hexstring.
"""
crc = sum(bytearray(binascii.unhexlify(hexstr)))
crc &= 0xff
crc = ((~crc + 1) & 0xff)
return crc | 151f13e5cdf176e3aa5a2bf5e8e160b81f71cd14 | 640,576 |
def unwrap_edges(edges):
"""Unwrap edges"""
return ( (edge.src_id, edge.dst_id) for edge in edges) | 563d0b318d5b3c61961800898fdef2b620bb9786 | 640,577 |
import re
def get_exclude_patterns_as_regex_list(exclude_patterns=None):
"""
Takes a list of strings are returns a list of compiled regexes.
Strips enclosing quotes if present.
:type exclude_patterns: list[str]
:return:
:rtype: list[re.__Regex]
"""
exclude_regexes = []
if exclude_... | 4de3c0e34540e326e5d95e00fc5dc738b7fe3f17 | 640,578 |
def decorated_test_task_with_decorator_args(**kwargs):
"""
Test task, echos back all arguments that it receives.
This one is registered using a decorator
"""
print(f"The decorated (with args) test task is being run with kwargs {kwargs} and will echo them back")
return kwargs | bc6cd92a7df6634834756ca391536fc86818e72c | 640,579 |
def extract_triples(conceptnet_path):
"""检索出conceptnet中的三元组"""
conceptnet_triples = []
with open(conceptnet_path, 'r', encoding="utf-8") as f:
for line in f.readlines():
ls = line.split(",")
head = ls[0].strip()
rel = ls[1].strip()
tail = ls[2].strip()... | 010dd5849b5bca4c0e8d8b10166df5bdfd0bbdc8 | 640,580 |
def separator(simbol, count):
"""
Функция создает разделитель из любых символов любого количества
:param simbol: символ разделителя
:param count: количество повторений
:return: строка разделитель примеры использования ниже
"""
s = simbol * count
return s | bdf9b7ac533eaec26552a3ed6238f239caac9d21 | 640,582 |
def eq_by(f, value_1, value_2):
"""Check if two values are equal when applying f on both of them."""
return f(value_1) == f(value_2) | 2ea1d66fdadf8cc8d9b31ec358b90e8e579263b6 | 640,583 |
from pathlib import Path
def read_markdown(fpath: Path) -> str:
"""Read Markdown file as a string."""
with open(fpath, "r+") as f:
md = f.read()
return md | 1723a43eacefd780c7a38caa5591e48bad8fdf85 | 640,584 |
def timestamp_to_sbs(t):
"""Convert timestamp to SBS data
Args:
t (Timestamp): timestamp
Returns:
hat.sbs.Data: SBS data
"""
return {'s': t.s, 'us': t.us} | 2c33620685d2a465c7156aea6ac0412b6a24d468 | 640,585 |
def normalize_ds_index(df, ds_col):
"""Normalize usage of ds_col as column in df.
Warnings
--------
- Be aware this function potentially modify the given Dataframe df, so please send a copy of the original if you want it to remain unmodified.
"""
if ds_col in df.columns:
return df
e... | 64bdf569cadf9795248ffd15f5501b26f2501651 | 640,588 |
def parse_contig_assignments(assignment_file_path, contig_name_col=0, unassigned_col=9):
"""
Finds contig_names that are unassigned twice.
Inputs:
- assignment_file_path: Path to tab-delimited file
- contig_name_col: Index of the col which will have the contig name
- unassigned_col: Index of th... | 49cca60afaadcf0e665b65e7fab08f1e186c3785 | 640,589 |
def create_name(words):
""" Concatenate words to create the title name. """
return ' '.join(words).title() | ace7c8c4ea3015f0f6ad346408ffff60b588cd99 | 640,591 |
from typing import TextIO
from typing import Dict
from typing import Any
def scan_hmc_params(
fd: TextIO, config_dict: Dict[str, Any], lineno: int
) -> int:
"""
Scan step size, metric from stan_csv file comment lines.
"""
metric = config_dict['metric']
line = fd.readline().strip()
lineno ... | 022f8000aec70b1af4a89053dfaaef8a7431c73b | 640,592 |
def covstr(strings):
""" convert string to int or float. """
try:
result = int(strings)
except ValueError:
result = float(strings)
return result | c4784b6f7529d124ea4f8d8725985a9662e10ba6 | 640,593 |
def flags(cls, *arg, **keywords):
"""
Decorator to set any flag.
"""
base = cls.__mro__[-2]
base.__dict__['_set_flags'](cls, *arg, **keywords)
return cls | db3ec94412dfb100d97e671674460cc1b936459b | 640,594 |
import argparse
def parse_arguments():
"""Accepts filepath and length as command line arguments.
Keyword arguments:
filepath -- fully qualified local file name or fully qualified URL
length -- umber of sentences to return in summarization (default 4)
"""
parser = argparse.ArgumentParser()
... | c34705d49b787e1a55335ea74d25dcf25a055f36 | 640,595 |
import socket
def check_machines(machines):
"""
Return a True if the current machine is in the list of machines.
:param `machines`: A single machine or list of machines to compare
with the current machine.
"""
local_hostname = socket.gethostname()
if not isinstance(mac... | 72dca69f98119dd8a12439b4029cbe5e1d2d769e | 640,596 |
def create_dataset_url(base_url, identifier, is_pid):
"""Creates URL of Dataset.
Example: https://data.aussda.at/dataset.xhtml?persistentId=doi:10.11587/CCESLK
Parameters
----------
base_url : str
Base URL of Dataverse instance
identifier : str
Identifier of the dataset. Can be... | 47116663bd851d380e7de807b3a5e544302936d1 | 640,597 |
import base64
def from_url_safe_stream_id(stream_id: str) -> str:
"""Convert the URLSafe encoded stream id to the corresponding original stream id
:param stream_id: streamId of the stream to be parsed
:return: stream id after conversion
"""
decoded_url_bytes = base64.urlsafe_b64decode(stream_id +... | 3cbeabb40431f999fa4ed9ebf9698ec670a45f9f | 640,598 |
def get_interest(n: float, p: float, i: float) ->\
float:
""""
Повертає проценти за вказану кількість років.
Parameters
----------
n : float
Термін угоди, виражений у періодах
p : int
Сума грошей (капітал), що даються в борг
i : float
Відсоткова ставка віднес... | 1c101906177709d1fda8a3954bed3cc8b749ab30 | 640,599 |
def accuracy(pred, target):
"""
Args:
pred: Tensor of size `B x C`
target: Tensor of size `B`
"""
return (pred.argmax(dim=1) == target).float().mean() | b77f56f9357f1eb9f7093574e17d5c8650106dd4 | 640,600 |
def get_scale_offsets(scaled_w, scaled_h, origin_w, origin_h,
offset_l, offset_t, offset_w, offset_h):
"""
Inverts scaling offsets (kind of like inverting the scaling itself, really).
Calculates the scale offsets necessary to scale back to its original form an
image that was scaled to the spe... | 51148dedd2133e2f6de2f5535f3b5d65bc885d58 | 640,601 |
def remove(seq1, seq2):
""" remove the elements in `seq2` from `seq1`
"""
return tuple(elem for elem in seq1 if elem not in seq2) | 49ab05fec0304aca078f419dfee0cb5fab38d5f5 | 640,602 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.