content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def intersect(a, b):
""" Return the intersection of two lists.
Args:
a (list): A list.
b (list): Another list.
Returns (list):
The intersection of the two lists.
"""
# NOTE: Binary operator '&' is built in and returns the intersection of 2 sets.
ret... | b0e0ac8160ed9fc16c27a8352992e64e1612d642 | 670,366 |
def bgr_to_rgb(bgr):
"""Converts Blue, Green, Red to Red, Green, Blue."""
return bgr[..., [2, 1, 0]] | 27e359732cfac4fdf553e1e2445c25fe1d5d8e89 | 670,367 |
import sys
def is_py_39():
"""check if current python version is 3.9"""
return sys.version_info.major == 3 and sys.version_info.minor == 9 | 3994cd84b9bcfc950749900f923e165bdcf90e00 | 670,368 |
def torchcrop(x, start_idx, crop_sz):
"""
Arguments
---------
x : Tensor to be cropped
Either of dim 2 or of 3
start_idx: tuple/list
Start indices to crop from in each axis
crop_sz: tuple/list
Crop size
Returns
-------
cropped tensor
"""
dim = len(x.s... | f7a3ef0eb2e81bb77d194b0e04d8c504979475d7 | 670,369 |
import tempfile
def get_tmpdir():
""" Return the name of the directory used for temporary files, always
without trailing '/'.
Searches a standard list of directories to find one which the calling user
can create files in. The list is:
* The directory named by the TMPDIR environment variable.
... | bf299616ef5c69d92f43d408a5c0fb65224265ba | 670,370 |
def column_sort_key(column):
""" util for sort columns.
"""
if column.endswith('_id'):
return '0' + column
if column.endswith('_masks'):
return '1' + column
return column | 4ddeda321a39dc4679f7d27febba98d4a11f4905 | 670,371 |
import json
async def send_files(route, files, payload, http):
"""Sends files"""
form = []
form.append({'name': 'payload_json', 'value': json.dumps(payload, separators=(',', ':'), ensure_ascii=True)})
if len(files) == 1:
file = files[0]
form.append({
'name': 'file',
... | 1be244a279e33cd15626975621afbf7e2bd594a2 | 670,372 |
def get_next_issue(issues, issue):
"""
A lista de números é ordenada pelos números mais recentes para o mais
antigos, portanto para retornarmos os números mais novos, devemos
caminhar pelo índice do valor maior para o menor, isso justifica
no preview subtrai 1 ao índice.
param: issues é a lista... | 4d6d02a8db9f63e07ff362d369ae3b51fd0cdddc | 670,373 |
import platform
def _OS_check():
"""
"""
if platform.system() == 'Darwin':
return True
else:
return False | 8d1735a839f729db69b7a140391537785722914b | 670,374 |
def cbool(value):
"""
"""
return 1 if value else 0 | 035b237d99ed63c1a7f658161f65f717b09aa8a6 | 670,375 |
def round_int(x, *, ndim=0):
""" 先四舍五入,再取整
:param x: 一个数值,或者多维数组
:param ndim: x是数值是默认0,否则指定数组维度,批量处理
比如ndim=1是一维数组
ndim=2是二维数组
>>> round_int(1.5)
2
>>> round_int(1.4)
1
>>> round_int([2.3, 1.42], ndim=1)
[2, 1]
>>> round_int([[2.3, 1.42], [3.6]], ndim=2)
[[2... | 36bb8dfe22bc1a14c0c882b5b30453ab37890b37 | 670,377 |
def get_river_config(fileName, noisy=False):
"""
Parse the rivers namelist to extract the parameters and their values.
Returns a dict of the parameters with the associated values for all the
rivers defined in the namelist.
Parameters
----------
fileName : str
Full path to an FVCOM R... | 5751456eda34c8f9fc2c134515cc420b156c2d17 | 670,378 |
def update_namespace(tuple_to_update, **updates):
"""
Returns a new namespace with the same properties as the input, but updated with
the given kwargs.
Args:
tuple_to_update (Union([types.namedtuple, typing.NamedTuple])): The tuple object
**updates: Properties to update on the tuple
... | 0308d80973a567deb8db859113c4908346b3fce8 | 670,380 |
def get_roi_coordinates(coordinates, rect):
"""
Translate the general coordinates to the ROI rect
"""
return map(lambda c: [coordinates[c] - rect[0], coordinates[c + 1] - rect[1]],
range(0, len(coordinates), 2)) | bde35f36eb3467d8e58318e7a0932ac3b4cee664 | 670,381 |
def _mock_key(service, method):
"""Key to address a mock object in MockableTransport."""
return '%s::%s' % (service, method) | 70ca03964dfec104cd65ad3f4a554482ffc4a798 | 670,382 |
from typing import Union
from typing import List
def list_over(obj: Union[list, str], n: int) -> List[str]:
"""
Return a list of strings of length greater than n in obj,
or sublists of obj, if obj is a list.
If obj is a string of length greater than n, return a list
containing obj. Otherwise retu... | c6e26a948ad8decb98c68c0d9cc7f42afea7e7cd | 670,383 |
def prune(d):
"""If possible, make the multi-valued mapping `d` single-valued.
If all value sets of `d` have exactly one member, remove the set layer,
and return the single-valued dictionary.
Else return `d` as-is.
"""
if all(len(v) == 1 for v in d.values()):
return {k: next(iter(v)) f... | b0c60b00a5bd47d248f558db6d96b8569b9e94bb | 670,384 |
import re
def read_source_file(file_path, regex):
"""Finds all fluent keys from the supplied source file."""
keys = []
with open(file_path, 'r') as file:
for line in file.readlines():
if line.find("fl!") != -1:
finds = re.findall(regex, line)
if finds:
... | 9c388091c052f68e8636a7ffaa589655538b0b0c | 670,385 |
def fn_check_missing_data(df):
"""check for any missing data in the df (display in descending order)"""
return df.isnull().sum().sort_values(ascending=False) | 831bf7fca1e1a3863f32cb0dbd169064d85f81e2 | 670,386 |
def rotate_square_counter(block, count):
"""
Return a square block after rotating counterclockwise 90° count times
"""
for _ in range(count):
block = [[block[j][i] for j in range(len(block))] for i in list(reversed(range(len(block))))]
block = [''.join(i) for i in block]
return block | f15e39891a2f71c5b65881e57bbe844ef2056ebd | 670,387 |
def recognize(audio, service):
"""
Uses the IBM Speech to Text service to translate the audio file to text.
:rtype: dict with the transcript and confidence for the the most likely alternative for the translated text.
"""
dic = service.recognize(
audio=audio,
model='es-AR_NarrowbandMo... | f6bceb9f2bff354365e7e2f933b51e47d3a884c9 | 670,388 |
def Finish_to_c(self):
"""Syntax conversion for breaking a loop."""
return f"goto break_{self.targetID};" | 0ca45ac96bbeae75c0bbeead4383efa96d3ee00a | 670,389 |
import argparse
def p_val_type(arg):
"""
Checks if p_val is a float within the range {0, 1}.
"""
try:
p_val = float(arg)
except ValueError:
msg = f"P-value '{arg}' is not a floating point number."
raise argparse.ArgumentTypeError(msg)
if not (0 < p_val < 1):
... | f75415714cc1b723de28f3269577b7495bd22f97 | 670,390 |
def parsePersonName(value):
"""
"""
if not value:return None
return value.lower() | b605799c533035cd5f33b5260faee37000d7a94b | 670,391 |
def key_by_id(mapping):
"""
Converts arrays to hashes keyed by the id attribute for easier lookup. So
[{'id': 'one', 'foo': 'bar'}, {'id': 'two', 'foo': 'baz'}]
becomes
{'one': {'id': 'one', 'foo': 'bar'}, 'two': {'id': 'two', 'foo': 'baz'}}
"""
if isinstance(mapping, list) and isins... | 87a6af2e2d0662ce58cc00ad5025acd9359e7f42 | 670,392 |
def _match_tags(repex_tags, path_tags):
"""Check for matching tags between what the user provided
and the tags set in the config.
If `any` is chosen, match.
If no tags are chosen and none are configured, match.
If the user provided tags match any of the configured tags, match.
"""
if 'any' ... | b9434c29679b98810f357282c2b42e4b318a62df | 670,393 |
def parse_csv_data(csv_filename):
"""
This function takes a csv file and returns the data in a list
:param csv_filename: the name of the csv file to be read
:return: the data in a list format
"""
csv_data = []
f = open(csv_filename, 'r')
for line in f.readlines():
splits = []
... | 771041ffae86501f689bb7f70ec3120603518065 | 670,394 |
import torch
def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
"""
A sequence of combined transformations for speed improvement
:param input_a: of shape (*, 2 * n_channels, L)
:param input_b: of shape (*, 2 * n_channels, L)
:param n_channels: IntTensor containing a single item (in... | 8de9ed08c8ae251993358240d14d47fbb715a6c5 | 670,395 |
import string
def isalphanum(word):
"""
This function returns true if a word contains letters or digits
:param word: A string token to check
:return: True if the word contains letters or digits
"""
for char in word:
if char not in string.ascii_letters and char not in string.digits:
... | ca65885ae38437cb22c68ca1b360467fe00e9a84 | 670,396 |
def factor_of_all_upto(num, limit):
""" Returns True if num is divisible by all numbers in the range of integers
in 1 up to and including limit.
# Speed up by skipping 1. Any integer is divisible by 1!
# If the number ends in 1, 3, 7, or 9, it's more likely to be prime.
# Check back... | 9a8f70f32fc05e92c29a75af7068138be88e8bcb | 670,397 |
def read_fp(filename, dtype=int):
""" read fingerprint from file
Args:
filename: <type 'str'>
Return:
chembl_id_list: <type 'list'>, a list of str
fps_list: <type 'list'>, a list of dict.
"""
chembl_id_list = []
fps_list = []
infile = open(filename, "r")
line_num = 0
for line in infile:
... | 29ebee689937a8954aa9f3130bd8b9ee3b0c18fc | 670,398 |
def get_input_dtypes(data):
"""Returns input get_input_dtypes."""
return ('float32','float32') | 7d48c6e36f5f0c030102c51bcab6ec91a9451481 | 670,399 |
def stmt_from_rule(rule_name, model, stmts):
"""Return the source INDRA Statement corresponding to a rule in a model.
Parameters
----------
rule_name : str
The name of a rule in the given PySB model.
model : pysb.core.Model
A PySB model which contains the given rule.
stmts : lis... | 1defd6b6f4f013c3ae5fc41bbda6e271fb6b4d0d | 670,400 |
def reverse_dict(d):
"""
Функция меняет местами ключи и значения в словаре с сохранением всех ключей,
которые указывали на одно и то же значение
Пример: {a: 1, b: 2, c: 1} -> {1: [a, c], 2: [b]}
"""
dinv = {}
for k, v in d.items():
if v in dinv:
dinv[v].append(k)
... | 5d3783a116c52e281b0b7c32b3b831f2bb66634d | 670,401 |
import string
import random
def get_alphanumeric_string(str_length, **kwargs):
"""Get random alpha numeric string, default is lowercase ascii chars
Available kwargs (in order of precedence*):
uppercase_only = default is False
mixed_case = default is False
digits_only = default is Fals... | 0242a3ad9c7fec2a9a1b068d9ebccf3db1fa5a5a | 670,402 |
import mpmath
def mode(p, b, loc=0, scale=1):
"""
Mode of the generalized inverse Gaussian distribution.
The mode is:
p - 1 + sqrt((p - 1)**2 + b**2)
loc + scale -------------------------------
b
"""
p = mpmath.mpf(p)
b = mpmath.m... | 7091cf76ba01c8c7e388f82a112fc207f5cdeae7 | 670,403 |
def whilst(b, x):
"""
Like using a takewhile in comprehensions. It aborts the remainder
of the iterable.
But unlike a StopIteration, the remaining other loops continue.
>>> from itertools import takewhile
>>> [(x,y) for x in takewhile(lambda x:x<3,range(10))
... for y in takewhile(lambda y... | 4e7fdd88ac476a2c65256fff86350e6c7457148f | 670,404 |
def wrap_type_blink(return_type, type_registry):
"""Returns True if the type is a blink type that requires wrap_jso but
NOT unwrap_jso"""
return (return_type == 'Map' or return_type == 'Rectangle') | 724f51f11a9fb340b4d4f7a4c18afcbc077f35a7 | 670,405 |
import torch
def kl_divergence_mc(
q_distrib: torch.distributions.Distribution, p_distrib: torch.distributions.Distribution, z: torch.Tensor
):
"""Elementwise Monte-Carlo estimation of KL between two distributions KL(q||p) (no reduction applied).
Any number of dimensions works via broadcasting and correc... | 1a1c0a14f13f4ed705608f37b2c4f00f67a1cbaa | 670,406 |
def _get_test_type(item):
"""
Gets the test type - unit, functional, integration, based on the directory that the test is in.
"""
return item.nodeid.split('/')[1] | 54e01a182042d9a3db9942843ee85108a4d27547 | 670,407 |
def to_camel(m):
"""Convert to camel case."""
return m.group(1).Upper() | 5fe5a8bef590dc205863bc0e73558fc003e6c66a | 670,408 |
def _dummy_get_parameter(tree_info, extra_config):
"""
Dummy function used to return parameters (TreeEnsemble converters already have parameters in the right format)
"""
return tree_info | 9d30a08177d04de84070db0778772b23efa15e2a | 670,409 |
def bubble_sort(a: list):
"""Optimized Bubble sort that return sorted list with O(n^2) complexity"""
a, n = a.copy(), len(a)
for _ in range(n):
is_swap = False
for i in range(1, n):
if a[i-1] > a[i]:
is_swap = True
a[i-1], a[i] = a[i], a[i-1]
... | da200df35cad0856c2b290a1119a1ccea9f6ce03 | 670,410 |
def calc_bfdp(bf, prior):
"""
Calculate BFDP for a single gene per Wakefield, AJHG, 2007
"""
# Wakefield phrases prior as probability of no effect, so we need to invert
prior = 1 - prior
po = prior / (1 - prior)
bftpo = bf * po
bfdp = bftpo / (1 + bftpo)
return bfdp | d2da81abb009b70c45b7fdcc43ee48220f25526a | 670,411 |
import time
def parseDateCol(df, date_col):
""" takes the date column and adds new columns with the features:
yr, mon, day, day of week, day of year """
df['datetime'] = df.apply(lambda x : time.strptime(str(x[date_col]), "%Y%M%d"), axis = 1)
print('parsing year')
df['year'] = df.apply(lambda x : x['datetime']... | 217ae6f9c66ed3e9ec721c91a2367cea7642689e | 670,412 |
def fnsplit(fn):
"""/path/fnr.x -> (/path/fnr, x) when possible. Non-str treated as None."""
if not (isinstance(fn, str) and fn):
return (None, None)
fn = fn.strip()
if not fn:
return (None, None)
x = fn.rfind('.')
if x == -1:
return fn, None
return (fn[:x], fn[x:]) | c2813b4ded84d7121ad45532e36c97dbd8463aaa | 670,413 |
def pluralize(s, count):
#===============================================================================
"""
Return word with 's' appended if the count > 1.
"""
if count > 1:
return '%ss' % s
return s | 2587ee2fe4ea7d8405345572acd9d0fe01a6aa15 | 670,414 |
import os
def isxml(path):
"""Is the given file an xml file?"""
(filename, ext) = os.path.splitext(path)
if ext.lower() in ['.xml']:
return True
else:
return False | 2f7c4edbb35319bf07e8b18122eeccded133d224 | 670,415 |
def isfile_s3(bucket, key: str) -> bool:
"""Returns T/F whether the file exists."""
objs = list(bucket.objects.filter(Prefix=key))
return len(objs) == 1 and objs[0].key == key | e5ded8c24764a0d8d0c9b84aa96ee16db688c8c1 | 670,416 |
def _get_attribute_dict(clazz, excluded=set()):
""" Return dictionary of non-static members and their values for an instance of class
Args:
clazz ([type]): object instance of a certain class
excluded (set): names of member attributes which are excluded from dictionary}). Defaults to set().
... | b5504b9003eeddbe17a9385832284509298982bf | 670,417 |
import re
def find_doi(input):
"""
checks if the doi of an article is syntactically correct or empty
:param input: doi of an article
:return: correct doi if found, otherwise None
"""
if input is None:
return None
regex = r"(\d\d\.\d+\/\S+)"
regex = re.compile(regex)
m = reg... | 585fb8c3d503104384c5cf14c0b0cc3655468e5f | 670,418 |
def filepaths(filesets):
""" Return a list of filepaths from list of FileSets """
filepaths = []
for fs in filesets:
filepaths += fs.files
return filepaths | 4fa6efea0ebf9bc49ababf050fa38d549770045b | 670,419 |
def agent_slot(occupants, a_id, t):
"""Return the slot agent with id a_id occupied in round t,
or -1 if a_id wasn't present in round t"""
agents = occupants[t]
if a_id in agents:
return agents.index(a_id)
else:
return -1 | c38b0e77276cdc35d1dfbd99a306cd31af5f7704 | 670,420 |
import os
def getFileListOnPath(path: str, filterExtension="") -> list:
"""Returns list of files in path"""
fileList = []
# Get list of all files
for item in os.listdir(path):
if os.path.isfile(os.path.join(path, item)):
if item.endswith(filterExtension):
fileList... | d4d80ced7a411083998dfea75cce88857d1d981a | 670,423 |
def __ensure_suffix(t, suffix):
""" Ensure that the target t has the given suffix. """
tpath = str(t)
if not tpath.endswith(suffix):
return tpath+suffix
return t | 392bf04404e2d739c676ede578410db34d232789 | 670,424 |
def is_clockwise(ring_to_test):
"""
A clockwise ring means it is an outer ring; counter-clockwise means the opposite.
For determining the direction of a ring, we need to calculate the sum of the areas under each side.
A positive sum indicates a clockwise polygon. See here for more info:
http://stack... | de884d2695227e812c6b8aa183ac47f7aef9b41a | 670,425 |
import logging
def get_hypervisor_for_guest(nova_client, guest_name):
"""Return the name of the hypervisor hosting a guest.
:param nova_client: Authenticated nova client
:type nova_client: novaclient.v2.client.Client
:param vm_name: Name of guest to loohup
:type vm_name: str
"""
logging.i... | 37774dab5121bcb7a6bb8ad0e45461628ddae728 | 670,426 |
def workflow_basedir(workflow_id: str) -> str:
"""Get base directory containing associated files for the workflow with
the given identifier.
Parameters
----------
workflow_id: string
Unique workflow identifier
Returns
-------
string
"""
return workflow_id | f63b1a304056afd5709436f7f003b4aac59245dd | 670,428 |
import torch
def weight_convolution(conv_weights:torch.Tensor, in_channels:int, out_channels:int, scaling_factor:int, kernel_size:int = 3, padding:int = 1):
"""
Weight Convolution - coded for clarity, not speed
kernel_size:int - the size of the convolution kernel, K ... the deconvolution kernel size = r ... | fc560271dc09a51e19109082e0ab85cdd2e735de | 670,429 |
def _numlines(s):
"""Returns the number of lines in s, including ending empty lines."""
# We use splitlines because it is Unicode-friendly and thus Python 3
# compatible. However, it does not count empty lines at the end, so trick
# it by adding a character at the end.
return len((s + 'x').splitline... | 440f4b2ae03e4b77d057bc01443e6c8f1c83c318 | 670,430 |
import unicodedata
def normalize(text):
"""Resolve different type of unicode encodings / capitarization in HotpotQA data."""
text = unicodedata.normalize('NFD', text)
return text[0].capitalize() + text[1:] | e7f245cadf8c1474aa937d43aaeca4e46dbf7d83 | 670,431 |
import requests
def get_drip_resources(URL='https://beta-gc2.datadistillery.org/api/v1/sql/bcb?q=select * from drip.dripdams'):
"""Export of known dam removals from data distillery
Parameters
----------
URL : str
Built query for GC2.
"""
try:
r = requests.get(URL)
if r... | bc6b1d26a98c904f447beb79e5b507a716d86614 | 670,432 |
def fcntl(fd, op, arg=0):
"""Perform the requested operation on file descriptor *fd* (file objects providing
a :meth:`fileno` method are accepted as well). The operation is defined by *op*
and is operating system dependent. These codes are also found in the
:mod:`fcntl` module. The argument *a... | c84d47b6890ad80f673452db0394dd4caa20dbcc | 670,433 |
def feature_results(correlation, chi2, rfe, boruta):
"""
Return a list which has passed for three testes
correlation = set of result from corrrelation teste
chi2 = set of features which has passed from chi2 teste
rfe = set of features which has passed from rfe teste
boruta = set of features whic... | 6c05016162f4c4a35c36355b1ff8be95a61e2ac0 | 670,434 |
def get_second_offset(time):
"""
Get second offset from time.
@time: Python time object in 24 hour format.
"""
return time.hour * 3600 + time.minute * 60 + time.second | 80ead4d1a7ca4942eb5ce0980488880f60b32b75 | 670,436 |
def tan(x):
"""
[Definition] x的正切函数
[Category] 三角函数
Notes:np.nan seems not to check domain of definition!
"""
return 'tan(%s)' %x | dcb9aee5a3b879f88bb9d476b74b5bd27168a47d | 670,437 |
import uuid
def new_iid():
"""Called by the websetup to get a unique uuid for the application iid."""
return uuid.uuid4().hex | c60cc679e68388747c3c1fede72c6a585d63696b | 670,439 |
def num(s):
"""
convert a string to integer or float
:param s: a string of number
:return: an int or float type number
"""
try:
return int(s)
except ValueError:
return float(s)
else:
raise ValueError('Expected integer or floating point number.') | 8d2585ae0c53dfd27f75edef59bab67e68293fc2 | 670,440 |
def skip_these_vars():
"""
Returns a list of variables that should not be read by GCPy.
These are mostly from the MAPL v1.0.0 cubed-sphere files,
which introduce extra dimensions that are not easily handled
by xarray and/or GCPy.
Example:
-------
>>> from gcpy import core
>>> import... | 6c9bdf0bec515cdd082c86ccfa7bf48b6b8c734b | 670,441 |
def normalize_typename(typename: str) -> str:
"""
Drop the namespace from a type name and converts to lower case.
e.g. 'tows:parks' -> 'parks'
"""
normalized = typename
if ":" in typename:
normalized = typename.split(":")[1]
return normalized.lower() | 360b0341e9c7adc3741466855b15925b8ca191ba | 670,442 |
def xyzw2wxyz(xyzw):
"""Convert quaternions from XYZW format to WXYZ."""
x, y, z, w = xyzw
return w, x, y, z | 6a092c0f6075c5d14198a7d092cb6b30a1fb0754 | 670,443 |
def all_subsets(lst):
"""Metoda na vsechny podmnoziny"""
#vlozime si na zacatku prazdnou mnozinu
set = [[]]
#Iterujeme kazdy prvek z listu
for x in lst:
#iterace vsech podmnozin
for y in set:
# pridani nove podmnoziny skladajici se z podmnoziny a prvku listu
s... | ce7ae01d400003ab2022a631c0d2a023e0388b15 | 670,444 |
def check_related_lot_status(tender, award):
"""Check if related lot not in status cancelled"""
lot_id = award.get('lotID')
if lot_id:
if [l['status'] for l in tender.get('lots', []) if l['id'] == lot_id][0] != 'active':
return False
return True | 6b4aeb76ee938de434f646913a196162e903df8e | 670,445 |
def decode_rle(input):
"""
Gets a stream of data and decompresses it
under a Run-Length Decoding.
:param input: The data to be decoded.
:return: The decoded string.
"""
decode_str = ""
count = ""
for ch in input:
# If not numerical
if not ch.isdigit():
# ... | 25de4f7756aefdfedfd3779040918f8b58c14d19 | 670,446 |
def load_parameters(simpa, growth_speed: float):
""" Add all parameters to one dictionary
"""
simParameters = simpa.simParameters
simParameters['growth_rate_one'] = growth_speed/(60*simpa.dL_dimer) #rate of one dimer per s
return simParameters | a08b4e2b82ab64f902f58120183cf90850a1c24e | 670,447 |
def check_analysis_type(options):
"""Determines what type of analysis to do based on the command line options."""
if options['cterm_models']:
analysis_type = 'cterminus'
else:
analysis_type = 'nterminus'
return analysis_type | cb106cea727b5a83f93235ab47a8c6b27256cccf | 670,448 |
import itertools
def flatten(list_of_lists):
"""Flatten one level of nesting."""
return itertools.chain.from_iterable(list_of_lists) | 1019d7f084e7d01db5e49e455123811dfae1ee2f | 670,450 |
import six
def get_model_label(model):
"""
Take a model class or model label and return its model label.
>>> get_model_label(MyModel)
"myapp.MyModel"
>>> get_model_label("myapp.MyModel")
"myapp.MyModel"
"""
if isinstance(model, six.string_types):
return model
else:
... | 3031b8facf621b266328917dc5cd49c94856e6a9 | 670,451 |
import os
def schema_path(schema):
""" Get a filesystem path for the named database schema
Args:
schema: Name of the database schema.
Returns:
A filesystem path pointing at a ".sql" file.
"""
dir_path = os.path.dirname(__file__)
schemaPath = os.path.join(dir_path, "schema", s... | c47ec4123a9417fe74f36c597b72d77c5436a095 | 670,452 |
def fst(ls):
"""returns the 0th element of a list"""
return ls[0] | a44d5b883be2117f9dc26be3cedac8f8e4356471 | 670,453 |
import os
def search_path():
"""Get the search directory."""
curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))
ver_path = [os.path.join(curr_path, '../../../verilog/')]
ver_path += [os.path.join(curr_path, '../../../tests/verilog/unittest/')]
ver_path += [os.path.join(curr... | fdc4077d0d818f99239a52216748088e6d5094b9 | 670,454 |
def ready():
"""Return a JSON object that identifies if the service is setupAnd ready to work."""
return {'message': 'api is ready'}, 200 | 70e49bc8f8a828f578df37d53ac898445f41a128 | 670,455 |
import os
def check_path(path):
"""Check path.
Args:
path: path.
Return:
real path
Raise:
if path is valid or not read and write permissions.
"""
if os.path.exists(path):
real_path = os.path.realpath(path)
if not os.path.isdir(real_path):
raise ValueError("path:%s is not di... | 80506b3023bb427e30ddc5dc56c1a414847cbb7f | 670,457 |
import os
import subprocess
def extract_tar_gz(file, output_dir="./models"):
"""
Extract a .tar.gz
Parameters
----------
output_dir (default="./models"): Where to extract the .tar.gz
Returns
------
output_dir: full path to the output directory where files where extracted
... | 260b547548b80a43abcf5082ddb559d55475bd32 | 670,458 |
def get_camera_from_topic(topic):
"""
Returns the camera name given the image topic.
"""
topic_split = topic.split('/')
return topic_split[2] | 63e773b45457e99c911941b39be1854668f877df | 670,460 |
def is_implosive(sound):
"""
This groups stops and affricates into a group of sounds.
"""
return sound.manner in {"implosive"} | 790c4b2edcf63b0c5c13b51228558411920e0b20 | 670,461 |
from pathlib import Path
import json
def read_parameters(parameters_file: Path):
"""This function reads the config file containing the parameters needed for filtering datasets."""
if parameters_file.exists():
with open(parameters_file) as fout:
parameters = json.load(fout)
else:
... | 6f7c1e1fb5a97504669f1c2414505507dc74ad74 | 670,462 |
def extract_sentences(nodes, token_node_indices):
"""
given a list of ``SaltNode``\s, returns a list of lists, where each list
contains the indices of the nodes belonging to that sentence.
"""
sents = []
tokens = []
for i, node in enumerate(nodes):
if i in token_node_indices:
... | 66231805def7aa1560fdb47965c4ef773431a5b1 | 670,463 |
def extract_parts(usage):
"""Extract individual components from a usage string"""
opp = {'{': '}', '[': ']', '(': ')'}
cur_word = []
tokens = []
stack = []
for c in usage:
if c.isspace() and not stack:
if cur_word:
tokens.append(''.join(cur_word))
... | de4040207d06fd309bea14260f2ef03ac5dc2e5a | 670,464 |
def fix_on_create_nodes(node):
"""
Helper function to create the correct cypher string for
querying and merging a new node to the graph. This is used
when no node is matched and a new one has to be created.
Input:
- node: dic,
dictionary of a node generated from some create_neo4j_
... | c51c118f1a50347670af6aa74fcc5b10c0baa700 | 670,465 |
def array_chunk(array, size):
"""
Given an array and chunk size, divide the array
into many subarrays, where each subarray is of
length size.
array_chunk([1,2,3,4], 2) --> [[1,2], [3,4]]
array_chunk([1,2,3,4,5], 2) --> [[1,2], [3,4], [5]]
"""
counter = 0
outer_list = []
inner_lis... | 7ec1e40c8306dc256387292421474ee9e037568b | 670,466 |
def reim(b):
"""
function to split into 2 arrays real part and imaginary part of complex array
"""
return ([z.real for z in b],[z.imag for z in b]) | 2764ee83b4fbef6631069400790bf8ffab618238 | 670,468 |
def time_minutes(dt):
"""Format a datetime as time only with precision to minutes."""
return dt.strftime('%H:%M') | 93288a8f0204dd56c59b18b75c62a5c1e059e159 | 670,469 |
import re
def offset(text):
"""Returns index of first non-whitespace character.
Args:
text (str): string to be analyzed for whitespaces.
Returns:
index (int): index of first non-whitespace character; -1 if none found.
"""
index = 0 # Assume first character is not a whitespace
... | 4dc17c73dd5098e56c12781f1aafc7816ddba0a5 | 670,470 |
import itertools
def save_v2_timecodes_to_file(filepath, timecodes):
"""
:param filepath: path to file for saving
:param timecodes: list of timecodes of each frame in format
[timecode_of_0_frame_in_ms, timecode_of_1_frame_in_ms, ... timecode_of_i_frame_in_ms]
:return: file object (closed)
... | d5ad02c7f26dbf2ebeb25740604f2bfa803ffb4f | 670,471 |
def WithChanges(resource, changes):
"""Apply ConfigChangers to resource.
It's undefined whether the input resource is modified.
Args:
resource: KubernetesObject, probably a Service.
changes: List of ConfigChangers.
Returns:
Changed resource.
"""
for config_change in changes:
resource = co... | 4e0db8a71b24146e0ef5d18c65e71ac12e500fef | 670,472 |
def dummy_equals(dummy1, dummy2):
"""
Yet another dummy function.
Parameters
----------
dummy1 : int
The first dummy parameter.
dummy2 : int
The second dummy parameter.
Returns
-------
bool
True if dummy1 equals dummy2, False otherwise.
"""
return d... | d44f8543b9a6761e0538e6c18cd065b353f66f2f | 670,473 |
import torch
def make_grid(grid_size, grid_offset, grid_res):
"""
Constructs an array representing the corners of an orthographic grid
"""
depth, width = grid_size
xoff, yoff, zoff = grid_offset
xcoords = torch.arange(0., width, grid_res) + xoff
zcoords = torch.arange(0., depth, grid_res... | 832dfb79e64ed768e22b86a525afaef8131eee80 | 670,475 |
import binascii
def encode(bs):
"""Given a bytes object, return a Base64-encoded version of that object, without
newlines."""
return binascii.b2a_base64(bs, newline=False).decode("utf-8").rstrip() | c19d4c93df608ec1656c846e163cbfe726bbb219 | 670,476 |
import re
def is_tns_name(name: str):
"""
Checks if a string adheres to the TNS naming scheme
"""
return re.match("^AT|SN(19|20)\d\d[a-z]{3,4}$", name) | 5d003431aa35946b4dcf4ab918a4e2d92428af75 | 670,477 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.