content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def create_city_map(n: int) -> set:
"""
Generate city map with coordinates
:param n: defines the size of the city that Bassi needs to hide in,
in other words the side length of the square grid
:return:
"""
return set((row, col) for row in range(0, n) for col in range(0, n)) | fd30b936647bae64ccf2894ffbb68d9ad7ec9c6b | 58,100 |
def merge_layers(input_layer: str = None,
merge_layer: str = None,
merging_attributes: str = """[]""",
output_name: str = None,
context: str = None,
gis=None) -> str:
"""
Combines two inputs of the same feature data type into a n... | a5d263e8ece9ff3ba3999dd0927dba25abb580b5 | 58,101 |
def multi_replace(instr, search_list=[], repl_list=None):
"""
Does a string replace with a list of search and replacements
TODO: rename
"""
repl_list = [''] * len(search_list) if repl_list is None else repl_list
for ser, repl in zip(search_list, repl_list):
instr = instr.replace(ser, re... | b621d5dd574af3ebc2b08b79cae2514054ac1281 | 58,102 |
def delete_all_users(): # noqa: E501
"""Delete all users
Delete all users # noqa: E501
:rtype: object
"""
try:
DbUser.objects.delete()
res = {}
status = 200
except Exception as error:
status = 500
res = Error("Internal error", status, str(error))
re... | 679b012ce23875fc2ed5f9454414d06fd029d6cd | 58,103 |
def nullable(datatype):
"""Return the signature of a scalar value that is allowed to be NULL (in
SQL parlance).
Parameters
----------
datatype : ibis.expr.datatypes.DataType
Returns
-------
Tuple[Type]
"""
return (type(None),) if datatype.nullable else () | fe5935d1b4b1df736933455e97da29a901d6acb1 | 58,104 |
def calculate_optimal_capacities_tree(mu,sigma,gamma,K):
""" Calculate the optimal capacities for the five node tree network without allowing
to close the loop. These capacities can be calculated explicitly using the method of Lagrange multipliers (see Eq. 9)"""
flow_correlations = np.array([4*mu**2+2*sigma... | b4f74dbb9cebd666c6281f7436c9e24f19c83436 | 58,105 |
def dustVel_phi(f):
"""
Cylindrical tangential component of the dust velocity in the x-y plane
"""
return sutil.polar_phi_hat(f, 'u_dustVel') | 71a242d79ce7fc958c8d2f16c6a730bd901b2b38 | 58,106 |
import os
def TraverseByDepth(root, include_extensions):
"""
Return a set of child directories of the 'root' containing file
extensions specified in 'include_extensions'.
NOTE:
1. The 'root' directory itself is excluded from the result set.
2. No subdirectories would be excluded if 'i... | 68f510a0014c3ad8b511a2b024e6c1d4aef05732 | 58,107 |
def build_facets(data):
""" Data from facets-serves.json
Data structure:
{ "services" : [
{"(type)": "quolab...ClassName",
"id": "<name>"}
] }
"""
deprecated = {"casetree", "cache-id", "indirect"}
services = [service["id"] for service in data["services"]
if ... | 1b617180a3a5d3115c5300b91eebb3d6ca079942 | 58,108 |
from typing import Dict
def make_country_dict(
csv_file:str = 'data/country_list.csv') -> Dict[str, str]:
"""Make a dictionary containing the ISO 3166 two-letter code
as the key and the country name as the value. The data is read
from a csv file.
"""
country_dict = {}
with open(csv_fi... | 0334a2b2c918f407d1df682f56c14943f1e66c43 | 58,109 |
from typing import Optional
import ssl
import os
def get_custom_ssl_context() -> Optional[ssl.SSLContext]:
"""Potentially (if enabled), returns a custom ssl context that respect
self-signed certificates.
More accurately, may return an ssl context that respects a local CA
as a valid issuer.
"""
... | 9c7e8e608c74f07ad91637e3d2bd4b966127d5da | 58,110 |
import random
def get_samples_for_activation(class_names, X_val, Y_val):
"""get_samples_for_activation.
Returns sample images from the given data.
Sample images contain one image per class in the dataset.
:param class_names: class names of the dataset.
:param X_val: features of the dataset.
:... | 8d8a105cefb4e1b875e47f7010b32e9567c4ab60 | 58,111 |
from typing import List
import sys
def formatted_tb() -> List[bytes]:
"""Return a str of the last exception.
Returns
-------
str
"""
return format_tb(*sys.exc_info()) | 6d5fce10e6d38b2e39733f1c88fc77640d45516d | 58,112 |
def plot_pcolormesh(axis1,axis2,facedata,data,name,name2,surlabel,xlabel,ylabel,rotate):
"""
Plots parameter values for each cell using the pcolormesh function. Uses the corner point values output by corner_point_vals()
"""
if info==True:
print ('Making pcolormesh (colored_cells) of %(name)s sur... | 536010bcbe648e58bbde99e7893885a48a6080ab | 58,113 |
import platform
def host_arch_target():
"""
Converts the host architecture to the first part of a target triple
:return: Target host
"""
host_mapping = {
"armv7l": "arm",
"ppc64": "powerpc64",
"ppc64le": "powerpc64le",
"ppc": "powerpc"
}
machine = platform.m... | 7cae48c32e03cecb42e29279a93013ad3529c978 | 58,114 |
import torch
def prepare_img_cv2(img, dims):
"""
prepare image for forward pass.
returns a Tensor
"""
# type check
if not isinstance(img, np.ndarray):
raise TypeError("expected <np.ndarray>. got <{}>".format(type(img)))
img_dims = (img.shape[1], img.shape[0])
_img = (lett... | 2fbd5e2748229cd3916c89585dc4a0000f133fcc | 58,115 |
import regex
def safe_filename(filename, replacement="_"):
"""
Replace unsafe filename characters with underscores. Note that this does not
test for "legal" names accepted, but a more restricted set of:
Letters, numbers, spaces, hyphens, underscores and periods.
:param filename: name of a file as... | 0b7eff36482832a2a4615013be67a2a3fad7370b | 58,116 |
def most_words():
"""Return the session where most words were written"""
session_dict = {}
with open(trackdata_path, 'r') as t_d:
t_data = t_d.readlines()
for line in t_data:
t_ses = line.strip().split(', ')
session_id = t_ses[0]
session = Session(session_... | 8acc3332baf277000ecb0cc474843675f76087b4 | 58,117 |
import requests
import json
def ocr_space_url(overlay=False, api_key='must specify your own apikey', language='eng'):
""" OCR.space API request with remote file.
Python3.5 - not tested on 2.7 Register here to get free api key: -> https://ocr.space/ocrapi
:param url: Image url.
:param overlay: Is O... | ff16f026262383ccfca4b3de91d2b1fa09bbde32 | 58,118 |
from typing import List
def get_reputation_data_statuses(reputation_data: List) -> List[str]:
"""
collects reported statuses of reputation data
Args:
reputation_data: returned data list of a certain reputation command
Returns: a list of reported statuses
"""
reputation_statuses = [sta... | 2c41344f2970243af83521aecb8a9374f74a40ac | 58,119 |
def get_users_groups(db_session):
"""
Fetch current db users and groups.
"""
all_users = db_session.execute(sa.select([users]))
all_groups = db_session.execute(sa.select([groups]))
old_user_admin = [user for user in all_users if user.user_name == OLD_USER_ADMIN]
old_user_users = [user for us... | 707839c17e343a72867062c5531508353494be09 | 58,120 |
def is_number(val):
"""Check if a value is a number by attempting to cast to ``float``.
Args:
val: Value to check.
Returns:
True if the value was successfully cast to ``float``; False otherwise.
"""
try:
float(val)
return True
except (ValueError, TypeErr... | 89728d3d199c3ef5885529da5a2d13dd94fa590f | 58,121 |
def _GetBuildTestStatus(build_dict):
"""Get the build test status for the given build.
Fetch the build test status file from the builder for the build number,
specified in the build info dictionary given by |build_dict|.
Args:
build_dict: Build info dictionary.
Returns:
Build Test Status dictionary... | 94bf7ddf418b1f4d844de03ebd5f9d42c4fd22cc | 58,122 |
def test_do_svr():
"""
Test calling the Support Vector Regressor,
Fit the weight on the training set
Input
------
X: dataframe, n*m, n is number of data points,
m is number of features
y: experimental electrical conductivity
Returns
------
svr: objective, the ... | decbd49007bd7384190dc861f1c77d420298c756 | 58,123 |
def get_mean_coords(
aln_1, coords_1: np.ndarray, aln_2, coords_2: np.ndarray
) -> np.ndarray:
"""
Mean of two coordinate sets (of the same shape)
"""
mean_coords = np.zeros((aln_1.shape[0], coords_1.shape[1]))
for i, (x, y) in enumerate(zip(aln_1, aln_2)):
if x == -1:
mean_c... | f8d0c5dfe17484148378b45fbeaa2c598d5d71ac | 58,124 |
def Nabla_continuous(k_space,s_space=None,kfield=None):
"""
This function returns the differential operator represented in Fourier
space.
i 2 \pi \vec{k}
"""
if(about.hermitianize.status):
print 'It is not recommended to calculate derivatives in'
print 'Fourier s... | 7b88060e58fb3c3c000d8e2139797cfe0320e637 | 58,125 |
def get_local_name(element):
"""
Just the element name with the schema URI (if any) removed
@type element: Element
@param element: The XML element
@rtype: string
@return: the base name of the element or None if it could not be determined
"""
if element is None:
ret... | cef42ed650b2798c623f220686364f257e5f385f | 58,126 |
def read_csv(path, *args, **kwargs):
"""Emulates `pd.read_csv` from Pandas, but as a Beam PTransform.
Use this as
df = p | beam.dataframe.io.read_csv(...)
to get a deferred Beam dataframe representing the contents of the file.
"""
return _ReadFromPandas(pd.read_csv, path, args, kwargs) | c5f3e510c957997fb242c8541fedd3e699529878 | 58,127 |
def CheckPlayerWin(copy, available_numbers, size, player_icon, board):
"""Check if the player can win, if they can return the number that would block it"""
#duplicate = a dupilacate list of the current board
#duplicate_numbers = a duplicate list of the available numbers
for x in range(size):
... | 803d85163ca02762232a0eab199e2bb234b2df98 | 58,128 |
def compute_beta(T, S, z, rn_b0=rn_b0, rn_lambda2=rn_lambda2, rn_mu2=rn_mu2, **_):
"""
Compute the haline contraction
"""
Ta = T - T0
Sa = S - S0
beta = 1 / rho0 * rn_b0 * (1 - rn_lambda2 * Sa - rn_mu2 * z)
return beta | ebeeabad5dad3a848df9be6df8ca21b8d246484c | 58,129 |
def format_rfc3339(datetime_instance):
"""Formats a datetime per RFC 3339."""
return datetime_instance.isoformat("T") + "Z" | ad60a9e306e82554601efc1ae317296a59b009b0 | 58,130 |
def delete_employee(request, pk):
"""
View that enables to delete an employee
"""
EmployeeInput.objects.filter(id=pk).delete()
return redirect('/add_employees/') | 5d83ea573111584d39117a540114f643d2ec4f22 | 58,131 |
import random
async def exchange_random_row(individual_1: list, individual_2: list) -> list:
"""Exchange Random Row
This function is used for making the crossover between two individuals, in picks a random row an exchange it between the two
given individuals.
Args:
individual_1 (list): The ... | d029ee3084c89f6c4e42e0941997ffea6f3a3e67 | 58,132 |
def parse_arguments(args: list) -> Namespace:
"""Parses the arguments passed on invocation in a dict and return it"""
parser = ArgumentParser(description="A tool to combine multiple merge tools")
parser.add_argument('-b', '--base', required=True)
parser.add_argument('-l', '--local', required=True)
... | 1bdad99ba963bc00c37c40322c71eafd4cc8ce8e | 58,133 |
def get_nhnm():
"""
Returns periods and psd values for the New High Noise Model.
For information on New High/Low Noise Model see [Peterson1993]_.
"""
data = np.load(NOISE_MODEL_FILE)
periods = data['model_periods']
nlnm = data['high_noise']
return (periods, nlnm) | 188243930269446111bd6d7e8b816b0717093369 | 58,134 |
def embed(inp, n_inputs, n_features, fix_parameters=False):
""" Embed.
Embed slices a matrix/tensor with indexing array/tensor
Args:
x(~nnabla.Variable): [Integer] Indices with shape :math:`(I_0, ..., I_N)`
n_inputs : number of possible inputs, words or vocabraries
n_features : num... | e5a88a61894f225d3ae051be202d471427a4a4f8 | 58,135 |
import mimetypes
def send_file(file_like, cache_timeout, as_attachment, attachment_filename):
"""
Replaces flask.send_file since that uses an uwsgi function that is buggy.
"""
mimetype, _ = mimetypes.guess_type(attachment_filename)
response = Response(file_like.read(), mimetype)
if as_attachme... | c9170534bace16440e83fe2dc035aeac60633e58 | 58,136 |
import re
def get_poem_info(xml_file, lines_info, authors):
"""Poem parser for 'ECPA corpus'.
We read the data and find elements like title, author, year, etc. Then
we iterate over the poem text and we look for each stanza, line, word
and syllable data.
:param xml_file: Path for the poem xml file... | 470100314aff74dc10c4f59b49fea759c0267662 | 58,137 |
def get_ts_data_parts(X):
"""
Separates time series data object into time series variables and contextual variables
Parameters
----------
X : array-like, shape [n_series, ...]
Time series data and (optionally) contextual data
Returns
-------
Xt : array-like, shape [n_series, ]
... | b8d6227c90c484f8e4830c63c35332adac68bbbb | 58,138 |
def unpack_matrix(
x_packer: ArrayPacker, y_packer: ArrayPacker, matrix: np.ndarray
) -> xr.Dataset:
"""Unpack a matrix
Args:
x_packer: packer for the rows of the matrix
y_packer: packer for the columns of the matrix
matrix: the matrix to be unpacked
Returns:
a Dataset
... | 573727dc41dd06bdf59409e09519e995864d6020 | 58,139 |
def get_metadata_keys(options):
""" Return a list of metadata keys to be extracted. """
keyfile = options.get("keyfile")
if (keyfile):
with open(keyfile, "r") as mdkeys_file:
return mdkeys_file.read().splitlines()
else:
return None | 2451d54ae49690691e5b0ce019178fd119e3d269 | 58,140 |
def mswe(w, v):
"""
Calculate mean squared weight error between estimated and true filter
coefficients, in respect to iterations.
Parameters
----------
v : array-like
True coefficients used to generate desired signal, must be a
one-dimensional array.
w : array-like
E... | 44baa79639a8fdd8129175690110d35ba2dcd799 | 58,141 |
def extract_diagonal(utmat, axis=1):
"""Extract the diagonal elements of an upper triangular array.
Parameters
----------
utmat : np.ndarray[..., nprod, ...]
Upper triangular array.
axis : int, optional
Axis of array that is upper triangular.
Returns
-------
diag : np.n... | 4984991bb2801aa955a77fc4274f8197f4633ff4 | 58,142 |
import pandas
def timing(framenumbers, fpc):
"""Returns DataFrame, indexed by frame, containing useful clock variables
and their differentials.
Takes 'framenumbers', a sequence of frame numbers.
'fpc' is the number of frames per cycle of driving.
Returned DataFrame has column 'cycle', which coun... | f2b0c5c70556c5028b89cd421dd0eb3289dbd35e | 58,143 |
def text_line_break(text: str, max_line_length: int) -> list:
"""
Splits the given input text into multiple lines so that each line is shorter or equal to the given max_line_length
while minimizing the empty space at the end of each line. Longer empty spaces are weighted more heavily compared
to shorter... | e7eee4209f1bb7cdd9b40b3cdd5421d3031eca10 | 58,144 |
import os
import pickle
import json
def main(*, requests_per_senator=1, get_active_senators=False, get_adjacency=False,\
get_cosponsorship=False, get_cosponsors=False, get_committees=False, verbose=False):
"""
Given congress and chamber, fetches active senators
Args:
requests_per_senators:... | 4fc5777e24a2fa2b44d5ecb4cf6cc777e5250a62 | 58,145 |
import re
def normalize_arg(x):
""" Normalize user provided arguments to blockwise or map_blocks
We do a few things:
1. If they are string literals that might collide with blockwise_token then we
quote them
2. IF they are large (as defined by sizeof) then we put them into the
graph... | 424d3d938156266be69cde3f6eff35650d03760a | 58,146 |
def register():
"""
1. 获取参数
2.校验参数
3. 通过手机号取出验证码
4. 判断短信验证码是否过期
5. 删除redis中的短信验证码
6.判断验证码的正确性
7.创建用户对象
8.设置用户属性
9.保存到数据库
10. 返回响应
:return:
"""
# json_data = request.data
# dict_data = json.loads(json_data)
# 下面这句话等同于上面两句
dict_data = request.json
mo... | c1e554d1f5a26d72bea4f963bfa5393bb216181a | 58,147 |
def _load_wordlist(name, stream):
"""
Loads list of words or phrases from file.
Returns "words" or "phrases" dictionary, the same as used in config.
Raises Exception if file is missing or invalid.
"""
items = []
max_length = None
multiword = False
multiword_start = None
number_o... | 97ed03cfe39883b707f6027e7e5aeb4177e292cf | 58,148 |
import urllib
def geturlopen(hosturl, postdata={}, headers=HEADER):
"""
operate method
:param hosturl:
:param postdata:
:param headers:
:return:
"""
# encode postdata
enpostdata = urllib.urlencode(postdata)
# request url
urlrequest = urllib2.Request(hosturl, enpostdata, hea... | 5536343beaa27dc487a37315ffd284b991ed1167 | 58,149 |
def convert_to_tensor_or_ragged(value):
"""Coerce objects other than ragged tensors to tensors."""
return (value
if isinstance(value, (tf.RaggedTensor, GraphPieceBase))
else tf.convert_to_tensor(value)) | 272841c6a048da8175568defa1e83ef57b3ee0ab | 58,150 |
def compute_net_energy_current(udata, xx, yy, zz, xc, yc, zc, rho=0.000997, flux_density=False, maxr=None):
"""
Returns the integral of energy flux (Net energy current inside the Gaussian sphere)
Net energy current = \int_0^{R} (energy current density) \cdot dS dr
"""
eflux, rs = compute_ene... | c65b1b71c4dd2ed82ad043adb221d7c64a3520a1 | 58,151 |
def energy_tot(P, F, H, molecule):
"""
Compute total energy (electronic plus nuclear).
INPUT:
P: Density matrix
F: Fock matrix
H: Core Hamiltonian
MOLECULE: molecule, as a collection of atoms
OUTPUT:
ENERGY_TOT: total energy
"""
return energy_el(P, F, H) ... | c57ef1bc24415cdae0f49edfece79afd456f6c1e | 58,152 |
def get_threshold_metrics(y_true, y_pred, drop=False):
"""
Retrieve true/false positive rates and auroc/aupr for class predictions
Arguments
---------
y_true: an array of gold standard mutation status
y_pred: an array of predicted mutation status
drop: boolean if intermediate thresholds are... | 58e7a29aa9329a0fec83754c37ace2efe1eb17f9 | 58,153 |
def generate_keys_rsa(taille=2048,mypass=b'password'):
""" Fonction generate_keys_rsa(taille=2048,mypass=b'password') permet générer une paire de clé RSA
elle prend en paramètre la taille de clé et le mot de passe pour protéger le clef privée
et reourne un tri-tuple (key, privatekey, publickey).Par défaut le mot d... | e063c7c66f45283bc06639a3013b81e96c162ec3 | 58,154 |
def hex_reflect_y(x, y, z):
"""Reflects the given hex through the x-axis
and returns the co-ordinates of the new hex"""
return x, z, y | 92f36567d26ae8e942d3dad269cc3f196c8fbe16 | 58,155 |
def test_assert_prop(): # noqa: D202
"""Test assert_ro_prop function behavior."""
class MyClass1(object):
def __init__(self):
self._value = 1
def getter(self):
return self._value
def setter(self, value):
self._value = int(value)
value = pr... | a151de3d7927c65b12160cbe20d9dde61085a7fa | 58,156 |
from .._mesh import Mesh
def create_submesh(
mesh, vertex_mask, face_mask, ret_indices_of_original_faces_and_vertices=False
):
"""
Apply the requested mask to the vertices and faces to create a submesh,
discarding the face groups.
"""
new_v = mesh.v[vertex_mask]
indices_of_original_vertic... | fa990c8d720cdb04c675380cf4d0bdc7ad424a69 | 58,157 |
def fixipmapping(ipparams, posflux, etc = [], retbinflux = False, retbinstd = False):
"""
This function returns the fixed best-fit intra-pixel mapping.
Parameters
----------
ipparams : tuple
unused
bestmip : 1D array, size = # of measurements
Best-fit ip mapping
... | 481257ccc956516db44942244630bb16b1c1c147 | 58,158 |
def request_windows_username_and_password():
"""
get user's information so that we can build a user for her on each minion.
Windows and MacOS do not have a well-defined method for deploying a password hash,
so we are stuck with storing a plain text password.
"""
print()
print('NOTE:')
p... | 421d10c58dbb75faee6667fdd9023daa944ae6bb | 58,159 |
def get_adjacent_coordinates(row, col):
"""Get possible adjacent coordinates for (row, col)."""
adjacent = []
for change_row, change_col in MOVES:
next_row = row + change_row
next_col = col + change_col
if not ((0 <= next_row < 5) and (0 <= next_col < 5)):
continue
... | 352ddd9a1fba36d3e0feada594c40de8176a3195 | 58,160 |
def pool_restart(state, modules=None, reload=False, reloader=None, **kwargs):
"""Restart execution pool."""
if state.app.conf.worker_pool_restarts:
state.consumer.controller.reload(modules, reload, reloader=reloader)
return ok('reload started')
else:
raise ValueError('Pool restarts n... | 09c16f8bc5e652357d97ec3f9df33bdcd6a241d6 | 58,161 |
import json
def getFileTree(frame, dir):
"""
Get the TreeView structure (recursive way)
"""
frame.cmd_return = ""
frame.exec_cmd("\r\n")
result = frame.exec_cmd("os.listdir(\'%s\')\r\n" % dir)
if result == "err":
return result
filemsg = result[result.find("["):result.find(... | 64f7d9aba936476560b506b907cb36a6e1bee734 | 58,162 |
def get_competitions():
"""Returns all competitions running and their id"""
competitions = [competition.to_json() for competition in Competition.query.all()]
return jsonify(competitions) | beb58c45bcf014a20ad48832025dde78989106de | 58,163 |
def _unpickle_method(name, im_self, im_class):
""" Unpickles an instancemethod object. """
if im_self is not None:
return getattr(im_self, name)
else:
return getattr(im_class, name) | 71b7b81be74088f7060c78e706b4646c1f2e613d | 58,164 |
def infer(chip_path, learner):
"""Run inference on a chip
Arguments:
chip_path {Path} -- Location of a single chip
learner {fastai2 model} -- Loaded fastai2 pkl file
"""
_, _, pred_class = learner.predict(
chip_path
) # Currently returns classes [not bilge, bilge, vessel]
... | aba5bcb9427247bb5bd4c390fbd07a4a493d3501 | 58,165 |
def remap(dictionary, mappings):
""" Remap dictionary using new mappings.
Note that the order of items will not be preserved when two keys are combined.
"""
result = defaultdict(list)
for tier in dictionary:
result[mappings[tier]].extend(dictionary[tier])
return result | 0fd203d6f2befc2bde40d7a7c71cf602768bc5d4 | 58,166 |
import glob
import os
def list_dir_no_hidden(path):
"""
List all files in a directory, except for hidden files.
Parameters
----------
path : str
The path of the directory whose files we wish to list.
"""
return glob(os.path.join(path, "*")) | 6db80ddd06e2cb25d431fa2072280e635aaeca55 | 58,167 |
import string
def create_arabic_trans_table():
"""
Return a mapping of Eastern Arabic Unicode ordinals to Western Arabic Unicode ordinals,
which can be used by the unicode-string.translate() function.
"""
eastern = [ord(char) for char in constants.EASTERN_ARABIC_DIGITS]
western = str(string.di... | fa92f103222dcbb613eab06b229fe223e3568815 | 58,168 |
def geometry(smi):
""" cartesian geometry of the atoms in a SMILES string
:param smi: SMILES string
:type smi: str
:returns: atomic symbols and their cartesian coordinates
:rtype: list of pairs of strings and triples of floats
"""
pbmol = _pybel_molecule(smi)
anums = atomic_numbers(smi... | 001be1925186642fbc962f030f3f2946780eeb02 | 58,169 |
def plug_has_connections(plug, nested=False):
"""Return True if ``plug`` has any source or destination connection.
Convenience function that run both `.plug_has_source` and
`.plug_has_destinations`.
Args:
nested (bool): If True, extend the check to all children in ``plug``
hierarch... | 757bbf127a4711ea8dfd937ada1fea7eba4449ef | 58,170 |
def is_unexpected(actual, expected):
""" evaluates if there is a parameter in actual that does not exist in expected """
if expected is None:
unexpected = actual
else:
unexpected = filter(lambda x: x not in expected, actual)
return unexpected | d0de1d2505e5ad78b5d465b2496b0a154fe0c237 | 58,171 |
def AAfilledRoundedRect(surface,rect,color,radius=0.4):
"""
AAfilledRoundedRect(surface,rect,color,radius=0.4)
surface : destination
rect : rectangle
color : rgb or rgba
radius : 0 <= radius <= 1
"""
rect = pygame.Rect(rect)
color = pygame.Color(*color)
al... | 7c2e26cbceab41a3c95c876f7c50cb20c35a5298 | 58,172 |
def get_opcode(ref_base, alt_base):
"""
Get the opcode for the operation needed to convert a the given reference base into the given alt base
:param ref_base: Character representing the reference base
:param alt_base: Character representing the alternative base
:return:
"""
if ref_base... | 9198e80dca0edfc997bc6477c87ca83afa1719ee | 58,173 |
def get_mesh_pyfunc(points, dim=2, periodic=False):
""" get mesh wrapped in a pyfunc."""
# partial_fn = functools.partial(
# DelaunayTriangulation if dim==2 else get_tetrahedron, periodic=periodic)
faces = tf.py_function(
_DelaunayTriangulationFaces if not periodic else (if dim==2 Periodic_2_tria... | 19b66c30b67739fea37df218a4f6c3e976b03e70 | 58,174 |
def analyze(problem, X, Y, M=10, num_resamples=100, conf_level=0.95, print_to_console=False, seed=None):
"""Performs the Random Balanced Design - Fourier Amplitude Sensitivity Test
(RBD-FAST) on model outputs.
Returns a dictionary with keys 'S1', where each entry is a list of
size D (the number of para... | 4229585654d26b1d7f07af2e61f81a1317315069 | 58,175 |
def _is_parent(a, b):
# type: (PredContext, PredContext) -> bool
"""
Return true if a is a parent of b, or equal to it.
"""
while b and a is not b:
b = getattr(b, 'parent', None)
return a is b | 574d93d924b0fdbbaeccc2491c9814a283c44d5f | 58,176 |
def prepare_tf_data_unbatched(xs):
"""Prepare TF dataset into unbatched numpy arrays."""
# Use _numpy() for zero-copy conversion between TF and NumPy.
# pylint: disable=protected-access
return jax.tree_map(lambda x: x._numpy(), xs) | 5fd2f1585f2e4a2061ae462ba3004ddd6044c759 | 58,177 |
def filter_noise(img, noise_mode, noise_ratio=0.01):
"""Add noise to an Image.
Args:
img (PIL Image): PIL Image to be added noise.
noise_mode (str): salt or gaussian noise.
ratio (float): The ratio of noise strength. salt:0.01 gaussian:10
Returns:
PIL Image: Add noise ima... | 6ebc89a4bc84d614e105face369c10b81f7b330c | 58,178 |
def is_command(string, tokens=None):
"""Check whether given string is considered to be a command.
:param string: The string, i.e command, to check
"""
if not string:
return False
if is_comment(string):
return False
if is_quoted(string):
return False
if is_script(s... | 3752b9e3ae541aaf4b596869248dc60a5ae3ce2a | 58,179 |
def _observedFromPupilCoords(xPupil, yPupil, obs_metadata=None,
includeRefraction=True,
epoch=2000.0):
"""
Convert pupil coordinates into observed (RA, Dec)
@param [in] xPupil -- pupil coordinates in radians.
Can be a numpy array or a number.
... | d9f07aae6d398262b5f0f537fa2bb2c0b178fd04 | 58,180 |
def default_endpoint_from_config(config, option=None):
"""Return a default endpoint."""
default_endpoint = config.get('core', {}).get('default')
project_endpoint = config.get('project',
{}).get('core',
{}).get('default', default_end... | a9ead6627c4d6c6513c33d99e7d392f531df15cd | 58,181 |
def get_registered_packages():
"""Returns the list of packages known to the site
>>> import zoom.request
>>> zoom.system.request = zoom.request.Request(dict(PATH_INFO='/'))
>>> zoom.system.site = zoom.site.Site(zoom.system.request)
>>> zoom.system.request.app = zoom.utils.Bunch(packages={})
>>... | 2e59f74ed3c3e6ca32e657726edda8780e478144 | 58,182 |
def build_condition(filter_map, using=CONDITIONS):
""" Implement the conditions described in
docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Condition.html
"""
if not filter_map:
return
filters = {}
dynamizer = Dynamizer()
for field_and_op, value in filter_map.items():
... | 930c8d9fc34429697dee320394b75ed26d4a715a | 58,183 |
def _remove_self(d):
"""Return a copy of d without the 'self' entry."""
d = d.copy()
del d['self']
return d | a80eca3886d0499d1871998501c19e9cdae93673 | 58,184 |
import zlib
def read_blob_data(filename, blob_pos, blob_size):
"""
Returns the (unzipped) blob data from filename and position.
"""
with open(filename, 'rb') as f:
f.seek(blob_pos)
blob_data = f.read(blob_size)
blob = OSMPBF.Blob()
blob.ParseFromString(blob_data)
r... | f8b389c84d18dd1b3de790714ff12a40669c3a04 | 58,185 |
import hashlib
def machine_id():
"""Return a unique machine id that survives reboot and SW upgrades.
Uses /proc/cpuinfo because /var/lib/dbus/machine-id is the same for all
docker images that inherit/extend the same base image. Also, anybody that
have access to any of those images can read the machin... | 213e6564c46dd9f0a498446addd21fe90c5768e1 | 58,186 |
def one_to_index(s):
"""
One letter code to index.
For example: A to 0.
"""
return d1_to_index[s] | e2d6035f2c432638b7141ac82b95e9ff699aee8b | 58,187 |
def deltanpq(phino, phinoopt=0.2):
"""Calculate deltaNPQ
deltaNPQ = (1/phinoopt) - (1/phino)
:param phino: PhiNO
:param phinoopt: Optimum PhiNO (default: 0.2)
:returns: deltaNPQ (float)
"""
return (1/phinoopt) - (1/phino) | 34d44a732bd87eb78e8ddee92b4555bea67789be | 58,188 |
def conv_from_stripe_amount(
stripe_amount,
curr,
zero_decimal_currs=ZERO_DECIMAL_CURRS
):
"""Converts the given amount used for Stripe to the one used by Indico.
:param float indico_amount: The amount used for Stripe.
:param str curr: The ISO code of the currency being used.
:param zero_de... | 4e47b9079901740467b18c6169838489edcf5a2f | 58,189 |
def diff_max(value_a, value_b, position_a, position_b):
""" Retorna o maior valor entre 2 valores """
# Cod 100 - Equal
# Cod 101 - No image
if not value_a or not value_b:
return 101, 0
if value_a > value_b:
return position_a, round((value_a - value_b), 2)
elif value_a < value_b... | 9fa578e3bf352e29d4cef96d7809f9797560d9cc | 58,190 |
import os
def repeat_masking_job(job, input_fasta, species):
"""Do the actual RepeatMasking for each chunk."""
temp_dir = job.fileStore.getLocalTempDir()
os.chdir(temp_dir)
local_fasta = os.path.join(temp_dir, 'input.fa')
job.fileStore.readGlobalFile(input_fasta, local_fasta, cache=False)
chec... | 69e2f567055ec1472c007d8012906774d8df1c8f | 58,191 |
import posixpath
def get_image_url(repo_name: str, short_name: str=None, absolute: bool=True) -> str:
"""
Return an absolute docker image URL
:param repo_name: name of the docker repository (challenge name)
:param short_name: [optional] e.g. solvable or controller
:param absolute: [optional] retu... | 2376e6471f4d2148172c5d2d3d1e668bb25c9cc2 | 58,192 |
def ScrewDislocation(origin, line, b, cut=None, debug=None):
"""Set up a straight screw dislocation.
Set up a straight screw dislocation through a specified point with
a given burgers vector. The first argument ('origin', a 3-tuple)
specifies a point on the dislocation line, the second ('line', a
... | 5fa40d988e7d5f7caca6ad16d309f5463968ee24 | 58,193 |
def html_string(request, html_file):
"""NYU Academic Calendar HTML as string"""
return html_file.read() | c0879d51a97b643f110ad2134dc7afe9dd279b66 | 58,194 |
def numba_cuda_basis_brownian_expect(x, time, delta_t, order_of_basis):
"""Calculate the expectation of arithmetic weight average multiplied by brownian motion"""
basisvalue = np.zeros((x.shape[0], order_of_basis, NUM_OF_BROWNIAN_MOTION))
basisvalue[:, 0, :] = 0.
if order_of_basis > 1:
for k in ... | 02e6e6828da893613cef183d4b30470c04a9ce02 | 58,195 |
def ConvertFieldRef(field_id, field_name, field_type, approval_name):
"""Convert a field name and protorpc FieldType into a protoc FieldRef."""
return common_pb2.FieldRef(field_id=field_id,
field_name=field_name,
type=ConvertFieldType(field_type),
... | 80388496c35bf434a2639e3f1dda060246e40279 | 58,196 |
def filter_stack_in_3dirs_3dfilter(volume_in, custom_filter):
"""
volin - input 3D volume
filter - input nD filter
"""
volout = np.zeros(volume_in.shape, dtype='float32')
volout = ndi.convolve(volume_in, custom_filter) # filter in axial direction
voltmp = ndi.convolve(np.swapaxes(v... | 08ce9983412ccf9d380e947733cc836d604577cd | 58,197 |
def _read_gadget_binary(filename):
"""
Reads a gadget binary specified by filename
"""
positions_dtype = np.dtype([("x", 'f'),
("y", 'f'),
("z", 'f')
])
header_dtype = np.dtype([('npart', ('i', 6)),
... | 57279b8f5e68ea530df03b7fc819cabcfda62de0 | 58,198 |
import torch
def l2norm(X):
"""L2-normalize columns of X
"""
norm = torch.pow(X, 2).sum(dim=1, keepdim=True).sqrt()
a = norm.expand_as(X)
X = torch.div(X, a)
return X | 404c5e1b7241cae336bc56c675a78d4e14b6dd9a | 58,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.