content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def noAction(State):
"""
Do nothing option.
Arguments
---------
State : StateClass
governing state, ignored.
Returns
-------
None
"""
return None | 6835d630b5f66b3184f8ce5deab096222f15dc5d | 661,400 |
def normalvariate(mu, sigma):
"""Normal distribution. *mu* is the mean, and *sigma* is the standard deviation."""
return 0.0 | 9dbdbb31b67ab9c8b6729a05b81652ef698681e5 | 661,401 |
import random
import string
def generate_random_string(length):
"""Utility to generate random alpha string for file/folder names"""
return ''.join(random.choice(string.ascii_letters) for i in range(length)) | b33734caf1c95e5a2f000f9673e8956e16c11614 | 661,402 |
def recursive_binary_search(l:list, item):
"""Use binary search with recursion."""
if len(l) < 2:
return 0 if len(l) == 1 and item == l[0] else None
else:
mid = len(l) // 2
if item == l[mid]:
return mid
elif item > l[mid]:
return recursive_binary_searc... | 4c62c9a4ea71078da75460a5e861465363dae6ed | 661,403 |
import argparse
import os
import sys
def parse_args():
"""Read args, check."""
app = argparse.ArgumentParser()
app.add_argument("orthologs_file", help="Output of the chain classifier.")
app.add_argument("bed_file", type=str, help="BED FILE")
app.add_argument("bdb_bed_file", type=str, help="BDB BED... | 2b28149b1f434ccd922563ab4f45dfd73ee3b8be | 661,404 |
def check_header_gti(hdr):
"""
Check FITS header to see if it has the expected data table columns for GTI
extension.
Require the following keywords::
TELESCOP = 'NuSTAR' / Telescope (mission) name
HDUCLAS1 = 'GTI' / File contains Good Time Intervals
NAXIS = ... | b478b0165244cf36019d26af3d6518b82e5d3925 | 661,406 |
def convert_args_to_list(args):
"""Convert all iterable pairs of inputs into a list of list"""
list_of_pairs = []
if len(args) == 0:
return []
if any(isinstance(arg, (list, tuple)) for arg in args):
# Domain([[1, 4]])
# Domain([(1, 4)])
# Domain([(1, 4), (5, 8)])
... | 2c0e10244a85e68f7da87db4e420648b702c1391 | 661,407 |
def xify_dirname(val):
"""Convert a directory name to an X-string, as used in the index.html
filenames. The "if-archive/games" directory is mapped to
"if-archiveXgames", for example.
We acknowledge that this is ugly and stupid. It's deprecated; we now
point people to dir/index.html indexes which don... | 96860bb53d9a9e98bd02753b1f5675a2b85410f1 | 661,408 |
def get_eta_H_i(f_H_i, etr_d_i):
"""開口部の暖房期の日射熱取得率 (-) …………式(3)
Args:
f_H_i(float): 開口部の暖房期の取得日射熱補正係数 (-)
etr_d_i(float): 開口部の垂直面日射熱出得率((W/m2)/(W/m2))
Returns:
float: 開口部の暖房期の日射熱取得率((W/m2)/(W/m2))
"""
return f_H_i * etr_d_i | 3ea996ab2f949b55a5faee32b6ac18b0b678c939 | 661,410 |
import os
def get_data_path():
"""
Get the directory from which the script is executed to load the data correctly. This is especially important for
the execution in a jupyter notebook.
"""
current_path = os.getcwd()
current_directory = current_path[current_path.rindex(os.sep) + 1:]
if curr... | 3f40f78de0dbdb86e1127a3a81169870a49b6c17 | 661,412 |
def get_keydefs(doc, soort, keydefs=None):
"""build dictionary of key combo definitions
"""
if not keydefs:
keydefs = {}
context = ''
for line in doc:
line = line.strip()
if not line or line.startswith(';') or line.startswith('#'):
continue
elif line.sta... | 71c350b1ca4c63769535737da30b6758727eb10e | 661,413 |
def disabled(m):
"""Load-time waring about disabled function"""
print("warning: method is disabled:%s" % m)
def nothing(*args, **kwargs):
print("warning: Calling disabled method %s does nothing" % str(m))
return nothing | d298ec7d69b23351fbf5a016cc68867b77331f53 | 661,414 |
def create_filter(badge, name, param, params):
"""
params should be a QueryDict e.g. request.GET.copy()
"""
# handle show/hide
active = param in params
if 'hide' in param:
active = not active
if param in params:
del params[param]
else:
params[param] = ''
... | 9cb846ededc229caa59c05f38e904e17270f248d | 661,415 |
def broadcastUNeighborDict(sContext, uNeighborRDD):
""" Broadcast user neighbors dict
"""
userNeighborList = uNeighborRDD.collect()
userNeighborDict = {}
for user, simrecords in userNeighborList:
userNeighborDict[user] = simrecords
uNeighborBC = sContext.broadcast(userNeighborDict)# broa... | 241af4abaacacaf2c90553f5d155e069dd1fad71 | 661,417 |
def tokenFieldPredicate(field):
"""returns the tokens"""
return tuple(field.split()) | 5a40ec384cd029942fd5c86214994dbf95f48813 | 661,418 |
def render_plugin(context, plugin):
"""
Render a single plugin. Requires the
:class:`feincms3.renderer.TemplatePluginRenderer` instance in the context
as ``renderer``::
{% render_plugin plugin %}
In general you should prefer
:func:`~feincms3.templatetags.feincms3_renderer.render_region... | 909159e89a6bff00254e81ff531e9197ca142bdd | 661,420 |
def num_simplex_boundary_simplices(n):
"""
Get the number of boundary simplices of an n-dimensional simplex.
:param n: Dimension of the simplex.
:return: Number of boundary simplices.
.. rubric:: Examples
>>> num_simplex_boundary_simplices(2)
3
>>> num_simplex_boundary_simplices(3)
... | b3ad06d268b515619338d17c6bc6b3cd7acdda67 | 661,421 |
import re
def has_datas(command):
""" Function to determine if there is data in the curl command, even if the datas are empty
or only if there is --data or -d without something next to it."""
has_datas_pattern = r"(-d|--data)"
has_datas = re.search(has_datas_pattern, command)
return True if has_d... | 4f7c639f428aeca2239a9468a6f723db4dfb2419 | 661,422 |
def check_key(data, key):
""" Check if key in data. If so, then return the value, otherwise
return the empty string.
"""
if data.keys().__contains__(key):
return data[key]
else:
return '' | b74bda9a268b19918844a779365b0ca8022a2ec8 | 661,423 |
def guess_type_value_type(none=True):
"""
@param none if True and all values are empty, return None
@return the list of types recognized by guess_type_value
"""
typstr = str
return [None, typstr, int, float] if none else [typstr, int, float] | 5926dc0ce7f766cb1e596fe8d4f5ff97f41fa9c9 | 661,424 |
from typing import Any
def decode_answer(response_data: dict) -> Any:
"""
Decode the answer described by *response_data*, a substructure of an
enrollment document.
Returns a string, number, tuple of strings, or None.
"""
answer = response_data["answer"]
if answer["type"] in ["String", "N... | e0c88644f09412a95ab6df929f691d6936140fc3 | 661,425 |
import random
import math
def evaluate_cost(uk_cities):
"""
this method evaluates the cost for the graph
:param uk_cities: networkx graph
:return: networkx graph
"""
# get all the roads from the graph
all_roads = uk_cities.edges()
for i, val in enumerate(all_roads):
# get the d... | 24751d183465b8a33c4698a9aa73fad9ee6e8da4 | 661,426 |
import os
def _check_file_and_return_name(file):
"""
Check whether a file exists and if it does, accumulate file number so that we don't overwrite previous files.
"""
i = 2
if file[-3:] == "mp4":
if os.path.exists(file):
file = file[:-4] + str(i) + ".mp4"
i += 1
... | 97524e96d5009e6df543a926c4f8ac07df48b580 | 661,427 |
def half_rect(input):
"""
Half rectification
Parameters:
inData: ndarray
input signal
Returns:
result: ndarray
half-rectified signal
"""
return (input + abs(input)) / 2.0 | 2c0c418f4e8d6fe58ecc65ae7849cb37da3b658a | 661,428 |
def find_ab(side1, side2, side3):
"""
Takes three side lengths an returns two smallest in a list
:param side1: int or float
:param side2: int or float
:param side3: int or float
:return: list of 2 ints or floats
"""
ansX = side1
if side2 > side1 and side2 > side3:
ansX = side... | 1f4cbb1093f3b702588d9229a162e53c3508a215 | 661,429 |
import numpy
def rads(angle):
"""
Converts given angle from degrees to radians.
Args:
angle: float
Angle in degrees.
Returns:
float
Angle in radians.
"""
return numpy.deg2rad(angle) | 2c94f42badd24c199f540695c567ff8f25a5ef2a | 661,430 |
def edit_string_for_tags(tags):
"""
Simplified version of comma separated tags
"""
names = []
for tag in tags:
name = tag.name
if ',' in name:
names.append('"%s"' % name)
continue
names.append(name)
return ','.join(names) | e2400cfb3808e7f42db5a3c109345513464881dc | 661,431 |
import requests
import base64
def get_file_content(repo_url, revision, file_path):
"""Get a git project file content of a specific revision/tag"""
url = "%s/contents/%s?ref=%s" % (repo_url, file_path, revision)
response = requests.get(url)
response.raise_for_status()
return base64.b64decode(respon... | e179df3b576fb4057e2fa944b0f8efe8025f4a04 | 661,433 |
def additive_extension(additive_func, q, q_max, cache=None, cache_offset=1):
""" Additive extension for event models.
Any sub- or super- additive function additive_func valid in the domain q \in [0, q_max]
is extended and the approximited value f(q) is returned.
NOTE: this cannot be directly used with d... | f1fab9ff996e76c37375f4bb6a20da3ead43a54c | 661,434 |
import random
def getRandomSequence(length=500):
"""Generates a random name and sequence.
"""
fastaHeader = ""
for i in range(int(random.random()*100)):
fastaHeader = fastaHeader + random.choice([ 'A', 'C', '0', '9', ' ', '\t' ])
return (fastaHeader, \
"".join([ random.choice([... | 14bf1fa84de82d10f1acae479cf5f145ced875ae | 661,436 |
import subprocess
import os
def get_avb_image_size(image):
"""Returns the image size if there is a AVB footer, else return zero."""
avbtool_info_cmd = ['avbtool', 'info_image', '--image', image]
result = subprocess.run(avbtool_info_cmd, check=False,
stdout=subprocess.DEVNULL,
... | da0f61332c589f61d48e84bc82cda9a95acc26ec | 661,437 |
def extract_line_coverage(coverage):
"""Extract line coverage from raw coverage data."""
line_coverage = {}
# file name -> function data
for filename, function_data in coverage.items():
line_coverage[filename] = {}
# function -> line data
for _, line_data in function_data.items(... | 1c7727353b9089e02a07fa447904e8333415718f | 661,438 |
from functools import reduce
def rgetattr(obj, name):
"""Recursive version of :func:`getattr`."""
return reduce(getattr, name.split('.'), obj) | aa27f5eb1e1450f6e5bf128eada61952d5b8bfb2 | 661,439 |
import random
def reduce_dicts(titles, gold, shuffle=False):
""" reduce 2 dictionaries to 2 lists,
providing 'same index' iff 'same key in the dictionary'
"""
titles, gold = dict(titles), dict(gold)
titles_list = []
gold_list = []
for key in titles:
titles_list.append(titles[key])
... | 374b814fc59d5caa8500d567c9e7eb6b0b542628 | 661,440 |
def int_list_to_str(lst):
"""
Given a list of integers: [1, 10, 3, ... ]
Return it as a string of the form: "[1,10,3,...]"
"""
return "[%s]" % ','.join([str(l) for l in lst]) | af21e4142a4a7819a5e64950416ac919b0d0b44d | 661,441 |
def endian_swap(value):
""""Given a 32-bit integer value, swap it to the opposite endianness"""
return (((value >> 24) & 0xff) | ((value >> 8) & 0xff00)
| ((value << 8) & 0xff0000) | (value << 24)) | 242d28990a7c286f411d2d1e1cd826e9bad78bf3 | 661,442 |
import time
def wait_for(predicate, timeout, period=0.1):
"""
Wait for a predicate to evaluate to `True`.
:param timeout: duration, in seconds, to wait
for the predicate to evaluate to `True`.
Non-positive durations will result in an
indefinite wait.
:param period: predicate evaluat... | 03564b07b51ad29785562611bca36490156d205e | 661,443 |
import re
def compute_cpf_validation(cpf):
""" Generates the check digits for a given CPF.
Parameter:
cpf -- A string with 9 to 11 digits. Only the first 9 will be used.
Return:
The checkdigits for the given CPF.
"""
if not re.match('[0-9]{9,11}', cpf):
raise ValueError('The CPF must have at least 9 digits... | 96ee1e207d5d90c0be05e594a7fe62102ddee559 | 661,444 |
import argparse
def get_args_eval():
"""arguments for _eval.py"""
parser = argparse.ArgumentParser()
parser.add_argument("--folder", type=str, default="vacc_download/walker2d_10_10-v1", help="Path to stored experiment data.")
parser.add_argument("--body-id", type=int, default=-1)
parser.add_argume... | b97ffc8b861af84d12b343920a920b35f147a9c8 | 661,445 |
def _create_statistics_data(data_list, is_multi_series=False):
"""
Transforms the given list of data to the format suitable for
presenting it on the front-end. Supports multi series charts (like
line and bar charts) and or single series ones (like pie/donut
charts).
:param data_list: a list of ... | 2376cfe38e5ad7828db096a6163e37656a65f220 | 661,446 |
import os
def scan_for_commands(dirname=""):
"""Build a dictionnary containing all commands
:param str dirname: the directory where commands are located
:return: a dict of commands (name : class)
"""
path = os.path.join(os.path.dirname(__file__), dirname)
result = {}
for f in os.listdir(p... | f58cb5f492874d56091ea1070b9540634ce21d02 | 661,447 |
import struct
def ubyte_to_bytes(byte_data: int)->bytes:
"""
For a 8 bit unsigned byte
:param byte_data:
:return: bytes(); len == 1
"""
result = struct.pack('<B', byte_data)
return result | 7d4c834d527e0fce3cca5575636047423ce44f6e | 661,448 |
def member_to_beacon_proximity(m2badge, id2b):
"""Creates a member-to-beacon proximity DataFrame from member-to-badge proximity data.
Parameters
----------
m2badge : pd.DataFrame
The member-to-badge proximity data, as returned by `member_to_badge_proximity`.
id2b : pd.Series
... | 458f2894190689ea3ca31483c1e814ccc31a9795 | 661,449 |
import pathlib
def get_stopwords(language = "english"):
"""Get stopwords for a language.
language: 停用词语言。有"english"和"chinese"两种参数可供查询获取。
"""
cnpath = pathlib.Path(__file__).parent.joinpath('dictionary', 'chinese.txt')
enpath = pathlib.Path(__file__).parent.joinpath('dictionary', 'english.txt')
... | f45f3096c915db81718d53589e8543b11a6e8b7d | 661,451 |
def get_height_magnet(self):
"""get the height of the hole magnets
Parameters
----------
self : HoleM50
A HoleM50 object
Returns
-------
Hmag: float
height of the 2 Magnets [m]
"""
# magnet_0 and magnet_1 have the same height
Hmag = self.H3
return Hmag | 99bd4c0d503fc86ba4491cde1b3fc7db904af91c | 661,452 |
import itertools
def first(n, it, constructor=list):
"""
>>> first(3,iter([1,2,3,4]))
[1, 2, 3]
>>> first(3,iter([1,2,3,4]), iter) #doctest: +ELLIPSIS
<itertools.islice object at ...>
>>> first(3,iter([1,2,3,4]), tuple)
(1, 2, 3)
"""
return constructor(itertools.islice(it,n)) | 2af22fa2f1038f284c3248234d8b9d6179f89430 | 661,453 |
def del_repeats(str_series):
"""
deletes consecutively repeated characters from the strings in a series
"""
no_repeats = str_series.str.replace(r'([a-z])\1+', r'\1')
return no_repeats | 4ab96eb345d2f469bcb8d13b4f4f03fd2ecfa653 | 661,454 |
def _set_defaults(value):
""" Reasonable defaults for these save some typing. """
# should work unless you've gotten creative with your network
address = '192.168.0.1'
if 'address' not in value:
value['address'] = address
# not sure this can be changed
user = 'cusadmin'
if 'user' not in value:
va... | 2637461b2a9169e0432cf9e78b500c2d7b86e0b7 | 661,455 |
import subprocess
def get_shell_cmd_output(cmd):
"""
Returns the output of the shell command "cmd".
:param cmd: the shell command to execute
"""
output = subprocess.check_output(cmd, shell=True, universal_newlines=True)
return output | 62924b9f56ebb4134dda333c7e60251f37d56b34 | 661,456 |
def get_deployment_labels(deployments):
"""
Get labels for a given list of deployments.
Returns a dictionary in the below format:
{ deployment_name: {dictionary of deployment labels}, ...}
"""
deployment_dictionary = {}
for deployment in deployments:
deployment_dictionary[deploymen... | 418786845c1f9313e6f1e670927f3f600553dab7 | 661,457 |
def safe_json_metadata(post: dict) -> dict:
"""
Create a MongoDB index safe json_metadata output.
Alternatively, run with:
mongod --setParameter failIndexKeyTooLong=false
"""
def truncate(data):
if isinstance(data, dict):
data = {
**data,
... | 29b423f12abc68fff210ced9bd9fa94cd17bb67b | 661,458 |
def getFloatFromStr(number: str) -> float:
""" Return float representation of a given number string.
HEX number strings must start with ``0x``.
Args:
numberStr: int/float/string representation of a given number.
"""
numberStr = number.strip()
isNegative = False
if "-" in numberStr:
... | de5ee4e8193bd8127bb8d42946e184f45d1f3b23 | 661,459 |
def get_max_links_len(body):
"""Length of max sequence of links, without duplicate tags between links"""
tag, max_len = body.find_next('a'), 0
while tag:
cur_len = 1
for tag in tag.find_next_siblings():
if tag.name != 'a':
break
cur_len += 1
if... | a72d1818c433b50d6d784b1d8db8bca0d762eb9e | 661,460 |
from typing import List
import math
def calculate_percentile(times: List[int], percent=0.95) -> int:
"""
Calculate percentile (by default 95%) for sorted `times`.
If we cannot choose one index, we use average of two nearest.
"""
index = (len(times) - 1) * percent
if index.is_integer():
... | fafde68141aa7a788d334acd21f488df435479b9 | 661,461 |
def insertion_sort(array: list, ascending=True) -> list:
"""This function sort an array implementing the insertion sort method
Parameters
----------
array : list
A list containing the elements to be sorted
ascending : boolen
Indicates whether to sort in ascending order
Retu... | 6083b4918048ec19ddde159391d7be284c2feabf | 661,463 |
import re
def get_pool_uuid_service_replicas_from_stdout(stdout_str):
"""Get Pool UUID and Service replicas from stdout.
stdout_str is something like:
Active connections: [wolf-3:10001]
Creating DAOS pool with 100MB SCM and 0B NvMe storage (1.000 ratio)
Pool-create command SUCCEEDED: UUID: 9cf5be... | 276dca436ce16b23fb2dd9f108ef4c309c030c8e | 661,464 |
import copy
def copy_list(src, deep_copy=False):
"""
Copies list, if None then returns empty list
:param src: List to copy
:param deep_copy: if False then shallow copy, if True then deep copy
:return: Copied list
"""
if src is None:
return list()
if deep_copy:
return co... | 4e658232de46c196983597e4410413f812ef1882 | 661,465 |
from pathlib import Path
def is_path(file):
"""Helper function for testing whether *file* needs an :func:`open` call."""
return isinstance(file, (bytes, str, Path)) | f9b7da66a82e696b624423145cc2dc6ce01951bc | 661,466 |
def get_head(text, headpos, numchars):
"""Return text before start of entity."""
wheretostart = headpos - numchars
if wheretostart < 0:
wheretostart = 0
thehead = text[wheretostart: headpos]
return thehead | 25c8b90f341b328c8c452d88a98c52b8107734cd | 661,467 |
def get_in(dct, keys):
"""Gets the value in dct at the nested path indicated by keys"""
for key in keys:
if not isinstance(dct, dict):
return None
if key in dct:
dct = dct[key]
else:
return None
return dct | 1445fbfd3b47a5b0f23968dcf8695cdb0716eeea | 661,468 |
import os
def update_set(s, d):
"""
function to update a set with URSIs and stranger presence from
vocal-condition wav files in a given directory
Parameters
----------
s : set
set to update
d : string
path to directory to update from
Returns
-... | d5e763ea722b40e41232905788cdb2705a964bec | 661,469 |
def initial_investment(pv_size, battery_size, n_batteries = 1, capex_pv = 900, capex_batt = 509):
"""Compute initial investment"""
return pv_size*capex_pv + battery_size*capex_batt*n_batteries | fbc34697b933fac22ae047213bef5a23a70e6dd2 | 661,470 |
def _select_column_names(columns_to_select, df):
"""
base function for column selection.
Returns a list of column names.
"""
if columns_to_select in df.columns:
return [columns_to_select]
raise KeyError(f"No match was returned for '{columns_to_select}'.") | 3c49f18680299304956ed29ec9dc0c6939e056d4 | 661,471 |
def _numeric_to_english(word):
"""! replace numerals with english """
eng = ['zero', 'one', 'to', 'three', 'for', 'five', 'six', 'seven', 'ate', 'nine']
for e, i in zip(eng, range(0,len(eng))):
word = word.replace(str(i), '_'+e+'_')
return word | 0343737eaf4b755b4de8438f42437c37b18af09b | 661,472 |
def est_dif (s):
"""доп. оценка - по разным цифрам"""
u = list(set(list(s)))
u.sort()
u = "".join(u)
return u | c0bfa5bbfe99f4325bfafd1f2bb82c8823c667f1 | 661,474 |
def recursive_unwanted_orphacode(elem):
"""
Remove the ORPHAcode past the one defined at the disorder's root level
! NO quality check !
Useless since new Orphadata generation
:param elem: disorder object or property
:return: disorder object or property without ORPHAcode key
"""
if isins... | 8250cd65562495b33babe901932d1b6a2ad78a87 | 661,475 |
def truncated_list(data, n):
"""Compute a truncated list, n is truncation size"""
if len(data) < n * 2:
raise ValueError('list not large enough to truncate')
return sorted(data)[n:-n] | b9fcee8b3c3fba90f5705108283118993b2ad601 | 661,476 |
import subprocess
def check_presence(tv_file):
"""
Just a wrpper of 'ls' command
"""
try:
subprocess.check_output(['ls', tv_file])
return True
except subprocess.CalledProcessError:
return False
return False | 4446254a369ff37f4ee35eb92d8082a643bad7f7 | 661,477 |
def compress(years):
"""
Given a list of years like [2003, 2004, 2007],
compress it into string like '2003-2004, 2007'
>>> compress([2002])
'2002'
>>> compress([2003, 2002])
'2002-2003'
>>> compress([2009, 2004, 2005, 2006, 2007])
'2004-2007, 2009'
>>> compress([2001, 2003, 2004, 2005])
'2001, 20... | f506476fd073246d7827104d338c4226ca6d28b9 | 661,478 |
import torch
def predict_cmap_interaction(model, n0, n1, tensors, use_cuda):
"""
Predict whether a list of protein pairs will interact, as well as their contact map.
:param model: Model to be trained
:type model: dscript.models.interaction.ModelInteraction
:param n0: First protein names
:type... | a90efa0026a50ed5fa6d59e9d0dd42eefcfc2394 | 661,479 |
def parse_country_details(response, pos=0):
"""Parses the country details from the restcountries API.
More info here: https://github.com/apilayer/restcountries
Args:
response (:obj:`list` of `dict`): API response.
Returns:
d (dict): Parsed API response.
"""... | 33c6a0f3430a928ad5e11fd4e150dc0a174cad04 | 661,480 |
from typing import TextIO
from typing import List
import os
import requests
import sys
def fetch_fasta(fh: TextIO, fasta_dir: str) -> List[str]:
""" Fetch the FASTA files into the download directory """
if not os.path.isdir(fasta_dir):
os.makedirs(fasta_dir)
files = []
for prot_id in map(str... | 85071a12e6db62d9595c9516cd857e93a35ae708 | 661,481 |
import torch
def vrender_flo(weights_coarse, xyz_coarse_target, xys, img_size):
"""
weights_coarse: ..., ndepth
xyz_coarse_target: ..., ndepth, 3
flo_coarse: ..., 2
flo_valid: ..., 1
"""
# render flow
weights_coarse = weights_coarse.clone()
xyz_coarse_target ... | c52fb982320fb55d875a1ae930168769d2b769c4 | 661,482 |
def obtain_factorial(x):
"""
Helper function obtain_factorial() for the factorial() function.
Given value x, it returns the factorial of that value.
"""
product = 1
for ii in list(range(x)):
product = product * (ii + 1)
return(product) | 66b576072522d8b21a4bb0b93734f7fff78a21fe | 661,483 |
def get_bg_data(bg_file_path):
""" The function creates two indices:
* bid -> {bg_id1, bg_id2, ...}
* bg_id -> {iid1, iid2, ...}
One booking is assigned to only one cluster
:param bg_file_path: a path to the file containing information about booking clusters
:return: bid -> {bg_id1, bg... | 9dc25180aed4a3c93a303b82701462041bc466f4 | 661,484 |
import torch
def dice_score_tensor(reference, predictions):
"""Computes the dice score for the data and prediction. Tensor shapes are ``[batch, 1, rows, cols]``. The
dice score is computed along the batch and is averaged at the end.
Parameters
----------
reference : torch.Tensor
The refer... | 5267dd960c8ad09831996c9836639c3d4639a645 | 661,485 |
def generate_transformation_wells(spotting_tuples):
"""Evaluates spotting_tuples and returns transformation wells.
Args:
spotting_tuples (list): Sets of spotting reactions are given
in the form: ((source wells), (target wells), (spotting volumes)).
Each unique transformation well is resus... | 7d0ab142a2c429d0d41a990917a8408eff26dbcb | 661,486 |
def get_ascii_from_char(char: str) -> int:
"""Function that converts ascii code to character
Parameters
----------
char : character
character to convert to ascii
Returns
-------
ascii_code : int
Ascii code of character
"""
return ord(char) | 044c0f2d7f9b773edefa89a98db13738f18538d9 | 661,487 |
def get_comments(github_object):
"""Get a list of comments, whater the object is a PR, a commit or an issue.
"""
try:
return github_object.get_issue_comments() # It's a PR
except AttributeError:
return github_object.get_comments() | 8afb6d9c7123d6e54aae686ba908cfae994c9a65 | 661,488 |
def _resolve_subkeys(key, separator='.'):
"""Resolve a potentially nested key.
If the key contains the ``separator`` (e.g. ``.``) then the key will be
split on the first instance of the subkey::
>>> _resolve_subkeys('a.b.c')
('a', 'b.c')
>>> _resolve_subkeys('d|e|f', separator='|')
... | f7b749a0645a71048aaa3ffa693540c97772653a | 661,489 |
import math
def gcd(x, y):
"""
gcd :: Integral a => a -> a -> a
gcd(x,y) is the non-negative factor of both x and y of which every common
factor of x and y is also a factor; for example gcd(4,2) = 2, gcd(-4,6) =
2, gcd(0,4) = 4. gcd(0,0) = 0. (That is, the common divisor that is
"greatest" in... | a3d3e9947ca96de93712efd574a17ee62db59844 | 661,490 |
import re
def problem1(searchstring):
"""
Match phone numbers.
:param searchstring: string
:return: True or False
"""
str_search = re.search(r'^(\S?\d+\W?)\W?(\d+)\-(\d+)',searchstring)
#str_search1 = re.search(r'^(\S\d+\W)(?=(\s|\d)\d+)',searchstring)
#print(str_search)
... | 3b2c2d8bf56516b796bc4757ccae10d35ef507cc | 661,491 |
import re
def setup_time_data_set(
collector_info,
collector,
token_file,
data_group):
"""Using default repeat
>>> token_file = 'abc.txt'
>>> collector = {"some": 'query', "entry_point": "entry.point"}
>>> collector_info = {
... 'credentials': 'credentials/ga.json'... | 92ef58e53b2e82b8ef435ff2af1ce6ac20c50065 | 661,492 |
def cipher(number):
"""cipher the number if not present return number"""
code = {
'1': '9',
'2': '8',
'3': '7',
'4': '6',
'5': '0',
'6': '4',
'7': '3',
'8': '2',
'9': '1',
'0': '5',
}
return code.get(number, number) | 520d528f2e5a9d94451ded2ce711c9dc5f27d1d1 | 661,493 |
def optional_g(text):
"""Method for parsing an 'optional' generalized number."""
if text == '#VALUE!':
return None
if text:
return float(text)
else:
return None | d7212f9611b3451a682bdfc10f0ed6a9e605cf58 | 661,494 |
def rank_as_string(list1, alphanum_index):
"""
Convert a ranked list of items into a string of characters
based on a given dictionary `alph` of the format that contains
the ranked items and a random alphanumeric to represent it.
Parameters
----------
list1 : list
A lis... | c3de9118abe5ead47e9e84e1682b9a16ead0b5fc | 661,495 |
def _get_date_from_filename(filename):
""" Returns date (first part of filename) """
return filename.split("/")[-1].split("_")[0] | 9dd84ef278fbbe48a421a5b708bb09200ef93912 | 661,496 |
def q_normalize(quat):
"""Return a normalized quaternion"""
mag = quat[0] * quat[0] + quat[1] * quat[1] + quat[2] * quat[2] + quat[3] * quat[3]
if mag != 0:
for i in range(4):
quat[i] /= mag
return quat | 89fe5e7c5a1dd466b4a338bde4d0c36894d6f126 | 661,497 |
import string
def _get_normalized_set(vocab):
"""Build set of special token ids to ignore when computing matching metrics.
Args:
vocab: An instance of text_utils.Vocab.
Returns:
remove: A set of wordpiece token indices to ignore.
"""
punct = {vocab.t2i(t) for t in string.punctuation if t in vocab}... | 3224edd40505aa5e971332ee7f8f39c19e07b54f | 661,498 |
def sum_period_pow_worth(copylist):
""" Parse list; Sum Period PoW Worth """
strslash = "/"
j = 0
totalpowworth = 0
for item in copylist:
if (item.__contains__(strslash)):
tmp = copylist[j-1]
totalpowworth += int(copylist[j-1])
j += 1
else:
j += 1
continue
return totalpowwo... | cb4236b3430b172966f1cc27f69b89a114b8f4d4 | 661,500 |
def get_neighbor_address(ip):
"""Get the neighbor address in a subnet /30
Args:
ip (`str`): Ip address to get the neighbor for
Returns:
None
"""
# Get the neighbor IP address
ip_list = ip.split(".")
last = int(ip_list[-1])
ip_list[-1] = str(last - 1) i... | df3118e02c215c8fe4cd029132ed5f70cf08a219 | 661,501 |
def get_n_params(model):
"""
Returns the number of learning parameters of the model
"""
pp=0
for p in list(model.parameters()):
nn=1
for s in list(p.size()):
nn = nn*s
pp += nn
return pp | c8d160293a2870d3550c5e5f9a56e5005fe50ba1 | 661,502 |
import pathlib
import os
import stat
def can_access(path, read=False, write=False, recurse=False):
""" Check whether a file exists and can be read/written, or a directory's subfiles (and subdirectories) can be listed/read/written.
Args:
path Path to a file or directory (or symlink to it)
read Check ... | 6ea4690fd3c55e13fcd547f97c2082fa160b97c5 | 661,503 |
import time
def de_timestr_with_regex_to_timestamp(timestr, regex):
"""
将格式字符串转换为时间戳
:param timestr: 某种格式的输入字符串
:param regex: 正则串
:return: 时间戳
"""
return time.mktime(time.strptime(timestr, regex)) | 13e61618432df030084ffe5a285f7493894a25ea | 661,504 |
def loadPlugin(mod):
"""
Spawn a plugin class given a module object.
Used by loadModule
"""
plugin = mod.Main()
plugin.name = plugin.__module__
plugin.__file__ = mod.__file__
return plugin | 0452cda4b942a547e186bb45e0f5ef9acdcab008 | 661,505 |
def dismissal_reason():
""" Data for fill reason in dismissal blank """
dismissal_reason = {1: 'по соглашению сторон',
2: 'в связи с истечением срока трудового договора',
3: 'досрочно, по требованию работника, в связи с выходом на пенсию'}
# enumerate print f... | 6655388f06a4faf66fece8ee21fc160ca968bacb | 661,506 |
def get_instances(ClassName, arguments, attributes):
"""Get instances of a class with specific attributes
Assumes ClassName is a class type
Assumes arguments is an ordered collection of dictionaries as defined
in the module documentation
Assumes attributes is a list of dictionaries that maps stri... | 0d3a554e4b0f7150905ef45e700ceb656cdfeae5 | 661,508 |
def _remove_field(metadata, field):
"""Remove a certain field from the metadata
Args:
metadata (dict): Metadata to be pruned
field ([string]): Coordinates of fields to be removed
"""
if len(field) == 1:
if field[0] in metadata:
del metadata[field[0]]
else:
... | eaba71615053e3a70b242d1fe60e404aa68da527 | 661,509 |
import re
def getDtbInfo(dtbPath):
"""
Extract information from DTB
"""
pattern = re.compile('^([^-]+)-([^\.]+)\.dtb$')
result = pattern.match(dtbPath)
if result is not None:
return {
'name': dtbPath,
'platform': result.group(1),
'cpu': result.group(... | 4748f85dbbbf7dbf708ef8b8197a40819bb165ff | 661,510 |
def attr(*args, **kwargs):
"""
Decorator that adds attributes to classes or functions for use with the Attribute (-a) plugin.
http://nose.readthedocs.org/en/latest/plugins/attrib.html
"""
def wrap_ob(ob):
for name in args:
setattr(ob, name, True)
for name, value in kwar... | 987fa5f946a99ec6a5ae89495172138ce16343a7 | 661,511 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.