content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def appendToFile(fileName: str, content: str):
"""Writes content to the given file."""
with open(fileName, "a") as f:
f.write(content)
return None | a9e4604fa9404f3c304a40e18ead42a70d99e956 | 3,618,100 |
def kaldi_normalize(word, vocab):
"""
Take a token extracted from a transcript by MetaSentence and
transform it to use the same format as Kaldi's vocabulary files.
Removes fancy punctuation and strips out-of-vocabulary words.
"""
# lowercase
norm = word.lower()
# Turn fancy apostrophes i... | cd713a39d4d53f82634a761fcc64100ac312377b | 3,618,101 |
import sys
def mc_prediction(policy, env, num_episodes, discount=1.0):
"""
Monte Carlo prediction algorithm. Calculates the value function
for a given policy.
Args:
policy: A function that maps an observation to action probabilities.
env: OpenAI gym environment.
num_episod... | 7d8eec5c5657ce9f2cb0bff5102c63ea4b0fc2f5 | 3,618,102 |
def table_col_info(cursor, tableName, printOut=False):
"""
Returns a list of tuples with column informations:
(id, name, type, notnull, default_value, primary_key)
"""
cursor.execute('PRAGMA TABLE_INFO({})'.format(tableName))
info = cursor.fetchall()
if printOut:
print("Column Info:... | 3c950a3980ac5126ecab44bc585a576a8ed947f5 | 3,618,103 |
import re
def _apply_regex(regex, full_version):
"""
Applies a regular expression to the given full_version and tries to capture
a group
:param regex: the regular expression to apply
:param full_version: the string that the regex will apply
:return: None if the regex doesn't match or the res... | 0a053fd716844f4ec1ad166f414e4d1b931434ec | 3,618,104 |
def sample_unit_sphere(N):
""" generate a set of points distributed on the unit sphere
Parameters
----------
N : int
Number of points
Returns
-------
array_like
A set of points distributed on the unit sphere
"""
dlong = np.pi*(3-np.sqrt(5))
dz = 2.0/N
lon ... | 17b56fd9d32353424dbd32082c7366620b3f4b55 | 3,618,105 |
def visualization_plot(figdata, i, add_label, spec_colnames, plot_color='grey', ylabel='Percent', ylim=-999):
"""Plot Bar Graph or Line Graph
-i: column name
-tmp_cut: data directly used for plot
-add_label: label added to X label
-spec_colnames: interpretation on short column name ... | a4f4fd92e32a07d682e57fd36edddc18f197c206 | 3,618,106 |
def indices(a, func):
"""
Get indices of elements in an array which satisfies func
>>> indices([1, 2, 3, 4], lambda x: x>2)
[2, 3]
>>> indices([1, 2, 3, 4], lambda x: x==2.5)
[]
>>> indices([1, 2, 3, 4], lambda x: x>1 and x<=3)
[1, 2]
>>> indices([1, 2, 3, 4], lambda x: x in [2, 4])
... | 8c1855cfdbbc11f7b88b23971f03717fc78be27a | 3,618,107 |
def get_deployment_config(app):
"""
Gets deployment configuration for the current environment.
Sets ENV_NAME and WIPE_ES as side-effects.
:param app: handle to Pyramid app
:return: dict of config options
"""
deploy_cfg = {}
current_prod_env = ENV_WEBPROD # this could change for CGAP d... | 263c8de978736966c39b6d992a11ee0172b46487 | 3,618,108 |
import copy
def build_adiabatic_eq_library(flamelet_specs, verbose=True):
"""Build a flamelet library with the equilibrium (infinitely fast) chemistry assumption,
equivalently with Gibbs free energy minimization.
Parameters
----------
flamelet_specs : FlameletSpec or dictionary of arguments f... | 67a7457e4331dec0f01c5fb52b0863bd488e2ea2 | 3,618,109 |
from typing import List
from typing import Tuple
from typing import Dict
import copy
def build_openapi(
method: str,
path: str,
resp_code: str,
parameters: List[Tuple[str, str]] = None,
request: str = None,
response: str = None,
media_type: str = "application/json",
example: bool = Tru... | 84eec732add1691f8d3d580e01885da4a9e38968 | 3,618,110 |
def my_decorated_function(name, value): # ...check_value(fix_name(negate_value(my_decorated_function)))
"""my original function."""
print("name:", name, "value:", value)
return value | fec8ea3f49f4561bdf63245bf5cb9ec284352704 | 3,618,111 |
def delete_user(user_name):
""" delete an iam user """
# get the user
user = get_user(user_name)
# create a client
client = boto3.client("iam")
# Attached managed policies ( DetachUserPolicy )
for policy in user["policies"]:
policy_arn = policy["PolicyArn"]
response = clien... | 9ff7e88f23cbbcaeaa721476a152dda96e29afc6 | 3,618,112 |
def fit_gauss2d(data):
"""
Fit a 2-dimensional anisotropic Gaussian to an image.
Parameters
----------
data : array_like
A two dimensional array_like object
Returns
-------
sigx : float
The standard deviation of the long axis
sigy : float
The standard devia... | 7c7f97cfe4c5d13a7572f87d3f6e69b6d0c2e8b0 | 3,618,113 |
from pymbolic import var
from loopy.match import parse_stack_match
from pymbolic.mapper.substitutor import make_subst_func
def rename_iname(knl, old_iname, new_iname, existing_ok=False, within=None):
"""
:arg within: a stack match as understood by
:func:`loopy.match.parse_stack_match`.
:arg existi... | 4047c1397b446f2ad2a2ee8e5bb36dd93f3349d1 | 3,618,114 |
def get_words_forward(text, sep=None):
"""Get words (from text at right side of caret)"""
tokens = split_tokens(text)
words = extract_words_from_tokens(tokens, sep)
return ''.join(words) | a2402f7ec94ebf7a35b58e410f84da63d627afb5 | 3,618,115 |
def check_str_isalnum(string: str) -> ResultComparison:
""" post: _ """
return compare_results(lambda s: s.isalnum(), string) | ff35a924c7c7c695df3c26e3bec795fb59d9e1d7 | 3,618,116 |
import platform
def get_architecture_string():
"""Return a string representing the operating system and the python
architecture on which this python installation is operating (which may be
different than the native processor architecture.."""
return '%s%s' % (platform.system().lower(),
platfor... | 1af6d3b0a713dad26a372389d583f7f7e44679e3 | 3,618,117 |
def polyfit(dates, levels, p):
"""Given the water level time history (dates, levels) for a station the function computes a least-squares fit of a polynomial of degree p to water level data.
It returns a tuple of (i) the polynomial object and (ii) any shift of the time (date)"""
try:
# Create ... | c6a77112f43ad642523d2696cb34775ff9828ec2 | 3,618,118 |
def update_episodio():
"""
Aggiorna i dati di un episodio esistente
"""
nome = request.form['nome']
descrizione = request.form['descrizione']
tag = request.form['tag']
file = request.files['file']
id = request.form['id']
file_path = ''
# controlla che i dati necessari siano ins... | 654701ee490438c402e134384ff0b134507ba557 | 3,618,119 |
import re
import html
def escape_text(txt):
"""
Escape text, replacing leading spaces to non-breaking ones and newlines to <br> tag
"""
lines = []
for line in txt.splitlines():
lead_spaces = re.match(r'^\s+', line)
if lead_spaces: # Replace leading spaces with non-breaking ones
... | 6c750fc9f0862a6b8a5739362918bb54ec73ea98 | 3,618,120 |
def get_coord(filename, pix_x,pix_y,timeFrame=0):
"""
Converts pixel values to solar coordinates
Parameters
----------
filename : str
name of the data cube
pix_x, pix_y : int
pixel location to convert
timeFrame : int
selected frame to the coordinates for (Default val... | 395c9de3388cd6a30e0c7cc17cdd79cfc10edfac | 3,618,121 |
import math
def setup_dataframes():
""" Set up dataframes for agents (df_a) and night shift info (df_n). """
global min_week_average_hours
min_week_average_hours = 100 # This will form a baseline for agent history.
agents = input_json["agents"]
df_a = pd.DataFrame(
data=None,
co... | c9c85b200caea3013a5577832b139a3de9b0a467 | 3,618,122 |
import requests
import json
def get_candle():
"""
Function returns array (list of arrays if param 'limit' > 1) with next data:
Start time (type int) (WARNING!For correct subsequent work with the field, it must be divided by 1000)
open (type float) Open price
high ... | cc661b2b2598644e5ce638f805d46b18fb6fcb67 | 3,618,123 |
import json
def _clean_output_json(output_json: str) -> str:
"""Make JSON output deterministic and nicer to read."""
try:
output = json.loads(output_json)
except json.JSONDecodeError:
raise ValueError(
f"Instead of JSON, output was:\n--- output start ---\n{output_json}\n--- out... | 0952ed8f8cc34ca2c18aa3d09ca0c81607066332 | 3,618,124 |
async def get_default_playing(in_guild):
"""Search for a suitable waiting channel on new guild entry
Parameters
----------
in_guild :
Discord Guild to determine default channel for
"""
channels = in_guild.voice_channels
words = ["active","play","stream"]
chans = [c for c in ch... | ffd8418f1b3f5a32933a67459ab94d3960dd68d6 | 3,618,125 |
def normalize_empirically(X_O, characters, keyslots, capitalization_constraints=1):
"""
Normalize empirically for the result to be between 0 and 1.
First minimizes and maximizes the keyboard problem for the given cost (X_O) and then normalizes all values in X_O
to minimally/maximally sum up to 0/1. ... | 08edcc08c3ad52ce96bf28c834510955f2edea4a | 3,618,126 |
def encrypt_payment_id(payment_id, public_key, secret_key):
"""
Encrypts payment_id hex.
Used in the transaction extra. Only recipient is able to decrypt.
:param payment_id:
:param public_key:
:param secret_key:
:return:
"""
derivation_p = crypto.generate_key_derivation(public_key, s... | 0f4f119705c699fa77171bd14a4b5bc89316a813 | 3,618,127 |
def list_csv_content_view(request):
"""
Homepage of the website. Displays uploaded CSV file in table form.
:param request: HTTPRequest object
:return: HttpResponse object
"""
if request.method == 'GET':
headings = [f.name for f in MuseumAPICSV._meta.get_fields()]
museum_api_csv_o... | 502791d766c1c8b1d462d462adcf9bcacf1920fc | 3,618,128 |
def vertical(x, ymin=0, ymax=1, color=None, width=None, dash=None, opacity=None):
"""Draws a vertical line from `ymin` to `ymax`.
Parameters
----------
xmin : int, optional
xmax : int, optional
color : str, optional
width : number, optional
Returns
-------
Chart
"""
li... | 0ca96d2dac5f88287f8e71045b5b77ddf568f9c0 | 3,618,129 |
def one_hot(labels, classes):
"""Apply One-Hot encoding to labels."""
return np.eye(classes)[labels] | d75e088e880124001f3d2677a2931b5cf25a3753 | 3,618,130 |
def get_os_credentials():
"""
Get OpenStack credentials from the environment
:return: str or None for the OS_AUTH_URL, OS_TOKEN, OS_USERNAME, OS_PASSWORD, OS_USER_DOMAIN_NAME and OS_TENANT_ID
"""
return get_os_auth_url(), get_os_token(), get_os_username(), get_os_password(), get_os_user_domain_name(... | e1185d10e130c164cf9f7882514b7cd0dd880d2b | 3,618,131 |
def reindex_colors(colors, labels):
"""Reindex the colors array using labels presented in a label image.
Because the labels in a label image are not necessarily a series of
consecutive integers, the ``1, ..., num_labels`` rows of the original colors
will be mapped to ``label1, lebel2, ..., labeln`` row... | 9f37120dda71aac758513ed7620a46746e926fbf | 3,618,132 |
def filter_factory(global_conf, **local_conf):
"""Return a WSGI filter app for use with paste.deploy."""
conf = global_conf.copy()
conf.update(local_conf)
def auth_filter(app):
return TAuthProtocal(app, conf)
return auth_filter | bb14c1173d0bfa0f3354811ba802ec6101dbe85c | 3,618,133 |
def compute_codebook(descriptor_space, num_codewords):
"""Compute codebook for bag of features descriptor using k-means.
The descriptor space is a collection of local geometry descriptors. This
needs to be in the format of a matrix, rather than a list or a tensor.
"""
if isinstance(descriptor_space... | a21602ef19cbb0662342a65437b1e0bc9f45eb31 | 3,618,134 |
from ..gfx.bezier import Bezier
def contours(path):
"""Returns a list of contours in the path.
A contour is a sequence of lines and curves
separated from the next contour by a MOVETO.
For example, the glyph "o" has two contours:
the inner circle and the outer circle.
>>> path = Bezier(None)... | ed9a03aadf967419839358eaee2098df32a89410 | 3,618,135 |
from operator import gt
def gen_dcppm(nr, B, k, ep, gamma, xmax = None):
"""
Input
-----
nr: number of nodes in each community
B: number of communities
k : average degree of the network
ep: the strength of the assortative structure, a real value in [0,1]
gamma: sha... | 6c6f6d4336f3382ec1887b6062118cac15e9e073 | 3,618,136 |
def stations_within_radius(stations, centre, r):
"""This function uses haversine to first compute the distance from the given centre to the station
and then selects the stations which are closer than the given radius distance. The function then
returns a list of stations (MonitoringStations) in an unsorted ... | f1a4e7bb9c233c71058dea90e5975763a07e9b8b | 3,618,137 |
def lowless(dem):
"""
LOWESS (Locally Weighted Scatterplot Smoothing)
"""
lowess = sm.nonparametric.lowess
y = dem
x = np.arange(0, y.size)
w = lowess(y, x, frac=1/3)
return w[:, 1] | c57152e0e3fea470cc3221332e23821bc130a1e7 | 3,618,138 |
def FetchByProjectAndTestName(project_name, test_name):
"""Fetches the first test with the given name."""
q = StorageMetadata.all()
q.filter('project = ', project_name)
q.filter('test_name = ', test_name)
return q.get() | 79f047b7ffc6ba93257170c2cbc4608a07a860de | 3,618,139 |
def parse_args():
"""Parse the input arguments, use '-h' for help"""
parser = ArgumentParser(description=('Produce VCFs and corresponding stutter'
' frequencies for a given set of STR loci. Also provides a bed file for each'
' locus defining a region around that locus.'))
parser.add_argument(
... | b976f86b32a5704c6f27e1f4eada8c270cd1aed4 | 3,618,140 |
import socket
def check_connection(server, port):
""" Checks connection to server on given port """
try:
sock = socket.create_connection((server, port), timeout=5)
except socket.error:
return False
else:
sock.close()
return True | 7b0b7174e7351c87a907d94012e65898cc38a713 | 3,618,141 |
def make_tensor(name: str, vals: np.ndarray) -> ITensorProto:
"""
Make a TensorProto with specified arguments. If raw is False, this
function will choose the corresponding proto field to store the
values based on data_type. If raw is True, use "raw_data" proto
field to store the values, and values ... | 3d9f1150a96e6dd7b56bc3ce67b45b9da8e73a1c | 3,618,142 |
def skip_inline(view, point):
"""Return True si il y a text between start of line and point"""
line_reg = view.line(point)
line = view.substr(sublime.Region(line_reg.a, point)).strip()
if line == "":
return False
else:
return True | 757941d539349b8e64781f07e24db6486535fda2 | 3,618,143 |
def load_image(fname):
"""Load named file, returning (data, metadata).
Keep temporarily for backward-compatibility...
"""
return load_tiff(fname) | cf70c305ed9086ce187394cd76acaf944510e1ef | 3,618,144 |
def tile(xi, yi, zoom):
"""Generates a box corresponding to a tile used for "slippy maps"
Parameters:
-----------
xi : int
The tile's X-index
- Range depends on zoom value
yi : int
The tile's Y-index
- Range depends on zoom value
zoom : int
The tile's z... | 8895fee10013b28a74bb4e1201e07623522a4e92 | 3,618,145 |
def _rescale_layout(coords, bbox):
"""Transpose the layout of a component into its bounding box"""
min_x, min_y = np.min(coords, axis=0)
max_x, max_y = np.max(coords, axis=0)
if not min_x == max_x:
delta_x = max_x - min_x
else: # graph probably only has a single node
delta_x = 1.0
... | 9a452e880f3170f36dc3aa097b23de35b373e3cb | 3,618,146 |
def empirical_cdf(values, v):
"""
Returns the proportion of values in ``values`` <= ``v``.
"""
count = 0.0
for idx, v0 in enumerate(values):
if v0 < v:
count += 1
return count / len(values) | 65de22130e87ede7dc637e4140f324bdad6dc31b | 3,618,147 |
def centerpoint(s):
"""
s is 2-d integer-valued (float or int) array shape
return is a (2-tuple floats)
correct for Jinc, hex transform, 'ff' fringes to place peak in
central pixel (odd array)
pixel corner (even array)
"""
return (0.5*s[0] - 0.5, 0.5*s[1] -... | ab79301294f59b88e6005f175671d86fb6201534 | 3,618,148 |
def _calculate_compliance(results):
"""
Calculate compliance numbers given the results of audits
"""
success = len(results.get('Success', []))
failure = len(results.get('Failure', []))
control = len(results.get('Controlled', []))
total_audits = success + failure + control
if total_audit... | d0855cd88a0ec88a1b9de2c1ba0372a854f2a9c6 | 3,618,149 |
def calculate_log(current_count, smallest_count, largest_count, max_size, min_size):
""" Calculate ratio (logarithmic version). """
return ((log10(current_count) / log10(largest_count)) * (max_size
-min_size) + min_size) | d8d95da709d4fda1c096f2e93c8d1f271c363a62 | 3,618,150 |
from prody import parsePDB as p
from prody import parsePDBStream as ps
from os.path import exists, isfile, splitext
import tarfile
from ..IO.output import printError
def parsePDB(filename, **kwargs):
"""Read PDB file. If there exists a beta file read it also.
If the file is a `.tar.gz` or `.tar.bz2` file, th... | ec925624fadad912762d74246b8cf4a678b36d3d | 3,618,151 |
def make_fuser(fusion_method: str, feature_size: int, n_modalities: int, **kwargs):
"""Helper function to instantiate a fuser given a string fusion_method parameter
Args:
fusion_method (str): One of the supported fusion methods [cat|add|bilinear|attention]
feature_size (int): The input modality... | c3e8a1c400fc1331a969cbc8ba39a72e025a33b8 | 3,618,152 |
def qa_to_qaconf_slow(qa_data):
"""
Transforms MODIS QA into a confidence score.
confidence comes from the vi_usefulness bits
"""
# https://lpdaac.usgs.gov/dataset_discovery/modis/modis_products_table/mod13q1
# 0-1 MODLAND_QA
# 00 VI produced, good quality
# 01 VI produced, bu... | 8187bb7207b14ebbb57c7f1943baf1c87d117000 | 3,618,153 |
from datetime import datetime
def create_token_from_id(id):
"""
Create a token that can be used to verify a email address.
Expires in 1 hour.
"""
to_encode = {
"id": id,
}
expire = datetime.utcnow() + timedelta(minutes=EMAIL_TOKEN_EXPIRE_MINUTES)
to_encode.update({"exp": e... | 71719b60e3f7075427593720992d9522ce697de4 | 3,618,154 |
def good_turing(corpus, words):
"""
:param corpus:
:param words:
:return:
"""
for w in words:
if w in corpus:
raise ValueError('未登录词有误!')
r_dict = {}
for w in corpus:
if r_dict.get(w) is None:
r_dict[w] = 1
else:
r_dict[w] += ... | af35ba996d0f0d2236fc8ef4f6f0466a5204520e | 3,618,155 |
def get_server():
"""Return the server info."""
return dict(version=QUALITY_TIME_VERSION) | e6601addf06561fb19ee895f31c7dcb025bc1ae3 | 3,618,156 |
def extract_main_tree(treedata, idx=None):
"""
Returns a single branch/trunk of tree following only the main progenitors.
Works whether the treedata is alltrees or atree.
Search until no progenitor is found. Doesn't matter how long the given tree is.
"""
if idx == None:
prin... | 7645b5dec144c31c724fa07e93aef710d2053a7b | 3,618,157 |
import torch
from typing import List
def decode_smiles(model_outputs:torch.tensor = None) -> List[str]:
""" Function to decode smiles from their generated indexes.
Parameters :
-------------
model_outputs : torch.tensor,
a tensor of tensors that containes indices of each generate... | f80b0bdc9f93f3fc804d29b5003eccf756c8a3b7 | 3,618,158 |
def to_ansi(*codes):
"""Convert a set of ANSI codes into a valid ANSI escape sequence."""
if not codes:
return ''
return colorise.nix.cluts._COLOR_ESCAPE_CODE +\
'{0}m'.format(';'.join(str(c) for c in codes)) | 7766f7c90815831820d53aa12e76600123948c79 | 3,618,159 |
def critical_cases_20():
"""
Real Name: b'Critical Cases 20'
Original Eqn: b'INTEG ( infected critical case rate 20-critical cases recovery rate 20-death rate 20+isolated critical case rate 20\\\\ , init Critical Cases 20)'
Units: b'person'
Limits: (None, None)
Type: component
b''
"""
... | 9476db57fc1546ee4f2e37b95431bda7c88611bd | 3,618,160 |
def datatype_percent(times, series):
"""
returns series converted to datatype percent
ever value is calculated as percentage of max value in series
parameters:
series <tuple> of <float>
returns:
<tuple> of <float> percent between 0.0 and 1.0
"""
max_value = max(series)
try:
... | 8973829f6ea3425351373097fa90b7d4762a880e | 3,618,161 |
def lame(E=None, v=None, u=None, K=None, Vp=None, Vs=None, rho=None):
"""
Compute the first Lame's parameter of a material given other moduli.
:param: E: Young's modulus (combine with v, u, or K)
:param v: Poisson's ratio (combine with E, u, or K)
:param u: shear modulus (combine with E, v, or K)
... | b8f1d52bac3130b69f75903091d00ce49ba553f8 | 3,618,162 |
def encrypt_factory(cypher = None,Seed = None):
""" creates an encryptor and a decryptor function from a cypher, or a seed, or randomly
"""
if not cypher:
cypher = make_cypher(Seed)
trans = mt(alphabet,cypher)
untrans = mt(cypher,alphabet)
def encryptor(message):
return message.... | 39a4e3098257e5d02d41b57be42cddb30d29a663 | 3,618,163 |
def simulate(ti_controls, sampling_times, model_parameters):
""" ensuring pyomo returns state values at given sampling times """
model, simulator = create_model(sampling_times)
""" fixing the control variables """
# time-invariant
model.theta_0.fix(model_parameters[0])
model.theta_1.fix(model_p... | 4f21cfbe570bd02e6042d4670f9bb9739e667470 | 3,618,164 |
def region_of_interest(img, vertices):
"""
Applies an image mask.
Only keeps the region of the image defined by the polygon
formed from `vertices`. The rest of the image is set to black.
"""
#defining a blank mask to start with
mask = np.zeros_like(img)
#defining a 3 channel ... | 6b268bb817aea7830c99d9498379d609a21e82a3 | 3,618,165 |
import os
import codecs
def initialize_vocabulary(vocabulary_path):
"""
initialize vocabulary from file.
assume the vocabulary is stored one-item-per-line
"""
characters_class = 9999
if os.path.exists(vocabulary_path):
with codecs.open(vocabulary_path, 'r', encoding='utf-8') as voc_fi... | c63f57299c42914986a17935ca57ccd995500cfe | 3,618,166 |
def _make_decorator(measuring_func):
"""morass of closures for making decorators/descriptors"""
def _decorator(name = None, metric = call_default):
def wrapper(func):
name_ = name if name is not None else func.__module__ + '.' +func.__name__
class instrument_decorator(object): #... | 80b00e2d47aa7e3df2b87c423489c9c7b8559da3 | 3,618,167 |
import re
import urllib
def webtest(url, webtimeout):
"""
This tests connectivity to a webservice running at a given URL.
:param url: Application URL to be tested.
:type url: basestring
:param webtimeout: application web timeout to be used for the test.
:type webtimeout: int
:return: Raise... | 0db44a47384e64056cc9fd3c519c9a3a9305a1ab | 3,618,168 |
def result(obj, key, default=None):
"""Return the value of property `key` on `obj`. If `key` value is a
function it will be invoked and its result returned, else the property
value is returned. If `obj` is falsey then `default` is returned.
Args:
obj (list|dict): Object to retrieve result from.... | 0a16702dea87f352cd60afe675de03177815e51b | 3,618,169 |
from typing import List
from typing import Tuple
from pathlib import Path
import json
def load_accuracy_data(
files: List[Tuple[str, str, str]], folder: str
) -> List[Tuple[ndarray, ndarray, str, int, float]]:
"""This function loads the accuracy data that the user has elected to plot.
Args:
files: ... | 7a8409e523403485c841a851afa4cbc491f034c2 | 3,618,170 |
def add_options(options):
"""Decorator to add a list of options."""
def _add_options(func):
for option in reversed(options):
func = option(func)
return func
return _add_options | a454361a550c9b1a9c67345123b43e490d03cff0 | 3,618,171 |
import shutil
def exec_rmdir(dirname):
"""
Create a directory.
Parameters
----------
dirname: str
The full path of the directory.
Returns
-------
bool:
True on success, raises an exception otherwise.
"""
_logger.debug('__ Removing directory tree %s.', d... | 378cfeddef679acdd15f1327121750a6822b10f7 | 3,618,172 |
import sys
import time
import getpass
import socket
def _get_s3_creds(client, force=False):
"""
Retrieves stored s3 creds for the acting user from the config, or generates new
creds using the client and stores them if none exist
:param client: The client object from the invoking PluginContext
:ty... | c7ac9131978e000308d19747727251c80100f5f8 | 3,618,173 |
from celery import canvas
import socket
import os
def build_tracer(name, task, loader=None, hostname=None, store_errors=True,
Info=TraceInfo, eager=False, propagate=False, app=None,
IGNORE_STATES=IGNORE_STATES):
"""Return a function that traces task execution; catches all
exc... | 4b3526e3e7472e7f253617db9634fe33466057e6 | 3,618,174 |
def create_mvp_sample_similarity():
"""Create the most minimal Sample Similarity model possible."""
sample_similarity_result = SampleSimilarityResult(categories=CATEGORIES,
tools=TOOLS,
data_records=DATA_... | 8ec6b317407d7698832eab6a4ab88067577413d9 | 3,618,175 |
def show_items(location_id):
""" Show items for selected location
"""
locations = SESSION.query(Location).order_by(asc(Location.name))
location = SESSION.query(Location).filter_by(id=location_id).one()
items = SESSION.query(Item).join(User).filter(User.location_id == location_id).all()
if 'em... | 9f47e39143f5cae770adb41ea1d7e89179b1e983 | 3,618,176 |
import torch
def DiskPatch(tile=(8, 8), device='cuda:0'):
"""
Creates a disk patch
Parameters
----------
tile : (int,int) (optional)
the number of divisions of the disk (default is (8,8))
device : str or torch.device (optional)
the device the tensors will be stored to (default... | 8075353104094a3170644ee31b50ba6d69d34edf | 3,618,177 |
def fused_mb_conv_block(
inputs,
input_filters: int,
output_filters: int,
expand_ratio=1,
kernel_size=3,
strides=1,
se_ratio=0.0,
bn_momentum=0.9,
activation="swish",
survival_probability: float = 0.8,
name: str = "",
):
"""Fused MBConv Block: Fusing the proj conv1x1 and ... | 4789ea4bf8246d709921296c826b6ad232fada57 | 3,618,178 |
def read_xdr_var(buf, var):
"""
Reads a single variable/array from a xdrlib.Unpack buffer.
Parameters
----------
buf: xdrlib.Unpack object
Data buffer.
var: tuple with (type[,shape]), where type is 'f', 'd', 'i', 'ui',
or 's'. Shape is optional, and if true is shape of ar... | c970dc4d2c108baec4ee148db943ace0c6d8809e | 3,618,179 |
def diffMonths(d1, d2):
"""
Takes in two datetimes and calculates the difference
in months between them.
"""
return int(diffDays(d1, d2)/30.4) | 0ebf0791b47f1b4a3acd9d26e2b596bf093ee56b | 3,618,180 |
from typing import Iterable
def _fetch_events_for_all_contracts(
web3,
event,
argument_filters: dict,
from_block: int,
to_block: int) -> Iterable:
"""Get events using eth_getLogs API.
This method is detached from any contract instance.
This is a stateless method, ... | 80feaf1faafbb157a67070091774e30b0943673c | 3,618,181 |
from typing import Dict
from typing import Any
import requests
def get_local_status() -> Dict[str, Any]:
"""
Returns a running status if localhost:4040/api/v1/applications is reachable; othe
:return: Dict[str, Any]
"""
idle_cluster_state = {
"url" : "spark://simulated-local-mode-cluster:70... | 06f79d95e513cf91634345c96334f6af7f385fdf | 3,618,182 |
def total_points(min_x, max_x, points_per_mz):
"""
Calculate the number of points for the regular grid based on the full width at half maximum.
:param min_x: the lowest m/z value
:param max_x: the highest m/z value
:param points_per_mz: number of points per fwhm
:return: total number of points
... | e0680e386559a9603b3b23b9627bd8648b23e65a | 3,618,183 |
def get_investor_brokerage_transactions(investor_id, **kwargs):
"""
Returns a list of brokerage transactions for a given investor.
Arguments
---------
investor_id: int
Investor specified by the investorId returned from the investors
endpoint.
Keyword Arguments
-------------... | 22e67b9cc71a1fba419914a9b3f0b18d6dc422b6 | 3,618,184 |
import requests
from datetime import datetime
def _received_in_time(record, extra_data):
"""Check if publication is not older than 24h """
api_url = current_app.config.get('CROSSREF_API_URL')
api_response = requests.get(api_url + get_first_doi(record))
if api_response.status_code != 200:
retu... | 3022ef66cabcf55a975d781fb6d8258f1f66632d | 3,618,185 |
def merge_multiple_edge_attrs(main_graph, merge_graph, key, merge_type="mean"):
"""merge multiple
"""
edges = list(main_graph.edges)
for edge in edges:
try:
merge_edge_attrs(main_graph, merge_graph, edge, edge, key, merge_type=merge_type)
except KeyError as e:
edg... | eea3b82e7495b3b9522996df608374c514bf25b3 | 3,618,186 |
from functools import reduce
def core_count():
""" count number of cores in the local machine """
with open("/proc/cpuinfo","r") as procinfo:
return reduce(lambda a, b: a + b.startswith("processor"), procinfo, 0) | a9adc9ed3f88d5a8dd0175ffb7508adc14f4717e | 3,618,187 |
def AnalyticalSolution(a,b,c,d,e,eps):
"""
Source: https://en.wikipedia.org/wiki/Quartic_function#General_formula_for_roots
Calculates the value of the analytical solution.
"""
p=(8*a*c-3*b**2)/(8*a**2)
q=(b**3-4*a*b*c+8*a**2*d)/(8*a**3)
Delta0=c**2-3*b*d+12*a*e
Delta1=2*c**3 -9*b*c... | 7f6e3c9126f08475c13deeb90edfc0cb776ec9c0 | 3,618,188 |
def time_text_to_float(time_string):
"""Convert tramscript time from text to float format."""
hours, minutes, seconds = time_string.split(':')
seconds = int(hours) * 3600 + int(minutes) * 60 + float(seconds)
return seconds | 96d84804aad2cd094901e61373855604d4768894 | 3,618,189 |
def calc_adaptive_threshold(frate, pfit, bounds):
"""
calculates the adaptive threshold, based on the current firing rate, the
estimated peak reduction and the initially user set static bounds that are
to be adaptively modified.
Args:
frate (neo.core.AnalogSignal): the firing rate
p... | db412f25cd1f080edbd9109b529b3fa7d68d2b47 | 3,618,190 |
def longest_seq( tr ):
""" Given a tree, t, find the length of the longest downward sequence of node
labels in the tree that are increasing consecutive integers. The length of the
longest downward sequence of nodes in T whose labels are consecutive integers.
>>> t = Tree (1 , [ Tree (2) , Tree (1 , [ Tr... | 8f52c3c6f175bcf907682725359a734877bf8a3e | 3,618,191 |
import argparse
import sys
def parse_args(argv):
"""Parses command line arguments."""
parser = argparse_flags.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# High-level options.
parser.add_argument(
"--num_filters", type=int, default=32,
help="Number ... | 340ce86bce51accc6a7f74c2b7e98ea8c9904b72 | 3,618,192 |
def soil_evpa(Pt, EPt, WUt, WLt, WDt, C, WLM):
"""
三层蒸散发模型。
Parameters:
-----------
Pt: float, t时刻的降水量
EPt: float, t时刻对应的蒸发能力
WUt, WLt, WDt: float, t时刻对应的地表,浅层和深层土壤含水量
C: float, 浅层蒸散发折算系数
WLM: float, 下层土壤水含水容量
Return:
--------
EUt, EDt, ELt: float, t时刻对应的地表,浅层和深层蒸发水量
... | ee40efe16dc50a3c4bd5e49333ffa08206f06014 | 3,618,193 |
import json
import requests
import urllib
from typing import Iterable
def smiles_from_pdb(ligand_ids: Iterable[str]) -> dict:
"""
Retrieve SMILES of molecules defined by their PDB chemical identifier.
Parameters
----------
ligand_ids: iterable of str
PDB chemical identifier.
Returns
... | ec12fb14d968c278bf39b4c36448ba8069242f7a | 3,618,194 |
from typing import List
from typing import Dict
def incremental_build(new_content: str, lines: List, metadata: Dict) -> List:
"""Takes the original lines and updates with new_content.
The metadata holds information enough to remove the old unreleased and
where to place the new content
Args:
... | 7bb44732e278b4dd41ef4796b08b3e39548be4ef | 3,618,195 |
def get_template_groups_priorities(self) -> dict:
"""Get order that template groups will be applied in
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - template
- GET
- /template/templateGroupPriorities
:return: Re... | 398c716eb4a5c527acdbf6ae75d6ff5b2a2dbd37 | 3,618,196 |
from typing import Tuple
from typing import List
from datetime import datetime
def read_tides(path: str) -> Tuple[List, List]:
"""Read a CO-OPS tide data CSV file and return
a list of times and elevations."""
data = [line.strip() for line in open(path)]
time = []
elevation = []
for line in dat... | fcbe79a5ddedbaccd0bc0a9c317324881a774a78 | 3,618,197 |
def sigmoid(x):
"""Sigmoid activation function. For small values
(<-5) the sigmoid returns a value close to zero and for larger values (>5)
the result of the function gets close to 1.
Arguments:
x {tensor} -- Input float tensor to perform activation.
Returns:
tensor -- Output o... | 03ebc630aafb4f42ec29a4ab12094b20f1c01b74 | 3,618,198 |
import asyncio
def run_trio(proc, *args):
"""Call an asynchronous Trio function from asyncio.
Returns a Future with the result / exception.
Cancelling the future will cancel the Trio task running your
function, or prevent it from starting if that is still possible.
You need to handle errors you... | 10c4fa8bab5f2ac870b8205d8be893b117850b43 | 3,618,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.