content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import argparse
def get_parser():
"""
Returns the parser for the command line tool.
:return: parser
:rtype: argparse.ArgumentParser
"""
parser = argparse.ArgumentParser(description = 'MNIST initialization and normalization benchmark.')
parser.add_argument('-epochs', dest = 'epochs', type... | 9518b530f6202aa12e725787d112ef6c13b7f415 | 641,295 |
def to_rgba(x):
"""returns the four first values of last dimension"""
return x[..., :4] | abd5eff0904e5dfd666f06b5b15f0f5e5bc4841a | 641,296 |
def uuid_ints_to_uuid_str(uuid: tuple[int, int, int, int]):
"""Return a string representation given the 4 integer UUID representation."""
usc = tuple(hex(i % 2 ** 32)[2:10].zfill(8) for i in uuid)
return '-'.join([usc[0], usc[1][0:4], usc[1][4:8], usc[2][0:4], usc[2][4:8] + usc[3]]) | 4969e68bb459e3434f6d6e3840b2e9ecdc8ee7ca | 641,297 |
def _B36Check(b36val):
"""
Verify that a string is a valid path base-36 integer.
>>> _B36Check('Aa')
'aa'
>>> _B36Check('.')
Traceback (most recent call last):
...
ValueError: invalid ...
"""
int(b36val, 36)
return str(b36val).lower() | 4ab5b87c6725ac47eee77cb7b44981c9809f537f | 641,299 |
import requests
from bs4 import BeautifulSoup
def crawl(url):
"""Crawl a specific url and return the soup.
"""
req = requests.get(url)
req.encoding = 'utf-8' # force utf-8 encoding
soup = BeautifulSoup(req.text, 'html.parser')
return soup | 5ec6a26d046a6f8bba3d14b9202f811008cbf0fd | 641,300 |
from datetime import datetime
def date(date):
"""DokuWiki returns dates of `xmlrpclib`/`xmlrpc.client` ``DateTime``
type and the format changes between DokuWiki versions ... This function
convert *date* to a `datetime` object.
"""
date = date.value
return (datetime.strptime(date[:-5], '%Y-%m-%... | d0762991946847a3de4d392d3b1ae80880b7c6fe | 641,301 |
def geometry_section(section_name):
""" Class decorator adding static property @section_name with the input value to a decorated class
"""
def modifier(cls):
cls.section_name = section_name
return cls
return modifier | 98368650fe0dd99eff3a786c9d1efd71f0c63d38 | 641,302 |
def scanning_title_provider(body):
"""Get the title of a page from its content body.
This implementation does not use a standard xml parser. Instead, it scans
the body text looking for content between <title> and </title>. This adds
the benefit of working with invalid, or non-standard, xhtml content.
... | 88b3ee2979bd6ce066cfbcc6c69c14ce3fce2f7b | 641,304 |
import torch
def generate_embedding(bert_model, labels):
"""Generate bert's embedding from fine-tuned model."""
batch_size, time = labels.shape
cls_ids = torch.full(
(batch_size, 1), bert_model.bert_text_encoder.cls_idx, dtype=labels.dtype, device=labels.device)
bert_labels = torch.cat([cls_i... | 01e91afc59467afff9f54d99af2671d0c37d9eeb | 641,305 |
def file_to_list(filename: str) -> list:
""" Reads a file and returns a list with the cotent of each line. """
with open(filename, "r") as filehandler:
content = [line.strip() for line in filehandler.readlines()]
return content | ce67d07d8959cf818f63fe562a035c9535e2dd7a | 641,306 |
def _PasswordName(user):
"""Returns the name of the password file for the specified user.
"""
return "{0}_pwd".format(user) | 4769276583ecace1570b6fc3c2c9c0f579b4c5ba | 641,307 |
def add_and_rebound(v: float, delta: float, m: float, M: float) -> float:
"""Rebound from walls."""
mutated_v = v + delta
if mutated_v > M:
return 2 * M - mutated_v
elif mutated_v < m:
return 2 * m - mutated_v
else:
return mutated_v | f64130550fdfc13931b3fc6e36987e659f622f06 | 641,308 |
def param_dist():
"""Generate standard parameters for testing CMR-D."""
param = {
'B_enc': 0.5,
'B_start': 0,
'B_rec': 0.8,
'Lfc': 1,
'Lcf': 1,
'P1': 0,
'P2': 1,
'T': 10,
'X1': 0.05,
'X2': 1,
}
return param | 90ed165ae117ab184218e461b2d4784ea0d0bdd8 | 641,309 |
def _get_prefix(concept1, concept2):
"""
Build a Concept UI prefix as the combination of the
UI prefixes of two concepts.
:param Concept concept1: The first concept.
:param Concept concept2: The second concept.
:returns: New prefix
:rtype: str
"""
# ["NMCD_NMCD", "DSLD_NHP"]
pr... | 38ab07aad98315a20ed61e9bad13ba817c6f5a00 | 641,310 |
def szcodes():
"""
Return dictionary of 7-Zip error codes.
"""
szc = {
0: "NO ERRORS",
1: "COMPLETED WITH WARNINGS",
2: "FATAL ERROR",
7: "COMMAND LINE ERROR",
8: "OUT OF MEMORY ERROR",
255: "USER STOPPED PROCESS"
}
return szc | 4b250c16182668123d8cb71980ab711b7a2540d1 | 641,311 |
import inspect
def get_caller(decorators=0):
"""return the name of the calling class/module
Arguments
---------
decorators : int
Number of contexts to go up to reach calling function
of interest.
Returns
-------
mod : object
The calling module/class
"""
f... | 4c12f70eefb2fd4a2e1f5038f1c85fca30b0cdbd | 641,312 |
def gen_startend(corpus):
"""
Three or four letter strings that start or end words like ant-, aard-,
-azy, or -gist.
"""
begins = {}
ends = {}
def add(store, partial_word):
"""register the partial word and keep a count."""
store.setdefault(partial_word, 0)
store[par... | c0a037acbdf4b6df7b10bb698e0ec446bcf5ce67 | 641,313 |
import platform
import unittest
def skip_unless_has_memory_collection(cls):
"""Class decorator to skip tests that require memory collection.
Any test that uses memory collection (such as the resource leak tests)
can decorate their class with skip_unless_has_memory_collection to
indicate that if the p... | d53c69b42503bd478f6a2322050aafe7eb8006bc | 641,314 |
def union(*items):
""" union(*items) → Return the set-union of the contents of all non-`None` arguments """
return set().union(item for item in items if item is not None) | 942998e782b503a96cbd6ab23843adc322309df8 | 641,315 |
def user_input():
""" Takes user input and create URL """
billboard = "https://www.billboard.com/charts/hot-100/"
date_year = input(f"Where would you like to travel?\nType the date "
f"YYYY-MM-DD: ")
date_month = input(f"Month in Numbers: ")
date_day = input(f"Day in Numbers: "... | 826d6588c580227fac4ca238a7b5c801534a45f1 | 641,317 |
def definition():
"""
Basis for a report which summarises planned student numbers.
Some field aliases are a bit strange simply for backwards compatibility with
a pre-existing web report.
"""
sql="""
SELECT v.acad_year,
v.session,
v.fee_cat as summary_description,
a.pat... | f530be2a25e9dd642b4d88ffae19cef4d7f090d7 | 641,319 |
def array_reverse(a):
"""
Reverses an array
"""
# Time O(n)
# Space O(n)
return a[::-1] | 38e84ca4995b7c1eaa30b358a6717a43fb9c604f | 641,321 |
def home_page():
""""Shows homepage"""
html = """
<html>
<body>
<h1>Home Page</h1>
<p>Welcome to my simple app!</p>
<a href='/welcome'>Go to welcome page</a>
</body>
"""
return html | 55c37603e109f107fe64b63d80153ba698c6cc43 | 641,322 |
def kebab_case(instr):
"""Convert a snake case string to kebab case."""
return instr.replace("_", "-") | 5c9e8a47a584b159689182f3be5c310370d39d6a | 641,323 |
def always_underloaded_factory(time_step, migration_time, params):
""" Creates an algorithm that always considers the host underloaded.
:param time_step: The length of the simulation time step in seconds.
:type time_step: int,>=0
:param migration_time: The VM migration time in time seconds.
:typ... | fb6e2f5d90417c5f07572e708a06e5a619034f7b | 641,324 |
import re
def findNameReferences(input):
""" Find references like {<something>=*.name} in the 'input'-string,
and retrieve all values for '*' """
# In the input-string, search for a '=', possibly followed by some
# whitespace, followed by a '{', possibly followed by some
# whitespace, an argumentname and a '.v... | 152d22ebe26663c1a68b647b05c1a0a56cc8bd0a | 641,325 |
import os
def get_list_scans(start_path, print_structure=True):
"""
Given a path containing scans (pfo_study) or sub-scans (join(pfo_study, 'pdata')),
finds the list of the names of the scans.
:param start_path: path to the folder containing scans or sub-scans.
:param print_structure: [True] optio... | 5132c9e7d266c109fe385aed10b192a3e2f1d040 | 641,326 |
import sys
import os
import subprocess
def install_package(package, upgrade=False, target=None):
"""Install a package on PyPi. Accepts pip compatible package strings.
Return boolean if install successfull."""
# Not using 'import pip; pip.main([])' because it breaks the logger
args = [sys.executable, '... | 550d1d3b8eec00a4dfd036beab98e23f82d615c9 | 641,327 |
from unittest.mock import call
import re
def is_release() -> bool:
"""Return if current branch is a release branch."""
tag_name = call("git describe --tags").replace("\n", "")
return re.match(r"^v\d+\.\d+\.\d+$", tag_name) is not None | f3eb14cdf279ff0b974b7ae16b4f430364fd50d5 | 641,328 |
def str_replace(s: str, dic: dict):
"""多值替换
str_replace('abcd', {'a': '8', 'd': '88'})
"""
return s.translate(str.maketrans(dic)) | d900ac79a65e78e48370c6bb48c5539f1587757a | 641,329 |
def get_model_field(model_name):
"""
获取model 指定字段的 verbose_name属性值
"""
field_dic = {}
for field in model_name._meta.fields:
field_dic[field.name] = field.verbose_name
return field_dic | 07ebed3ad7f8e87097d35611ad500fd363f9700f | 641,330 |
import argparse
def parse_args():
"""Parse input arguments."""
parser = argparse.ArgumentParser(
description='Weather Prediction arguments')
parser.add_argument('--RUN', dest='RUN_MODE',
choices=['train', 'test'],
type=str, required=True)
parse... | feae2beb779c6ef0f8af2bcfadd8b79a37cb3c50 | 641,331 |
import base64
def decode_base64(data):
"""Decode base64, padding being optional.
:param data: Base64 data as an ASCII byte string
:returns: The decoded byte string.
"""
missing_padding = len(data) % 4
if missing_padding:
data += b"=" * (4 - missing_padding)
return base64.urlsafe_... | 3d3fef2ef9b6e8092ef73ff6b9a282e890dd5c88 | 641,332 |
def supplement_area(gdf, field_name):
"""Supplement roof edge area attribute.
Args:
gdf (geopandas.GeoDataFrame): Target GeoDataFrame.
field_name (str, optional): Roof edge area field's name.
Returns:
geopandas.GeoDataFrame: GeoDataFrame of complement area attribute.
"""
are... | 023b3102c03102a9f1772bf6d0bcdc6d5116258d | 641,333 |
def repo_exists(github_repos, repo_slug):
"""Checks if a repository with a given slug exists among the public GitHub repositories.
Args:
- github_repos: List of GitHub repositories.
- repo_slug: Repository slug (usually in a form of path with a namespace, eg: "username/reponame").
Returns:
... | d245912d9e3a5df342a3e8077cff79c9c27f1d3e | 641,334 |
def get_sum(limit = 1000):
"""Gets the sum of the multiples of 3 or 5"""
sum = 0
for n in range(1, limit):
if n % 3 == 0 or n % 5 == 0:
sum += n
return sum | 9891fdf149cdba2cdc800ac3ec9e0b53d99b9b3e | 641,335 |
async def demo_handler(request, *args):
"""
Test of docstring
And here is the description
"""
return "" | b056d8467da76beace141faa6979570e0183fd6b | 641,336 |
def checkfuncname(b, frame):
"""Check whether we should break here because of `b.funcname`."""
if not b.funcname:
# Breakpoint was set via line number.
if b.line != frame.f_lineno:
# Breakpoint was set at a line with a def statement and the function
# defined is called: d... | 1aa8f757613efbfbbe0e1d0593a4cb34e008939d | 641,337 |
def _strip_suffix(service_name):
"""
Strip ".service" suffix from a given service name.
"""
return service_name[:-8] | f13f6e5eb82c38466e4b0657e1eefe0abb429139 | 641,338 |
from typing import Dict
from typing import Any
import importlib
import inspect
def _deserialize_from_settings(mod_name: str, class_name: str, settings: Dict) -> Any:
"""Deserialize an object from its settings.
Args:
mod_name: Name of the module.
class_name: Name of the class.
settings... | 9805020a60bf7a53c8f6b9e526dddec56ff6d545 | 641,339 |
import re
def is_valid_password(password):
"""
- min length is 6 and max length is 25
- at least include a digit number,
- at least a upcase and a lowcase letter
- at least a special characters
:return bool:
"""
pattern = re.compile('^(?=\S{6,25}$)(?=.*?\d)(?=.*?[a-z])(?=.*?[A-Z])(?=.*... | 6dfa4fbea6bde6c3cf66f8705a50a0042f9f073c | 641,340 |
def monta_lista_base(lista_ref):
"""A partir de uma lista_ref constrói uma nova lista
de mesmo tamanho e elementos None
Args:
lista_ref (list): lista de referência para o tamanho da nova lista
Returns:
[list]: lista com elementos None com mesmo tamanho de lista_ref
"""
return ... | 1ab395059bac4aec09480a7d01404a827acd8f1d | 641,341 |
from textwrap import dedent
def split_docstring(docstring):
"""
Split a docstring into a summary and a description.
Arguments:
docstring (str): the docstring
Returns:
summary (str or None): a one-line summary.
description (str or None): the multi-line description.
"""
... | 0d8d74a0629864757aa294ab967570ba508fdd32 | 641,342 |
def csv_format_smono(smono_bounds):
"""flattens and formats suppressed monomial bounds for CSV file"""
smono_flat = []
for sm in smono_bounds:
for bound in sm:
smono_flat += bound
return smono_flat | 9418edeecbcd63bc0a0a3ef523075056f4f5422a | 641,343 |
from typing import Set
from typing import Tuple
def diff_two_set(first: Set, second: Set) -> Tuple[set, set]:
"""Get two set difference tuple.
:return: Tuple[(first - second), (second - first)]
"""
return first.difference(second), second.difference(first) | b93bf60acfc9f5a6c7578b4f7a59ed0d18e1e820 | 641,344 |
import numpy
def symmetrize(m, use_triangle='lower'):
"""Symmetrize a square NumPy array by reflecting one triangular
section across the diagonal to the other.
"""
if use_triangle not in ('lower', 'upper'):
raise ValueError
if not len(m.shape) == 2:
raise ValueError
if not (m.... | 9405fb07973ba50aa14b7dc64d69270e26a7e2af | 641,345 |
def implicitConstraint(self):
"""
Evaluates the constraint function @ a given point ($\vec(x)$)
@ In, self, object, RAVEN container
@ Out, g(x1,x2), float, $g(\vec(x)) = x1 + x2 + objective - 9$
because the original constraint was x1 + x2 + objective > 9
the way the constraint is designed ... | 4e96b98953ddc16cb48d1bd7cf7aaf441fdc552c | 641,346 |
def truncate_if_float(input_string: str) -> str:
"""
:param input_string:
:return:
"""
try:
as_float = float(input_string)
except ValueError:
return input_string
if as_float.is_integer():
return input_string
return "%.5f" % as_float | a22d2d633be1fadce7d6b975858caaee97bf2907 | 641,347 |
def parse_extra_alignments(extra_field):
"""
Parse the additional alignments field of a SAM file
:param extra_field: The 'XA' field of a SAM file (e.g. "XA:Z:NC_000913.3,+2729620,22M,0;NC_000913.3,+3427225,22M,0;")
:return: A list of tuples representing the positions of the additional alignments
""... | 5799794760e65ff20aa2f3767d49d17b873fb31e | 641,348 |
import gzip
import io
def smart_open(file, mode='rt', encoding='utf-8'):
"""Convenience function for reading compressed or plain text files.
:param file: The file to read.
:param encoding: The file encoding.
"""
if file.endswith('.gz'):
return gzip.open(file, mode=mode, encoding=encoding, newline... | f0848c07f72822cfa14b9bae92130ac7ce53b771 | 641,349 |
def check_version_2(dataset):
"""Checks if json-stat version attribute exists and is equal or greater \
than 2.0 for a given dataset.
Args:
dataset (OrderedDict): data in JSON-stat format, previously \
deserialized to a python object by \
... | bfc86b4d16750379a6ad9325f13ac267c0f414a3 | 641,350 |
def _train_dev_split(X, y, dev_ratio=0.25):
"""
This function spilts data into training set and development set.
"""
train_size = int(len(X) * (1 - dev_ratio))
return X[:train_size], y[:train_size], X[train_size:], y[train_size:] | a547cc105e6e89077dd99c43a50a77e6cc527259 | 641,353 |
def psi0(ctx, z):
"""Shortcut for psi(0,z) (the digamma function)"""
return ctx.psi(0, z) | d59412a12bffc32a3706d5d9469c27b2a2328a67 | 641,354 |
import requests
from bs4 import BeautifulSoup
def load_html(url: str):
"""URL を get メゾットで読み込みます."""
res = requests.get(url)
res.encoding = res.apparent_encoding
soup = BeautifulSoup(res.text, 'lxml')
return soup | b5161f4e09188bc73628f4e9eeda380fe14caa7a | 641,355 |
import logging
def check_response(response):
"""Check the status of responses from polyswarmd
Args:
response: Response dict parsed from JSON from polyswarmd
Returns:
(bool): True if successful else False
"""
status = response.get('status')
ret = status and status == 'OK'
i... | 4e712f45d21a8bbccfba6f79f126c7215825d5c8 | 641,357 |
from typing import Any
from typing import List
def listify(item: Any) -> List:
"""Convert any scalar value into list."""
if not item:
return []
if isinstance(item, list):
return item
if isinstance(item, (tuple, set)):
return list(item)
if isinstance(item, (int, float, str))... | b26b293869b13b942409b99e8c2cfbfe77424f6c | 641,358 |
def _ecdsa_get_pubkey(private_key) -> bytes:
""" returns the associated public key of a given ECDSA private key """
return private_key.public_key() | a4547df61880ba3f40b48a0328a66e0de678ce86 | 641,359 |
import random
def hello_url_path_elements(nutrient, crop):
"""
This method demonstrates how we can use segments of the url to provide input to the method as well
curl http://localhost:5000/recommendations/corn/nitrogen
"""
return f'The recommended amount of {nutrient} for {crop} is {random.randint... | b33c46eddedcb2c5e752852159c240e48e1ee9bd | 641,360 |
import numpy
def get_octonion_mult_table():
"""Computes the octonionic multiplication table"""
# Cf. diagram at: http://math.ucr.edu/home/baez/octonions/
ret = numpy.zeros([8, 8, 8])
fano_lines = '124 156 137 235 267 346 457'
for n in range(1, 8):
ret[0, n, n] = -1
ret[n, n, 0] = ret[n, 0, n] = 1
... | 735371df4b080327609a46db470ec02d9624d037 | 641,361 |
def eulers_cromer_method(f, dx, y, yp, range, cromer=True):
""" The Eulers method, and Eulers-Cromer method for second order
differential equations.
:param f: Second order differential equation to approximate the solution for.
:type f: lambda
:param dx: Step size. Smaller is better.
:type ... | 84a3b5b4543284a7c1fe265370dfa261851df58f | 641,362 |
def get_message_counts_for_account (cnx, account_id):
"""
query = "select count(m.id),date(min(m.date_time))," + \
"date(max(m.date_time)) " + \
"from message m,folder f where m.folder_id=f.id and " + \
"f.account_id=" + str(account_id) + ";"
"""
message_count = 0
query = "select su... | 7395c5ff28569a25d3cd5c5a4bc4bde170655198 | 641,363 |
def amap(attr, *args):
"""More convenient syntax for quick data exploration. Get an attribute
value for multiple objects. Name is short for "attrmap".
Parameters
----------
attr: str
Name of attribute to retrieve for each object.
args: any
Objects (usually of same type) to retri... | af3236c8a5d6c9431fb470b6e6e6bd1288f02313 | 641,364 |
import re
def _update_id(record, new_id):
"""
Update a record id to new_id, also modifying the ID in record.description
"""
old_id = record.id
record.id = new_id
# At least for FASTA, record ID starts the description
record.description = re.sub('^' + re.escape(old_id), new_id,
... | 6fc291a462ee4bd02dee998d4585612220b464f4 | 641,365 |
import json
import requests
def collection_exists(collection_name):
"""
Check if a collection already exists on DIVAServices
Arguments:
collection_name {string} -- the name of the collection on DIVAServices
Returns:
bool -- True if the collection exists, False otherwise
"""
... | eecdb84be1422fe9c6011c03bb9240f372dcb257 | 641,366 |
import json
def from_json_file(json_file):
"""Constructs a `BertConfig` from a json file of parameters."""
with open(json_file, "r", encoding='utf-8') as reader:
text = reader.read()
json_object = json.loads(text)
config = dict()
for key, value in json_object.items():
... | adf0bea44f1c9e4f4f5fd6e0c2d840f8772ff41a | 641,367 |
import warnings
def _get_secret_keys(config, secrets_config_key='SECRETS', secrets_list=None):
"""
Finds all of the configuration values that should be secret
"""
keys = []
if secrets_config_key is not None:
configuration_keys = config.get(secrets_config_key)
if configuration_keys ... | 1390da52b7e5cdbae26023931dd03bc54a4cbb8c | 641,368 |
from typing import Any
def return_input(obj: Any) -> Any:
"""A dummy function that always returns input."""
return obj | 5877fde16fca3ad5080b4c7aef7c6a21ffa4c3b4 | 641,370 |
def hind_da_initialized_1d(hind_ds_initialized_1d):
"""CESM-DPLE initialized hindcast timeseries mean removed xr.DataArray."""
return hind_ds_initialized_1d["SST"] | d2df5bc768434f0c183d49f7504e5080098f9d21 | 641,371 |
import math
def build_sweep_config() -> dict:
"""
Gets training configuration for bayesian hyper-parameters optimization.
Args:
anisotropic (bool): if True, uses an anisotropic graph manifold.
coupled_sym (bool): if True, uses coupled symmetric layers.
Returns:
(dict): config... | 49e40a77141297cc6995172469a40c00a1d1eed0 | 641,372 |
from datetime import date
def voto(nasc):
"""Informa se a pessoa pode ou nao votar.
Args:
nasc (int): Ano de nascimento da pessoa.
Returns:
Idade da pessoa e se seu voto é negado, opcional ou obrigatório.
"""
idade = date.today().year - nasc
if idade < 16:
return f'Co... | c368384db2faa4594a382bdab8a02d68c94aaede | 641,373 |
def parse_error_msg(orig_msg):
"""
Parse "error" message received from backend
Format:
"error: %s\r\n"
"""
error = orig_msg[7:]
return "error", error | 2f719bde6cab50379bd3b9769d9ee394c5900b1e | 641,374 |
from math import copysign as sign
def other_reverse_invert(lst):
"""Best practice solution from codewars."""
return [-int(sign(int(str(abs(x))[::-1]), x)) for x in lst
if isinstance(x, int)] | dda32368e21afb214db48ea5c29f5aca185282cd | 641,375 |
def add_calculated_rul(df):
"""Calculates Remaining Useful Life (RUL) and adds it to dataset, which is returned.
Parameters
-----------
df : pd.DataFrame
Dataframe containing time-series data.
Returns
pd.DataFrame
dataset, inclusive of calculated RUL values.
"""
... | 86163be9592320ee9da3b6687c8fef2260b788a4 | 641,376 |
def relu_d(x: float) -> float:
"""
The gradient of the ReLu activation function
Args:
x: The point at which to take the gradient
Returns:
The gradient of the ReLu activation function
"""
if x > 0:
return 1
return 0.1 | 0f25a4c12018629913e0f782b6c734167cb1a4ad | 641,377 |
def _strip_shell(cmd):
"""Strip a (potentially multi-line) command.
For example
$ foo \
> --bar baz \
> --quux 10
would becomes `foo --bar baz --quux 10`.
"""
parts = []
for line in cmd.strip().split("\n"):
without_console = line.lstrip("$> ").rstrip("\\ ")
... | 6acfb178e71faa1c8e416232db19d4a8ed72cab2 | 641,378 |
def list_local_tags(repo):
"""Return a list of the tags on the local repo."""
# A tag can point to a blob and the loop prunes blob tags from the list of tags to be sorted
tag_list = []
for bar in repo.tags:
try:
bar.commit.committed_datetime
except ValueError:
pas... | ef3e4cac7f8542ad55976a67ad48752134c8c8a6 | 641,379 |
def ask(msg, number=True):
"""Return valid user response to a question.
Accepts:
msg, str: What to display to the user
number, bool: Whether to enforce entry of a number
Returns:
response, (str|float): User entry, either string or float
"""
while True:
response = inp... | 257eac87dbe97fe9e38dbe0045dc1c190a9f5b08 | 641,380 |
from operator import getitem
from functools import reduce
def dpath(dict_, path):
"""Dig into dictionary by string path. e.g.
dpath({'a': {'b': {'c': 'd'}}}, 'a.b') -> {'c': 'd'}
"""
paths = path.split('.')
return reduce(
getitem,
paths,
dict_
) | 35dee83a37ae922d1e5023a726bfe5e0283c5843 | 641,381 |
def length(node):
"""
Count how many values there are in the linked list
:param node: value of head node, start of list
:return: int: number of list elements
"""
if node is not None:
return 1 + length(node.next_node) # count nodes basically
return 0 | 9652d54a8d727924bde45972abff403e0dcc43ff | 641,382 |
def cli(ctx, extension_only=False, upload_only=False):
"""Get the list of all installed datatypes.
Output:
A list of datatype names.
For example::
[u'snpmatrix',
u'snptest',
u'tabular',
u'taxonomy',
u'twobit',
u'txt',
... | 703c15f4ae699c14167c31136b2d7a4d80bcc26d | 641,383 |
def dicgetlast(dictionary,pier=None,element=None):
"""
DEFINITION:
get last delta value inputs from a dictionary with year keys
RETURN:
Returns a value dictionary
APPLICTAION:
result = dicgetlast(dictionary,pier='A2',element='deltaD,deltaI,deltaF')
EXAMPLE:
"""
return... | 352b477424a1f6e5637eb1c38a4ab18bebfb763f | 641,384 |
def matrix_multiplier(mat1, mat2):
"""Multiplies Two matrix of any size"""
# empty list for storing multiplied rows
multiplied_matrix = []
for row1 in mat1:
# list for adding multiplied value
rows = []
for col2 in zip(*mat2):
sum1 = 0
for (a, b) in zip(r... | 6368361c788d030bc013d93b62477f73065405fd | 641,386 |
import socket
def gethostname():
"""Return hostname of this instance."""
return socket.gethostname().split(".")[0] | 038b574c4f6e0817cdd69cbafdcc505293490bdf | 641,387 |
from typing import Union
import hashlib
import requests
def _pwned_password(passphrase: str) -> Union[int, bool]:
"""Check passphrase with Troy's Hunt haveibeenpwned API.
Query the API to check if the passphrase has already been pwned in the
past. If it has, returns the number of times it has been pwned,... | 7ff2f195d0cda81980ddc3e5655fd8f6d851699c | 641,388 |
import os
import subprocess
import shlex
def run_cmd(app, cmd):
"""Run a command and return a tuple with (stdout, stderr, exit_code)"""
os.environ['FLASK_APP'] = app
process = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
(stdout, std... | 0559f0a6d325f78eaf17db3cf77d205d5f515edb | 641,390 |
from functools import reduce
def intersect(groups):
"""Given <groups> of allergens grouped with ingredients, find the allergen
contained in each of the relevant ingredients. """
intersecs = {k: reduce(lambda a, b: a.intersection(b), e)
for k, e in groups.items()}
inert = False
... | 9cc1a328cbc379ade3e5305f90e4cb8466633914 | 641,391 |
def vector2string(vec):
"""
Helper function, converts vector to one string separated by spaces
:param vec:
:return:
"""
s = ""
for item in vec:
s += str(item) + " "
return s | 672e312c471e8e1c5af07dad7cfb051393e2a3e5 | 641,392 |
def last_received_endswith(agent, tail):
"""
Check if the agent's last received message ends with `tail`.
It is supposed to be executed as an agent method (in example: use it as
the condition in `wait_agent_condition` or execute it with the method
`execute_as_method`).
Parameters
---------... | 58526dec02f8f12ff06745c2ff2588e563d875e0 | 641,393 |
def version_to_str(vsn):
"""
Convert the given version tuple to a dot separated string representation
"""
return '.'.join(str(x) for x in vsn) | 97b76da4a5d8b2beabf1b47519ddb8d93599e10f | 641,394 |
def time_to_secs(t):
"""Convert a datetime.time object to seconds"""
return t.hour*3600 + t.minute*60 + t.second | 37b12e42b6841c6ce3c9a45ab90c0e33257ae2b1 | 641,395 |
def find_passing_students(lst):
"""
Takes a list created in convert function. Students can pass if the mt1*0.3 + mt2*0.3 + final*0.4 > 60.
Args:
lst: list of tuples created in convert function
Return:
student_names: list of stringss that stores the passing students' names.
"""
#... | 00fe09d5514b55d67a4021219810e0f71ac7bdaf | 641,396 |
def get_func_id(func):
"""Get a quasi-identifier of a given function."""
return func.__qualname__ | 8aba6fdb53d5c1ba89e0e4443b919070516224fa | 641,397 |
import math
def rotate(v, axis, angle):
"""Rotate a vector about an axis through an angle
Parameters
----------
v : array with exactly 3 numeric entries
The vector to be rotated.
axis : one of 'x', 'z'
The axis about which to rotate. Rotations about y are not
supported sin... | e0148dfc28216e8f6a4cc1e5d16a5e93ee023753 | 641,399 |
from typing import List
import os
def find_file(name: str, path: str = ".") -> List[str]:
"""Find all files with a specific name recursively in a directory."""
return [
os.path.join(root, name) for root, _, files in os.walk(path) if name in files
] | e49f5ebc1c550a87f84d44f74c1fd6322c0543ed | 641,400 |
import torch
def seq_gather(x):
"""
seq shape: [None, seq_len, s_size]
idxs shape: [None,]
Select vec from seq: [None, s_size]
"""
seq, idxs = x
batch_size = seq.shape[0]
res = []
for i in range(batch_size):
vec = seq[i, idxs[i], :]
res.append(vec)
res = torch.s... | a67618719f00871261d61fe80b2710ab72480433 | 641,402 |
def _pick_repository(parameters_json: dict) -> str:
""" return ARCHT for Architectural Lantern Slides, else UNDA """
part_of = parameters_json.get('partOf', '')
while isinstance(part_of, list):
part_of = part_of[0]
if parameters_json.get('collectionId', '') == "qz20sq9094h" or "qz20sq9094h" in p... | c91652dc2dc0396bd80c307ec4e2954ce6fe10b1 | 641,403 |
def sumd(n):
""" Return the sum of digits of a number.
number: non-negative integer
"""
# Base Case
if n == 0:
return 0
else:
# Mod (%) by 10 gives you the rightmost digit (227 % 10 == 7),
# while doing integer division by 10 removes the rightmost
# digit (22... | 6fbcf51c69e2e4a23ca6ca3851a37ee43bf170e3 | 641,404 |
import math
def round_half_up(n, decimals=0):
"""
实现常见的那种四舍五入,警告这只是一种近似,如果有精确的小数需求还是推荐使用decimal模块。
"""
multiplier = 10 ** decimals
return math.floor(n*multiplier + 0.5) / multiplier | d46d4b395a0a5271e997201cbf2c3d51494b7f1a | 641,405 |
def extract_keyhandle(path, filepath):
"""extract keyhandle value from the path"""
keyhandle = filepath.lstrip(path)
keyhandle = keyhandle.split("/")
return keyhandle[0] | 7ba511ffb74ef079228ea9f263049437f82efecb | 641,406 |
def convert_command_group_all(test):
"""command-group-all superseded by run-bash-script and run-powershell-script"""
cmds = [x['command'] for x in test['args'].pop('commands')]
test['args']['source'] = '\n'.join(cmds)
if 'windows' in test['name']:
test['type'] = 'run-powershell-script'
else:... | a4f2c82ec3228fadd5ff73189be883891e915391 | 641,407 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.