content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def looper(f, delimiter=''):
"""Returns a function that applies function f to every element of an iterable."""
return lambda iterable: delimiter.join([str(f(i)) for i in iterable]) | fb7e52c0b1e8aac8919f6ed9041d7e2eaaca8816 | 3,604,764 |
def extract_corrections_from_parallel_tokens(orig_text, orig, cor):
"""
corrections:
[['I', 'I', [0, 1]],
['went', 'went to', [2, 6]],
['school', 'school', [7, 13]],
['this ysterday', 'yesterday ', [14, 27]]]
"""
_, _, _, edits = token_level_edits(orig, cor)
align_orig_tokens = [i[0]... | 0b3b9c25999e0ddabd654d67e618de556859b8a1 | 3,604,765 |
def render_colored_batch(m_v, m_f, m_vc, width, height, camera_f, camera_c, bgcolor=np.zeros(3, dtype=np.float32),
num_channels=3, camera_t=np.zeros(3, dtype=np.float32),
camera_rt=np.zeros(3, dtype=np.float32), name=None,batch_size=None,cam_pred=None):
""" Render a... | 865a5059af6335e6f8ed7ccbfd8c09627446f98a | 3,604,766 |
def form_concat_RE(re1, re2):
"""Helper for del_one_gnfa_state
---
Given two non-eps REs, form their concatenation.
"""
if re1=="":
return re2
elif re2=="":
return re1
else:
return ('.', (re1, re2)) | 621906db027421ffb03569671163fd2f6c2cac8c | 3,604,767 |
def moon_coordinates(time, cam):
"""This function searches for the moon position at a given time.
Parameters
-----------
time: 'astropy.time.core.Time'
Time the image was taken.
cam: 'str'
Camera
Returns
-------
moon_altitude: 'float'
Altitude of the moon at the... | 478025ec25f5e4f2ac7836a66f4a0de4e3916df8 | 3,604,768 |
def get_id_from_mnemonic(uniprot_mnemonic):
"""Return the UniProt ID for the given UniProt mnemonic.
Parameters
----------
uniprot_mnemonic : str
UniProt mnemonic to be mapped.
Returns
-------
uniprot_id : str
The UniProt ID corresponding to the given Uniprot mnemonic.
... | e81ea484de19e71bde7e9f306fefa03f908444ef | 3,604,769 |
def compare_arrays(array_a, array_b):
"""compare array a and array b values"""
comparison = array_a == np.array(array_b)
return comparison.all() | 19ba30ca154a467c3bf8336a2746789dc406e9ca | 3,604,770 |
def Jaccard3d(a, b):
"""
This will compute the Jaccard Similarity coefficient for two 3-dimensional volumes
Volumes are expected to be of the same size. We are expecting binary masks -
0's are treated as background and anything else is counted as data
Arguments:
a {Numpy array} -- 3D array... | 0c5e7be04f596736ab0184b2799708350691c240 | 3,604,771 |
def get(name):
"""Get a particular setting buy name.
This function does not return copies, so be careful not to mutate objects.
Raises IndexError if the setting does not exist.
"""
global settings
ensure_loaded()
return settings[name] | 1113effc449b00427faee9be92d0e25edd512dc2 | 3,604,772 |
def human_size(size):
"""
递归实现,精确为最大单位值 + 小数点后三位
:param size: 字节大小
:return:
"""
def strofsize(file_size, file_remainder, unit_level):
if file_size >= 1024:
file_remainder = file_size % 1024
file_size //= 1024
unit_level += 1
return strofsi... | c502a42fc111f6c985e6c5ccdca76b99a02707be | 3,604,774 |
def polarizability(prog, output_str):
""" Reads the polarizability tensor from the output string.
Returns the dipole moment in _.
:param prog: electronic structure program to use as a backend
:type prog: str
:param output_str: string of the program's output file
:type output... | 3b4a0e0246f3708dde13c77ae468e83eac58e842 | 3,604,775 |
def alterar_funcionario_da_obra(request, id):
""" Atualiza Funcionario_da_Obra."""
funcionario_da_obra = Funcionario_da_Obra.objects.get(id=id)
form = Funcionario_da_ObraForm(
request.POST or None, instance=funcionario_da_obra)
if form.is_valid():
form.save()
return redirect("fun... | 21bdd6a8a6728b5b63f2502e10cf76e4ee19d2fa | 3,604,777 |
import typing
def validate(
instance: typing.Union[dict, list],
schema: dict,
path: typing.Optional[typing.List[str]] = None
) -> None:
"""
Validates the given instance using the given schema and raises a ValidationError if it is invalid.
:param instance: the sampledb object
:... | 60f7bbc0d44dfb206a81220aaa0284747932dc2d | 3,604,778 |
import time
async def insert_new_account(name, cur: Cursor, description="", ntime=None):
"""create new account by name"""
assert isinstance(name, str)
if name.startswith('@'):
raise BlockChainError('prefix"@" is root user, name={}'.format(name))
ntime = ntime or int(time() - V.BLOCK_GENESIS_TI... | 62fbcb704d0efebb7185d3e20ce5dc269ebe5e18 | 3,604,779 |
def meshWeightDataToString(msh, vmap):
"""Convert mesh group and weight data to strings."""
ret = []
for ii in msh.vertices:
grp = []
for jj in ii.groups:
# Check for aberrations.
if 0.0 > jj.weight:
raise RuntimeError("invalid vertex weight: %f" % (jj.weight))
grp += [[jj.weight... | ec92db8440ed39fffd2ca48332c86a69a6c29116 | 3,604,780 |
def posts_delete(request):
"""Logic to handle requests and return responses."""
context_data = {"title": "Delete"}#
return render(request, "index.html", context_data)
#return HttpResponse("<h1>Delete<h1>") | 4dcb5508d9fc2d6a179b7eb8e3cb3ee7e3d04a51 | 3,604,781 |
def generate(target, n=1):
"""Randomly generate n grammatical sentences for the target."""
if target not in grammar or n <= 0:
return []
return [_generate(target).strip() for _ in range(n)] | c0d9c2fc93690370d7ca9e20e3a41b0b20b97dc8 | 3,604,782 |
import token
def remove_argument(filename, trailer_node, key):
"""
remove "key" from arglist in trailer_node,
"""
if trailer_node.type != python_symbols.trailer and len(trailer_node.children) != 3:
log_warning(filename, trailer_node.get_lineno(), "node type is not trailer or len(children) != 3... | 57d847bc1ed22bff050f7ce0bff4cca5022b9af1 | 3,604,783 |
def batch_symmetrize(input_matrix, batch_size, n_nodes):
"""
Take an n_nodes - 1 x n_nodes matrix and symmetrizes it.
It concatenates a row of zeros with the matrix,
adds the transpose and then removes the padded row.
Parameters
----------
input_matrix: theano tensor
batch_size x n_n... | 21eab63d4a70599df1762449818f5517166fbcf6 | 3,604,784 |
def convertLSRToRADEC(xyzuvw_lsr, kpc=False):
"""
Generate astrometry values from cartesian coordinates in LSR frame
Paramters
---------
xyzuvw_lsr : [6] (or [nstars, 6] ???) array
[pc, pc, pc, km/s, km/s, km/s]
kpc : boolean {False}
set this flag if input is in kpc not pc
... | 7c720faa60eb2dff1f2ee7f0b0a63cba1f1ab5f1 | 3,604,785 |
def receive_messages(queue, max_number, wait_time):
"""
Receive a batch of messages in a single request from an SQS queue.
Usage is shown in usage_demo at the end of this module.
:param queue: The queue from which to receive messages.
:param max_number: The maximum number of messages to receive. T... | 4cb76d05a78e404689d83a450d0b6eacbd09e0e0 | 3,604,786 |
def WndProc(hwnd, message, wParam, lParam):
"""Window procedure"""
global bWndProcFlag
if message == 289 and not bWndProcFlag:
bWndProcFlag = True
user32.PostMessageW(hwnd, 256, 40, 0)
user32.PostMessageW(hwnd, 256, 39, 0)
user32.PostMessageW(hwnd, 513, 0, 0)
return ... | 6a8ed37b60cfb8b6aa55930d7046e908896aedb9 | 3,604,787 |
from re import S
def superm2(image):
"""Performs the symmetry detection on image.
Somewhat clunky at the moment -- first you
must comment out the last two lines: the
call to `draw` and `cv2.imshow` and uncomment
`hex` call. This will show a 3d histogram, where
bright orange/red is the maximu... | c44833d668be46703467d3a1839c32688d6e16d8 | 3,604,788 |
def static_ball(p, radius):
"""Creates a ball that remains fixed in place.
:param p: The center point of the ball
:type p: (int, int)
:param radius: The radius of the ball
:type radius: int
:rtype: shape
"""
return _ball(p, radius, pymunk.inf, True) | 0aa94e6ed7fdfb445bc38e2d93d08924b6fb6010 | 3,604,789 |
def calc_tree_limit(az):
"""Calculates tree limit in altitude for given azimuth.
Returns alt_limit in degrees.
Input: azimuth in degrees.
"""
#Define Tree limits as np.array
#I put zero alt limit, where horizontal or cupboard limit is reached,
#because we do not care about tree limits ... | 7e2b192a8163d90311ad9c7cc7c6a5abd34e655d | 3,604,790 |
def create_credentials(account, user_name, password):
"""
Function to create a new credentials
"""
new_credentials = Credentials(account, user_name, password)
return new_credentials | 7b165164af2c66410c2fe5a4519b98bc60474ca6 | 3,604,791 |
import typing
def fixed_format_items(items: ITEMS_TYPE) -> typing.List[str]:
"""Format items using a fixed with formatter.
:param items: iterable of templates or strings
:return: formatted string
"""
items = list(items)
with np.printoptions(floatmode="maxprec"):
template_lengths = [l... | 14efb8d52266538380be7ce279583c7185984ff5 | 3,604,792 |
from datetime import datetime
def format_timestamp(timestamp) -> str:
"""Format a unix timestamp in ISO date format"""
try:
return datetime.fromtimestamp(timestamp, tz=timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
except TypeError:
return str(timestamp) | 38e03e90e3711f9939c425751b9e01528331d7c8 | 3,604,793 |
def redirect_to_link(name, optional_argument=None):
""" Used to redirect to a GoRecord """
record = GoRecord.query.filter_by(name=name).first()
if record is None:
return redirect(url_for('golink_search', search=name))
link = record.link(optional_argument)
return redirect(link) | 8039aacc1c90d5ec104b1545d833b05dbbf1458c | 3,604,795 |
def disable(name, **kwargs):
"""
Disable the named service to start at boot
Args:
name (str): The name of the service to disable
Returns:
bool: ``True`` if disabled, ``False`` otherwise
CLI Example:
.. code-block:: bash
salt '*' service.disable <service name>
"""... | 6a182c9bafa713db17340914fe241c186459e4f5 | 3,604,796 |
def strip(value):
"""
REMOVE WHITESPACE (INCLUDING CONTROL CHARACTERS)
"""
if not value or (ord(value[0]) > 32 and ord(value[-1]) > 32):
return value
s = 0
e = len(value)
while s < e:
if ord(value[s]) > 32:
break
s += 1
else:
return ""
fo... | 380f2cdf5580b1dff02ff8e377942d443917842f | 3,604,797 |
def is_behind_right_down(tile_ref, tile_test):
"""
Les fonction is_behind_xxx permettent de savoir si une tile est "derrière" une autre tile,
par rapport à la direction de conquête de Player (rightward, downward).
Renvoie True si tile_test est derrière tile_ref.
"""
return tile_test.x <= tile_re... | 18677d7d646ada9963bc0a15c88df59c38895605 | 3,604,798 |
def grad_var_name(var_name):
"""
return gradient name for a certain var name
"""
return var_name + GRAD_VAR_SUFFIX | 106a0999604979109dce269d4ffb85a5e11d151c | 3,604,799 |
def accuracy(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
maxk = max(topk)
batch_size = target.size(0)
# (batch, feature),从每个feature选择topk
_, pred = output.topk(maxk, 1, True, True)
# 转置
pred = pred.t()
correct = pred.eq(target.view(1, -1).exp... | a0b57d35d85e58adbf4e9c9e405c440925ee1e0b | 3,604,800 |
def qdqL2(x, levels, bucket_size=1024):
"""
Quantize and dequantize with L2 norm.
x: the input vector (numpy.ndarray)
levels: either levels_uni for QGSD or levels_exp for NUQSGD
bucket_size: we split our big vector to multiple buckets of size
bucket_size for quantizing
returns... | 90fe7f06c0772a4d117d60f91abac990203a0041 | 3,604,801 |
def _PromptForRegion():
"""Prompt for region from list of available regions.
Returns:
The region specified by the user, str
"""
if not console_io.CanPrompt():
return None
all_regions = constants.SUPPORTED_REGIONS_WITH_GLOBAL
idx = console_io.PromptChoice(
all_regions, message=('Please specif... | 761bc801b511bff63691496fb5d145804c897061 | 3,604,802 |
def solution(limit: int = 1000000) -> int:
"""
Return the number of different square laminae that can be formed using up to
one million tiles.
>>> solution(100)
41
"""
answer = 0
for outer_width in range(3, (limit // 4) + 2):
if outer_width**2 > limit:
hole_width_low... | ab0392b83d71d63fc6beeabd6c2a8b43d49de8db | 3,604,803 |
def get_user(user_id: int, user_serivce: UserSerivce = Depends()):
"""Get particular user."""
return user_serivce.get(user_id) | f201069bee6c1b08e888e69ceec8f371153e555f | 3,604,804 |
def compute_paglm_weights(f,suff,interval,dt,Cinv=None):
"""
This function computes the paglm weights given a nonlinearity, sufficient
statistics, bin size, and optional prior over an approximation interval.
"""
# if Cinv is none, make prior a matrix of zeros
if Cinv is None:
Cinv = np.... | 64dc99377ffda2b7b0382ab11075513172de77eb | 3,604,807 |
def inner_info_nec_lower(scores):
"""InfoNCE estimator for I(diX;T) - van den Oord et al. (2018):"""
nll = np.mean(np.diag(scores) - jax.scipy.special.logsumexp(scores, axis=1))
K = scores.shape[1]
mi = np.log(K) + nll
return mi | f0ec7ec3461cf3a0b664866930bb85ab247d7768 | 3,604,808 |
def imputation(matrix, nan_filling):
"""
takes in matrix dataframe and value for filling in NaNs for imputation
Parameters: matrix dataframe, NaN filling value
Returns: imputed matrix dataframe
"""
matrix.fillna(nan_filling, inplace=True)
return matrix | a6981e54f6228e9ebfcbb6ea65e5305f50a327ca | 3,604,809 |
def compute_precision(model, x, y, reverse_data_dictionary, next_compatible_tools, usage_scores, actual_classes_pos, topk):
"""
Compute absolute and compatible precision
"""
absolute_precision = 0.0
test_sample = np.reshape(x, (1, len(x)))
# predict next tools for a test path
prediction = m... | f8df82ffafa4f9923b4f401538cd29ca29eb5ffe | 3,604,810 |
def get_app_foldername(path):
"""Gets the app name based on a path"""
if not is_file(path):
return ""
s = path.split("/")
if not (len(s) >= 2):
return ""
if s[0] == "examples":
if s[-1].endswith(".py"):
return ((s[-1])[:-3])
else:
return ""
else:
return s[-2] | d7943202bf7034ae06c43b0b3ea309bc9141ba04 | 3,604,811 |
import uuid
import html
def make_individual_project_explorer_layout(rubicon_model, commit_hash, page_size):
"""The html layout for an individual project explorer view determined by
`commit_hash` in the dashboard.
A project explorer view shows a subset of experiments logged
to a project in a tabular f... | 1424ab76090c4c8d123799fe30711f21e07eda39 | 3,604,812 |
def constant(interp, constname):
""" Returns the value of a constant"""
w_obj = _lookup_constant(interp, constname)
if w_obj is None:
interp.warn("constant(): Couldn't find constant %s" % constname)
return interp.space.w_Null
return w_obj | 02ed99875283d05b01e2f0e2534a3ebf9f7e9371 | 3,604,813 |
def display_select(context, element, options, id_object):
"""displays a select list based on the element"""
sel_part = "<select class=\"%s form-control\" name=\"%s\" id=\"%s\">" % (
layout_extras.tooltip_class(element.name),
element.name,
element.name,
)
selected = _form_value(co... | b3cbdfcfff0309a54b9ab81df4ccc1e7fa9e64b2 | 3,604,814 |
def stratified_grouped_fold(D, stats, K, strata='runs'):
"""Add a folding to the data.
Args:
D (pd.DataFrame): The data with measurements with colund id.
stats (pd.DataFrame): Statistics of data D, containing per peptide info.
K (int): The number of folds.
strata (str): String w... | 1829da91b40bd1d64818e65cfdb61475aa6f2427 | 3,604,815 |
def index_types():
"""Returns a list of the supported index types"""
return ["UNIQUE", "CLUSTERED", "NONCLUSTERED"] | e6f8989b23c1800c8aec8aff12555c6ba0fb8c12 | 3,604,816 |
def set_ownertrust(userid, gpghome, trustlevel=5):
""" edit a already imported key and change the trustlevel (default 5=ultimate trust) """
args = ["--homedir", gpghome, "--batch", "--yes", "--import-ownertrust"]
batch_args = userid + ":" + str(trustlevel) + ":\n"
returncode, stdout, stderr = _gpg(args,... | 7213e2a77ca5f471fe0c54f11c986af20d9d7d16 | 3,604,817 |
def fft(lc, bintime):
"""A wrapper for the fft function. Just numpy for now.
Parameters
----------
lc : array-like
bintime : float
Returns
-------
freq : array-like
ft : array-like
the Fourier transform.
"""
nbin = len(lc)
ft = np.fft.fft(lc)
freqs = np.fft... | 6ba9aacad4d617641a2d0e3a1bd034ce37ad7b10 | 3,604,818 |
import torch_xla.core.xla_model as xm
import smdistributed.dataparallel.torch.distributed as dist
import torch
def total_processes_number(local_rank):
"""
Return the number of processes launched in parallel. Works with `torch.distributed` and TPUs.
"""
if is_torch_tpu_available():
return xm.x... | 6595354a73b8d824585778e85b5a14d4f9edfa4e | 3,604,821 |
def _wrap_execution(ctx, fn, args, kwargs):
"""
Intermediate target function that is executed in a new thread;
it receives the original function with arguments and keyword
arguments, including our tracing `Context`. The current context
provider sets the Active context in a thread local storage
v... | f29339aad9db96363e59e925b74710ebadcc4b10 | 3,604,822 |
def create_operator_element(operator):
"""
Creates a PunctuationElement instance containing an operator token of the specified type. The operator
should be a TOML source str.
"""
operator_type_map = {
',': tokens.TYPE_OP_COMMA,
'=': tokens.TYPE_OP_ASSIGNMENT,
'[': tokens.TYPE... | c57ba1ec34c7263cf946968fcc48f1b8250272ea | 3,604,823 |
def Elem_Type \
( elem_type
, bases = None
, front_args = ()
, rest_args = None
, init_arg_defaults = {}
, _autoconvert = {}
, ** attributes
) :
"""Return a new subclass of XML.Element"""
if bases is None :
b... | c36d1591bf7c98d8d9262da4bf07f0988391ca88 | 3,604,824 |
import calendar
def get_casefile_id_sample(year, month, n):
"""
Get random sample of casefile IDs
Parameters
----------
year : int
Sample year
month : int
Sample month
n : int
Number of casefiles to return
Returns
-------
Shuffled list of casefile ID... | 3c30f3bb25377a8bf98d73856e75d2cf69a84115 | 3,604,825 |
def parse(card_info):
"""
Parse an iterable containing the lines of a single card into a dict.
The format of the lines should be:
Name
Mana Cost
Supertype Type -- Subtype
Abilities (one per line)
Set Appearances (comma separated, with rarity)
Any missing fields... | 7a69714d5de025af149288b24121edb4c4405709 | 3,604,827 |
def get_corp_for_id(id):
"""Takes a character's id and returns their corporation name.
Args:
name (str): full character name
Returns:
str: value of their corporation's name
"""
return eveapi['xml'].eve.CharacterAffiliation(ids=id)['rowset']['row']['@corporationName'] | 2f6fb9e5224a4781d234bd82057a28df0eff0db1 | 3,604,828 |
def pnas_conv1x1(in_channels,
out_channels,
stride=1):
"""
1x1 version of the PNASNet specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int o... | bbb23c33dcfead5ab2b5dfed94b1a06d3e7d3e99 | 3,604,829 |
import dateutil
def put_assets_asset_id_owners_team_id(asset_id, team_id, body):
"""Request handler for the API endpoint
``PUT /v1/assets/{asset_id}/owners/{team_id}."""
cli = get_inventory_client()
owns = Owns(team_id, asset_id)
start_time = dateutil.parser.isoparse(body['start_time'])
end_... | 34698080a23664fe1533ab85ab2aa576bc555175 | 3,604,830 |
import pkg_resources
def is_version_greater_equal(version1, version2):
"""Returns True if version1 is greater or equal than version2 else False"""
return (pkg_resources.parse_version(version1) >=
pkg_resources.parse_version(version2)) | 0618f18c22121d954ae156af7bb6eff80236ae29 | 3,604,832 |
def evaluate(model, env, num_steps=1000):
"""
Evaluate a RL agent
:param model: (BaseRLModel object) the RL Agent
:param num_steps: (int) number of timesteps to evaluate it
:return: (float) Mean reward for the last 100 episodes
"""
episode_rewards = [0.0]
obs = env.reset()
for i in ... | 098083fc4248450402495166ae23f04a785c30ce | 3,604,833 |
def vegenere_decrypt(key: int, cipher_text: str) -> str:
"""
Decrypt and print ciphertext encrypted using a shift cipher using key
Input:
key: the word the message m is encrypted with
cipher_text: the ciphertext we are decrypting
"""
decrypted_text = ""
index = 0
for letter ... | 1923f653e1d3cd3900dad38834024deb843fd2ba | 3,604,834 |
from typing import List
import re
def cut_by_words(text: str, seg_size: int, overlap: int,
last_prop: float) -> List[str]:
"""Cut the input text into segments by number of words in each segment.
Cuts the text into equally sized segments, where the segment size is
measured by counts of wo... | 6d6b2dabc56c2d119160faf15be60ea83c026db3 | 3,604,835 |
from typing import List
def get_valid_cameras(cameras: List[Camera], exit_event: ExitEvent, pixels_per_meter: float, capture_radius: float) -> List[Camera]:
"""Gets a list of valid cameras based on an exit event's velocity and the location of the cameras.
:param cameras: The list of cameras that exist.
... | ce85555efc7b6b695cf124713bd72b6b83bc0d1b | 3,604,836 |
def part1(moons):
"""
>>> part1(input_moons())
6849
"""
simulate(moons, 1000)
return sum(moon.energy() for moon in moons) | 7475399ecc35a1d1f09116efe9aa172c9aca9856 | 3,604,837 |
def hilbert_2D(Volume_spectra: cp.ndarray) -> cp.array:
"""
Compute the analytic signal, using the Hilbert transform. \
The transformation is done along the last axis.
Args:
Volume_spectra::cp.ndarray
2nd order tensor containing spectras raw data. Last dimension is depth encoding.
... | 2b5905242a2ef9e015db77aaf9a566a80d03a84e | 3,604,838 |
def create_model(config: ml_collections.ConfigDict,
deterministic: bool) -> nn.Module:
"""Creates a Flax model, as specified by the config."""
if config.model == 'GraphNet':
return models.GraphNet(
latent_size=config.latent_size,
num_mlp_layers=config.num_mlp_layers,
mes... | 30af3b47269f20080a5e0beb047aa983965430d4 | 3,604,839 |
def u(X, _, mu):
"""The 1D-Shekel function."""
x = X[0]
sep = int(mu.shape[0] / 2)
bet = mu[:sep]
gam = mu[sep:]
u_sum = np.zeros_like(x)
for i in range(len(bet)):
i_sum = (x - gam[i])**2
u_sum += 1 / (bet[i] + i_sum)
return u_sum.reshape((1, u_sum.shape[0])) | b5ff9029a035410433f3e504ba5c07e1935d7ce0 | 3,604,840 |
def parse_itypes(item_types_txt):
"""
Reads each item type in ItemTypes.txt and builds a dictionary of ITypeNode
objects keyed by itype code.
"""
itype_nodes = {}
parent_codes = {}
for item_type in item_types_txt:
code = item_type["Code"]
if not code:
continue
... | 31d38b631e3c53d454d7dc084b65d5fbdd21f0ed | 3,604,841 |
import ast
def ReverseComplementMembership(x, y, **kwargs):
"""Change (x doesn't contain y) to not(y in x)."""
return ast.Complement(
ast.Membership(y, x, **kwargs), **kwargs) | d5a5457874f482eaa09f05b2b07ef9e26cbf961b | 3,604,842 |
import json
def _getAllMarkets():
"""
Retrieves all available markets.
bitcoincharts.com offers a JSON of current status (high, low, etc.) for every available market. From this data
we extract only market names.
:return: (list) all available markets
"""
try:
logger.info('getAllMar... | def62eefda8474dbe46b0d8711012ddb849e5e59 | 3,604,843 |
def percent_change(data, axis=-1):
"""Convert data to percent signal change over specified axis.
Parameters
----------
data : numpy array
Input data to convert to percent signal change.
axis : int
Axis of the ``data`` array to compute mean over.
Returns
-------
pch_data... | 6cf146b55a0d774816dcdf37b2f1d41c5c71bb6b | 3,604,845 |
def export(request, type):
"""
Export the RMG database to the old RMG-Java format.
"""
# Build archive filenames from git hash and compression type
sha = subprocess.check_output(['git', 'rev-parse', 'HEAD'],
cwd=rmgweb.settings.DATABASE_PATH)[:7]
base = 'RMG_da... | bb337985b700969c8c210f7a227debcd058b9d48 | 3,604,847 |
def getLastStepVehicleIDs(loopID):
"""getLastStepVehicleIDs(string) -> list(string)
Returns the list of ids of vehicles that were on the named induction loop in the last simulation step.
"""
return _getUniversal(tc.LAST_STEP_VEHICLE_ID_LIST, loopID) | 5672cc2c36a46af7dfd2e8c1fdd214ca7a7c94f7 | 3,604,848 |
import warnings
def p_to_f(*period_derivatives):
"""Convert periods into frequencies, and vice versa.
For now, limited to third derivative. Raises when a
fourth derivative is passed.
Parameters
----------
p, pdot, pddot, ... : floats
period derivatives, starting from zeroth and in
... | defb9cd4bc0fa61368cd00577e92ab49cfaf88d2 | 3,604,849 |
def distance_check(list_of_comparison, time):
"""test function, no longer used"""
list_of_comparison=np.array(list_of_comparison)
condition = list_of_comparison - time < 1
return condition | 0cad6e4ab37df62664f0f440d1a2b41be5e4307e | 3,604,850 |
def get_config(config, group):
"""Return the tuple of song_data, log_data and output_data paths.
Arguments:
config -- ConfigParser object used to extract data values
group -- Top-level grouping of config values (AWS or LOCAL)"""
group = group.upper()
return config[group]['SONG_DATA'], c... | 62af332b29e0a901c14143bd8b77834229ce0013 | 3,604,851 |
def _check_crs(input_crs, return_rasterio=False):
"""Convert CRS to the ``pyproj.CRS`` object passed by ``solaris``."""
if not isinstance(input_crs, pyproj.CRS) and input_crs is not None:
out_crs = pyproj.CRS(input_crs)
else:
out_crs = input_crs
if return_rasterio:
if LooseVersi... | a472d194f68f09025e1f109ea1ed2ea4447df569 | 3,604,853 |
def composite_stage_with_expanding_resource(
mock_stage_archive, mock_expand_resource):
"""Sets up a composite for expanding resources prior to staging."""
composite_stage = StageComposite()
archive = mock_stage_archive()
root_stage = Stage(archive.url)
composite_stage.append(root_stage)
... | 4f8ad599d10e8c90107cf1a2df7c11f3659f81f0 | 3,604,855 |
def singleton(cls):
"""
decorate a class and make it to generate singleton entity
@singleton
class xxx:
"""
instances = {}
def _singleton(*args, **kw):
"""
a closure function for decorator to execute each time
"""
if cls not in instances:
instances... | 7a599472b7d1ba4a6f1b2a13fb600c98144c6ef5 | 3,604,856 |
def target_encoding(cols, target_cols, aggregation='mean', sep='_te_'):
""" Template for creating target encoding FeatureConstructors
:param cols: columns to encode
:param target_cols: columns which values are aggregated
:param aggregation: name of built-in pandas aggregation or @helper-function
:p... | 8f921a788537bb39640073d6644923139760c3d6 | 3,604,857 |
def opt_single_property(pairs, return_removed=False, goal='max',\
scoring_function=num_bps):
"""Return single pseudoknot-free Pairs object with max number of bps
pairs -- Pairs object or list of tuples. One base can only interact
with one other base, otherwise an error will be raised.
return_re... | fa9c17ac99521ce3cefbb28da522b045ba7dbd48 | 3,604,858 |
import re
def sanitize_jinja(arg):
"""
For some string, prevent usage of Jinja-like flags
"""
if isinstance(arg, str):
# If the argument looks like it contains Jinja expressions
# {{ x }} ...
if re.search(r'\{\{[^}]+}}', arg) is not None:
raise ValueError('Inline Ji... | 7c28e987b18e4395d2d80dead85f1ee699515309 | 3,604,859 |
def ancestor(synset1, synset2):
""" Returns the common ancestor of both synsets.
For example synsets("cat")[0].ancestor(synsets("dog")[0]) => Synset("carnivore")
"""
h1, h2 = synset1.hypernyms(recursive=True), synset2.hypernyms(recursive=True)
for s in h1:
if s in h2:
return ... | 4f37b5895c7455e560847f00358b3538b43aff03 | 3,604,860 |
def generate_bbox(cls_map, reg, scale, threshold, stride=2, cell_size=12):
"""
generate bbox from feature cls_map
Parameters:
----------
cls_map: numpy array , n x m
detect score for each position
reg: numpy array , n x m x 4
bbox
scale: float number
... | efcf026a489bc445a3e9f7904d3e328df1efbd63 | 3,604,861 |
def get_sparse_vector(ids, length, values=None):
"""Sparse vector generation.
If "values" is None, the elements are set to 1.
:param ids:
:param length:
:param values:
:return:
"""
n = len(ids)
if values is None:
return ssp.coo_matrix((np.ones(n), (ids, np.zeros(n))), (lengt... | 83a173aaa0b3ca8d9a68acd613dd7bf1da5088c1 | 3,604,863 |
def one_hot_encode(pad_ques_input, pad_ans_input, pad_ans_target, vocab_size):
"""
Pads the input sequences to the max_len
Returns:
-- pad_ques_input: one hot encoded padded tokens of questions to input to encoder
-- pad_ans_input: one hot encoded padded tokens of answers to input to decoder
... | ba4d3b237e124c64c1ea67f227ae15a26ec961f0 | 3,604,864 |
import importlib
import logging
def get_resource_task(resource_path, config=Injected):
# type: (str, Config) -> Callable[[str, Dict, Dict], Union[List[AppModel], AppModel, ResourceResult]]
"""Search and return a bounded method for given path.
:param resource_path: resource path
:type resource_path: s... | 855865cb6c02d2a2b7859eebcfbd82abda3e962b | 3,604,865 |
def make_id_number(
date_of_birth: date, gender: Gender, citizenship: Citizenship
) -> str:
"""Construct a valid RSA ID number from the given information.
Args:
date_of_birth: The date of birth.
gender: The gender indicator.
citizenship: The citizenship indicator.
Returns:
... | 420a05fe4cbf4469bfa44541ffd00bd263a0beed | 3,604,867 |
def parse_escape(s, fg=None, bg=None, style=None):
"""Parses an escape sequence.
Not sure if this is very accurate.
"""
if style is None:
style = []
if not s:
return (None, None)
parts = _iter_escape(s)
for p in parts:
if p == 38:
fg = _parse_colors(par... | dd37430de86dbc811cde57df3d4d7f3efa6dc909 | 3,604,868 |
def add_biodata_args(parser):
"""Add standard arguments for preparing biological data to a command line arg parser.
"""
parser.add_argument("--genomes", help="Genomes to download",
action="append", default=[],
choices=SUPPORTED_GENOMES)
parser.add_argument... | 5d2eb97878ee19b6d7efe9ad301f0298f98d8b2c | 3,604,869 |
def Iq(q,
scale=1.0,
gamma=3.0,
q_0=0.1):
"""
:param q: Input q-value
:param scale: Scale factor
:param gamma: Exponent
:param q_0: Correlation peak position
:return: Calculated intensity
"""
with errstate(... | b9f65d9fb3f47d8f67158b194493bc9cddde6c6b | 3,604,870 |
import asyncio
def run_coro(coro):
"""Runs a co-routing in the default event loop and retuns it result."""
return asyncio.get_event_loop().run_until_complete(coro) | 62f109ef4440ecb2807640ff91b27f07e91d8f9f | 3,604,871 |
from datetime import datetime
def _init_campaign(
context,
csv_output,
xlsx_output,
only_activated=True,
confirmation_tokens=False,
skip_agendas=False,
stdout=None,
):
"""Initialises campaign based on manifest data.
Parameters:
- context:dict[str]->any dictionary containing ma... | fe9681e3d4b3b7a0906e2ff495b80ce56e25f652 | 3,604,872 |
def get_help(command_name):
"""Get help output of command."""
return mirtk.check_output([command_name, '-h']).splitlines() | aa92bb5890382e8b44fad1acba55bfaeb6736c34 | 3,604,873 |
import copy
def count(df):
"""
A function to count numbers for each prediction cases
:param df: A dataframe of raw prediction result
:return:
- df_count
Column: Ground Truth
Row: Predicted label
TP: df_count[ground truth label, ground truth ... | 64c1f42748acde3ed6b251025b3f7f88a23b0e08 | 3,604,875 |
import numpy
def charge_exchange(ods, nc=10):
"""
Adds some FAKE CER channel locations so that the overlay plot will work in tests. It's fine to test
with dummy data as long as you know it's not real. This function can overwrite existing data if you're not careful.
The original is modified, so deepcop... | 1e0f169ffa12263715fffdd6476da37300340c66 | 3,604,876 |
def _format_creators(value: list) -> dict:
""" Creators require special formatting.
$a Personal name (ex: Griesinger, Peggy)
$b Numeration (ex. III) (used for royalty or people who are Jrs. or Srs.)
$c Titles and other words associated with a name (ex. King of England)
$d Dates assoc... | 43f372d5075ee2186e57737b717b3432ace1a0d3 | 3,604,878 |
def create_pk(overview, absorption, distribution, elimination, special_populations, ddi_studies):
"""create pk on pk class"""
pk = Pharmacokinetics(overview=overview,
absorption=absorption,
distribution=distribution,
elimination=elimina... | 26937f554e58a4bf0d6622aa17bee0557d271e6b | 3,604,879 |
def buildaff(ulx: float, uly: float, pixelres: float) -> tuple:
"""
Build a gdal GeoTransform tuple
Args:
ulx: projected geo-spatial upper-left x reference coord
uly: projected geo-spatial upper-left y reference coord
pixelres: pixel resolution
Returns:
affine tuple
... | 43e593050a6b3ebef876f4347d3df787e2a49795 | 3,604,880 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.