content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def parse_tpl_file(tpl_file):
""" parse a pest template file to get the parameter names
Parameters
----------
tpl_file : str
template file name
Returns
-------
par_names : list
list of parameter names
"""
par_names = []
with open(tpl_file,'r') as f:
try... | 0797cfedbef07dcd118e13440691c287f952a740 | 48,400 |
def find_factors(n):
"""
Finds a list of factors of a number
"""
factList = {1, n}
for i in range(2, int(n ** 0.5) + 1):
if (n % i == 0):
factList.add(i)
factList.add(n // i)
return sorted(factList) | 0b8992bfe81bfd49c738b49380ceb0c8e7155b3f | 48,401 |
def unique(a):
""" Return the list with duplicate elements removed.
Args:
a (list): A list.
Returns (list):
The list with duplicate elements removed.
"""
# NOTES:
# 1. Built-in function 'set()' can convert a list (ordered) into a set (unordered).
# 2. B... | 1aeac608e53ebc91cb0709b69fc8731f0ad39562 | 48,402 |
from typing import Tuple
def sim_seird_decay(
s: float, e:float, i: float, r: float, d: float, beta: float, gamma: float, alpha: float, n_days: int,
decay1:float, decay2:float, decay3: float, decay4: float, step1_delta: int, fatal: float
) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarra... | 4217488020bfcf28020fc31aee898655a6cf191e | 48,403 |
def do_quote_form(expressions, env):
"""Evaluate a quote form.
"""
check_form(expressions, 1, 1)
# BEGIN Question 6B
return expressions.first
# END Question 6B | 989df694053dfeeb774a9062aea3a27cb0ddcc38 | 48,404 |
def make_flatmap_image(braindata, height=1024, recache=False, **kwargs):
"""Generate flatmap image from volumetric brain data
This
Parameters
----------
braindata : one of: {cortex.Volume, cortex.Vertex, cortex.Dataview)
Object containing containing data to be plotted, subject (surface id... | fc36acb5701e6b9346fe676b18cb109dad314d88 | 48,405 |
from typing import List
def compute_i_k_index(citations: List[int], k: int = 10):
"""Given a list of citations (integers) compute the i-k-index (default i10)."""
citations = np.asarray(citations)
i_k_index = (citations > k).sum()
return i_k_index | 16ba1e7be56d10d2e5ff9e20d97df86ee482a899 | 48,406 |
from datetime import datetime
def get_session_details_helper(client):
"""
Retrieve details regarding the current session within `client`
:param client: ICAT client containing an authenticated user
:type client: :class:`icat.client.Client`
:return: Details of the user's session, ready to be conver... | 2c1d714f6e131f7639a44a41ed6e0d45cb54b5b3 | 48,407 |
def resnet18(use_rp=False, width=1, **kwargs):
"""Constructs a ResNet-18 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
if use_rp:
print('model using random projection')
model = ResNetRP(width, bb.BasicBlockRP, [2, 2, 2, 2], **kwargs)
els... | cd51bc95741b3e5ea78145af71091658c8c8e25f | 48,408 |
def assign_seller(request, campaign_id):
"""
Shows a list of sellers to assign contacts to.
"""
campaign = Campaign.objects.get(pk=campaign_id)
campaign.count = ContactCampaignStatus.objects.filter(campaign=campaign, seller=None).count()
message = ""
if request.POST:
seller_list = [... | 1945384df939306fc5379ae2b071446116b85997 | 48,409 |
def _swissroll_dataset():
"""Interwined spirals."""
sz = 100
Y = np.arange(sz) % 2
t = np.linspace(0, 4 * np.pi, sz)
X = t[:, None] * np.vstack([np.cos(t + Y * np.pi),
np.sin(t + Y * np.pi)]).T
X += 0.2 * np.random.randn(*X.shape)
return X, Y | 388969317aff95be12fed6545f7f6eb8102bbce7 | 48,410 |
def load_mat_data(dataset_str):
""" dataset_str: protein, metabolic, conflict, powergrid """
dataset_path = 'data/' + dataset_str + '.mat'
mat = loadmat(dataset_path)
if dataset_str == 'powergrid':
adj = sp.lil_matrix(mat['G'], dtype=np.float32)
feats = None
return adj, feats
... | 73cfc51aeeb9fdc08cd9a727402791c1bfc5e970 | 48,411 |
def filter_row_by_data_type(col_name, data_type=None, get_type=False):
"""
A Pandas UDF function that returns bool if the value match with the data_type param passed to the function.
Also can return the data type
:param col_name: Column to be process
:param data_type: The data_type to be compared wi... | 552e930bd3b56c71efd89be051f4faf7f783adac | 48,412 |
def get_ajax_job_status_msg(jobid):
"""return the job status msg (as a string)"""
# user's browser requesting job status msg
global STAT_CODE_RUNNING
if not validate_jobid(jobid):
return Response("Invalid Job ID: %s" % jobid, mimetype='text/plain', headers = {'X-Dalton-Webapp':'OK'})
stat_co... | 69d6eaa5753a69b714b03d93299ab3423d607921 | 48,413 |
import shelve
def run(args, config, prog_args):
"""Run an experiment."""
name = args.name
repo = pygit2.Repository('.')
with shelve.open('.em', writeback=True) as emdb:
exp_info = emdb.get(name)
if exp_info:
if exp_info['status'] == 'running':
return _die(E... | 259a27861b149daff3948f27883f672c64bb3ff3 | 48,414 |
from datetime import datetime
def EarliestActiveTimestamp():
"""Calculates the earliest timestamp of an active channel.
Returns:
A DateTime representing the earliest possible timestamp of an active
channel.
"""
return datetime.now() - timedelta(hours=CHANNEL_LIFETIME_HOURS) | 848eb41ebac30778ec3fac7bc3afd71b65d931b4 | 48,415 |
def get_avg_male_ellipse(exp):
"""Gets the average major and minor axis lengths of the ellipse
fitted to the male for all males across all groups in an experiment.
Parameters
----------
exp : FixedCourtshipTrackingExperiment
Experiment to get average ellipses from.
Returns
-------
... | c65bdd7883cea9007b233a46fa75d15c95fcedb9 | 48,416 |
def on_request(f, name=None):
"""
An interceptor which updates the context value of `REQUEST` during the
enter stage.
:param f: Callable to update the request.
:param unicode name: Interceptor name.
:rtype: Interceptor
"""
return middleware(f, None, name=name) | 9dfe6bd77693d63ff60a9edc82700ae26a86a14d | 48,417 |
import tokenize
def build_model():
"""Build the model
Returns
-------
sklearn.pipeline.Pipeline
The model
"""
pipeline = Pipeline([
(const.FEATURES, FeatureUnion([
(const.TEXT_PIPELINE, Pipeline([
(const.VECT, CountVectorizer(tokenizer=tokenize)),
... | 305642beb9250d12e3f1019b461eeb151e253fbb | 48,418 |
import copy
def extend_and_specialize(items, loader):
# type: (List[Dict[Text, Any]], Loader) -> List[Dict[Text, Any]]
"""Apply 'extend' and 'specialize' to fully materialize derived record
types."""
items = deepcopy_strip(items)
types = {t["name"]: t for t in items} # type: Dict[Text, Any]
... | 0480c3dd1dd8dfef4c460e592717f9d5c9eede72 | 48,419 |
import json
def curl(url, tokens=None, headers=None, request_type="GET", data=None, parse=False,
validate=False, soft_validation=False):
"""
:rtype type
"""
_headers = {}
handler_chain = []
post_req = ["POST", "PUT"]
get_req = ["GET", "DELETE"]
print_url = Options.CURL_PRINT_ONLY is not None... | 9ef6d5d2e18acb9d4037ce0faed0ddc185f56a67 | 48,420 |
def reorder_atoms(mol):
"""change index of the atoms to ensure atoms are ordered by ascending residue number
"""
order = [(i.GetPDBResidueInfo().GetName().strip(), i.GetPDBResidueInfo().GetResidueNumber()) for i in mol.GetAtoms()] # currently the atom name is not used in sorting
order = [i[0] for i in s... | dc87436974482b1c815ff43b2c3030a31ad49e95 | 48,421 |
def from_dict(
d,
mapping=None,
type_map=None,
ignore_fields=None,
infer_date=False,
convert_hyphens=False,
schema=None,
table=None,
partitions=None,
s3_key=None,
case_map=False,
case_insensitive=False,
ignore_malformed_json=True,
ignore_nested_arrarys=True,
n... | 76d8c4cca52ed23d858e91a82804f81fc96709c8 | 48,422 |
from typing import Callable
import functools
def stop_on_shutdown_event(f: Callable[[Agent, Event], None]):
"""
Decorator which can be used to wrap the handle_event method.
If a system_shutdown event is received, stop running without calling handle_event.
"""
@functools.wraps(f)
def wrapper(... | a948098e80c56ff69badce5cc754abaab9ff6fda | 48,423 |
def generate_full_uri(request=None, suffix=None):
"""
生成绝对链接
:param request:
:param suffix:
:return:
"""
url = suffix or ''
if request:
request_host = request.get_host()
host, *sub_path = request_host.split("/", 1)
base_uri = '{scheme}://{host}'.format(scheme=requ... | bf48fa0ef933f8194baefb20408cb7be16131f92 | 48,424 |
def bins_to_str(lbin):
"""
Return a list of unicode characters into a message
:lbin:list(bin), a list of characters
"""
sbin = ''.join(lbin)
lbin8 = wrap(sbin, 8)
message = chr(int(lbin8[0],2))
for c in lbin8[1:]:
message+=chr(int(c,2))
return message | 47bbd7d7881e5d9ad3e0369216653719048b8156 | 48,425 |
def _log_commit_progress(table_size, no_chunks):
"""Shim to avoid sgr spamming output with commit progress for small images"""
return table_size > 500000 or no_chunks > 100 | 82394d325bb755045ca7057ebbe53520024edeab | 48,426 |
def loss_function(outputs, targets, num_labels): # TODO: Add typing
"""
Loss function used to re-train the BERT model.
Using binary cross entropy logistic loss function as it's better suited for multi-label learning
"""
return nn.BCEWithLogitsLoss()(outputs, targets.view(
-1, num_labels)) | a8def379e1869dff7c6a53c2d5c8ad19748576d9 | 48,427 |
import binascii
def display_string_dump(elf_file, section_spec):
""" Display a strings dump of a section. section_spec is either a
section number or a name.
"""
section = _section_from_spec(elf_file, section_spec)
if section is None:
print("Section '%s' does not exist in the file!" % s... | 1d3d1d864d99a0acfc69db387dbadab81f83e111 | 48,428 |
import pandas
def get_backend() -> Optional[str]:
"""
Returns the current pandas plotting backend,
or ``None`` if pandas is not available.
Typically the result will be ``"matplotlib"``.
:return: str or None
"""
try:
except ImportError: # pragma: no cover
return None
ret... | cd4a2adecd42b45faf95dd7963958e4f16b06eeb | 48,429 |
import argparse
import shutil
import os
import subprocess
def cmd_convert(args: argparse.Namespace) -> int:
"""Convert all raw samples to the specified output format."""
try:
files = find_files(args.path, '.raw')
except Exception as e:
print(f'Error - {e}.')
return 1
if not fi... | 6ddc7c5507c9a1b89090cc07a45cb34c6aefba79 | 48,430 |
def PolygonACD(array, value):
"""
used by libcvcaller.py
inputs:
array
value
outputs:
array?
"""
try:
return libcv.PolygonACD(array, value)
except:
print "libcv failed in PolygonACD"
return [] | be6f41703f51ad24ee7215a66ea7285db2c5ed82 | 48,431 |
import logging
def back_rm(img, edge_lim=20, dim=3):
""" Background extraction in TIFF series
For confocal Z-stacks only!
dem = 2 for one frame, 3 for z-stack
"""
if dim == 3:
mean_back = np.mean(img[:,:edge_lim,:edge_lim])
logging.debug('Mean background, {} px region: {:.3f}'.... | 4c62fc1fa03f4bcfac96ec4f5d88b53cc0323eb4 | 48,432 |
def root(request):
"""
Tutorial > Root
"""
return HttpResponsePermanentRedirect(reverse('explore.views.tutorials')) | df5fcb264220c76e90a2f1e570162095c1c974fb | 48,433 |
import logging
def extract_spectral_data_from_df(df):
"""
takes a dataframe where each columns is a spectral sensor. Expands each columns into a dataframe and returns a
dictionary of dataframes
:param df: dataframe of binary format spectral data
:return: dictionary of dataframes of expanded spectr... | deef70f237aaea683ee0d25eadf982c0bb984c5e | 48,434 |
def gsfLoadScaleFactor(
p_sf, subrecord_id: c_int, c_flag: c_char, precision: c_double, offset: c_int
) -> int:
"""
:param p_sf: POINTER(gsfpy3_09.gsfRecords.c_gsfScaleFactors)
:param subrecord_id: c_int
:param c_flag: c_char
:param precision: c_double
:param offset: c_int
:return: 0 if ... | ce01379ee1b83bb2f5362cfd189908f53e49a17e | 48,435 |
def get_ip(request, real_ip_only=False, right_most_proxy=False):
"""
Returns client's best-matched ip-address, or None
@deprecated - Do not edit
"""
best_matched_ip = None
for key in defs.IPWARE_META_PRECEDENCE_ORDER:
value = request.META.get(key, request.META.get(key.replace('_', '-'), ... | 744c8693d4882b3e0431fb640efef87b27042bd5 | 48,436 |
import re
def parse_textfile(input_text):
"""This funtion converts text into a list of available emission maps, a dict of emission data and a dict of
metadata. The expected input is:
input_text: str
"""
list_available_maps = ''
dict_data = {}
dict_meta = {}
start_data_row = -1
end... | 1a6a6b308effb2e44a7b019284f4c65f8c18a4f3 | 48,437 |
import torch
def auto_annotate(img_paths):
"""
Auto annotates a list of images using DETR.
Args:
"""
detr = torch.hub.load('facebookresearch/detr', 'detr_resnet50', pretrained=True)
detr.eval()
annotations = []
for img_path in img_paths:
res = predict(detr, img_path)
... | 092adb3e8ff4c0aca4a313c85865cada4481ad2a | 48,438 |
def get_sample_info(fin):
"""
Read in information from phenotype file
Create a dictionary to store each column
"""
f = open(fin,'r')
f = f.read().split('\n')
f = map(lambda x: x.rstrip(), f)
if '' in f:
f.remove('')
header = f[0].split('\t') # list
c = f[1:]
# Check... | 707dab056b36ffe4a77bf64d6a78081a59bc5a8b | 48,439 |
def parseVarMap(text):
"""Parse a string of the form [ namelist, slicelist ]"""
n = 0
m = _ListStart.match(text)
if m is None:
raise CDMSError("Parsing cdms_filemap near " + text[0:_NPRINT])
result = []
n += m.end()
s, nconsume = parselist(text[n:], parseName)
result.append(s)
... | fe8e1ae02d748b0ac992727755368b3764a12e47 | 48,440 |
import typing
def pins_to_sessions(
tsm: SMContext,
pins: typing.List[str],
sites: typing.List[int] = [],
fill_pin_site_info=True,
):
"""
get the sessions for the selected pins
Args:
tsm (SMContext): tsm context for nidcpower
pins (typing.List[str]): desired pins for which... | 500ac4ca729194e7d60ffaa703c527dfc8ca1c01 | 48,441 |
def get_V_hs_min(V_vent_g_i):
"""(39)
Args:
V_vent_g_i: 暖冷房区画iの全般換気量(m3/h)
Returns:
熱源機の最低風量(m3/h)
"""
return np.sum(V_vent_g_i[:5], axis=0) | 36dfc56b74d69de3b3c6dbf55383b2579dc00eeb | 48,442 |
import subprocess
def rearm_windows():
"""Rearm Windows License"""
rearm_cmd = r'cscript c:\Windows\System32\slmgr.vbs -rearm //nologo'
return subprocess.check_call(rearm_cmd) == 0 | d7c468005f2504b0210568efc588919cdb6e1568 | 48,443 |
def _warn(warn_message, *args, **kwargs):
"""
Inputs: warn_message- the warning message
Used to override "warnings.formatwarning" to output only the warning
message.
"""
return f'{warn_message}\n\n' | cf88c86af6492142c6f3d364f8cdf1f5cb39da1d | 48,444 |
def rotate_half(x):
"""Helper that splits a tensor at last dim into half and rotate it."""
x1, x2 = jnp.split(x, 2, axis=-1)
x = jnp.concatenate([-x2, x1], axis=-1)
return x | 58478e8875dba60a6aba7da42c4c3cf8f401a3f7 | 48,445 |
def Mag(*argv):
"""Return the magnitude of one or more vectors
This method computes the vector magnitude of the Numpy arrays in
*args*. Each array in *args* must have the same number of dimensions.
The arrays may be a mixture of staggered and unstaggered arrays. I.e.
for any axis the dimension le... | cdb5b1f492c5456f7bb02fe39d509ad3f881c74c | 48,446 |
from sys import version
import torch
def stateful_linear(types, args, kwargs, pg):
"""Handles ``__torch_function__`` dispatch for ``torch.nn.functional.linear``.
This method computes a linear.
"""
input_tensor = args[0]
weight = args[1]
if version.parse(torch.__version__) > version.parse("1.1... | 97cd0d1cf027adb5cb017b8d60c680711bf39d94 | 48,447 |
def sort_map(map):
"""
resume = {}
sort = []
for i in range(len(map)):
for j in range(len(map[i])):
resume[(i, j)] = map[i][j]
srtd = [k for k in sorted(resume.values())]
for e in srtd:
sort.append(list(list(resume.keys())[list(resume.values()).index(e)]))
sr... | fdb60775f264437a7fed632ce7261029544a3be3 | 48,448 |
def encode2str(key=JWT_SECRET_KEY, algorithm="HS256", headers=None, json_encoder=None, **kwargs) -> str:
"""
生成json web token
:param key: 签名密钥
:param headers: token头信息
:param json_encoder:
:param kwargs:
:return:
"""
return encode(key=key, algorithm=algorithm, headers=headers, json_... | ad76064b78cdc9e2952ccc25ac44e94bc65b5564 | 48,449 |
def parallel_preprocess(
input_data, preprocess_pipeline, word_tokenize=None, num_pool=-1
):
"""
Process data in parallel using multiple CPUs.
Args:
input_data (list): List if input strings to process.
preprocess_pipeline (list): List of functions to apply on the input data.
word... | 97ad5dfc5d9ecb304d16bc21fd16214550679284 | 48,450 |
def get_selection_value(source_obj, field, value):
"""Get the string of a selection field using
fields_get method to get the string
@param source_obj: Model that contains the field
@type source_obj: RecordSet
@param field: Database name of the field
@type field: str or unicode
@param value:... | 952966e150900ddcf0afd838bf357b0b3054d047 | 48,451 |
from sys import path
async def imageToByte(image, session):
"""Attempts to auto-detect between URL link, bytes and local file path, and converts image to bytes.
Args:
image (string): Must be either bytes, URL link or local file path of image.
Raises:
ConvertImageError: Provided string is... | 7a23d42b97bfadc483e6a26148a2aab20d256e5c | 48,452 |
import scipy
import time
def visualize6(M, name, nozero=False, k=2., useall=False, lim=1e-2, conc='c_w_l',W=46,color='crimson'):
""" visualize variation in the the profile shape"""
if useall:
val, c_w_l, idx = conditionVal2(name=name, nozero=nozero, conc=conc)
else:
val, c_w_l, idx = cond... | 0507e5c8c4f8632ac42f11bc468da6e61a8ee51a | 48,453 |
def max_key(dict):
""" Returns the maximum key in an integer-keyed dictionary.
Args:
dict (dict): The integer-keyed dictionary.
Returns:
int: The maximum key.
"""
output = 0
for key, value in dict.items():
output = max(output, int(key))
return output | 059a26fa690aaca2df2b0a7e251c206aa5e7276b | 48,454 |
def terminal_path_lengths(neurite):
"""Get the path lengths to each terminal point."""
return _map_sections(sf.section_path_length, neurite, Section.ileaf) | c34bb84d15d320aab7d836d5a83f2f46e39f57e1 | 48,455 |
def seperator(digits):
"""Seperate thousands into list container. e.g ['1', '000'] for 1000."""
strdigits = str(digits)
sep = []
while len(strdigits) > 3:
sep.insert(0, strdigits[-3: len(strdigits)])
strdigits = strdigits[0:-3]
# if strdigits not empty at the end of loop
if strdi... | 5a75e73521900a5a600d4bac8496811b9a3a371d | 48,456 |
def generate_analysis_list(analysis_ids, public_only=False):
"""Get general analysis information
Parameters
----------
analysis_ids : list of ints
The analysis ids to look for. Non-existing ids will be ignored
public_only : bool, optional
If true, return only public analyses. Defaul... | 51ceaa1db2e13d77b8aac838782e58307a11f07d | 48,457 |
def normalization(epochs):
""" Normalizes each epoch e s.t mean(e) = 0 and var(e) = 1
Args:
epochs - Numpy structure of epochs
Returns:
epochs_n - mne data structure of normalized epochs (mean=0, var=1)
"""
for i in range(epochs.shape[0]): # TODO could switch to a 1... | c8ca3fc6c1f23696a585befdf76c6e9044a47fb9 | 48,458 |
import pickle
import torch
def all_gather_list(data, group=None, max_size=16384):
"""Gathers arbitrary data from all nodes into a list.
Similar to :func:`~torch.distributed.all_gather` but for arbitrary Python
data. Note that *data* must be picklable.
Args:
data (Any): data from the local work... | 6dc6db3a4fb484609cf2ccb2e30cf41397b5de23 | 48,459 |
def build_get_method_query_valid_request(
**kwargs # type: Any
):
# type: (...) -> HttpRequest
"""Get method with unencoded query parameter with value 'value1&q2=value2&q3=value3'.
See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request builder
into your code flow.
... | 20a9d193fcde98bf0ca96b4530c8e8490b897651 | 48,460 |
def build_adj_neighborhoods(L, K, symmetric=True):
"""Build Adjacent Neighborhoods with periodic boundary conditions"""
V = []
M = (K-1)/2
for i in range(L):
if symmetric:
start = np.floor(i-M)
else:
start = i
Vi = [int(((start + j) % L)+1) for j in range(... | 0889f44a0ba04f486166d9a2c7cd813ec8a390ad | 48,461 |
import copy
from sys import version_info
def namelambda(name):
"""Rename a function. Decorator.
This can be used to give a lambda a meaningful name, which is especially
useful for debugging in cases where a lambda is returned as a closure,
and the actual call into it occurs much later (so that if the... | 96c1b841812f1bc79990a7af1b345de6e9e3ddbb | 48,462 |
import argparse
def get_arguments():
"""
parses the command line arguments.
:return:
"""
parser = argparse.ArgumentParser(
description='Analyse the estimator_status and ekf2_innovation message data for the '
'.ulg files in the specified directory')
parser.add_argume... | 678d1069f5d290a4f45cb0c1df42608c2d8764ab | 48,463 |
def maximum_iou(evt_gt, evt_pr, input_events, **kwargs):
"""Implements Maximum Intersection over Union from
Startsev, M., Agtzidis, I., & Dorr, M. (2019). 1D CNN with BLSTM for automated
classification of fixations, saccades, and smooth pursuits.
Behavior research methods, 51(2), 556-572.
"""
ev... | 8474a4d9bcefc6756c0ce09a87e2ba1a6cf8977d | 48,464 |
def _tpos_to_gpos(transcript, start, end=None):
"""Compute the equivalent gene position for a transcript position.
Args:
transcript: `pyensembl.Transcript` instance
start (int): position relative to the transcript
end (int): optional, second position relative to the transcript
... | e5e4d3e6a00e19e317e77fb5065ba5a77dc33579 | 48,465 |
from typing import Tuple
from typing import List
def parse_func(x: str) -> Tuple[str, List[str]]:
"""
Parses out the components of a function string.
:returns: First element is the name of the function, second argument are the function arguments.
"""
try:
name = x.split("(")[0]
arg... | 36830c95cb5238f6e7bea4f5693f28e651f0c0fb | 48,466 |
def volume_get_all(context, marker=None, limit=None, sort_keys=None,
sort_dirs=None, filters=None, offset=None):
"""Retrieves all volumes.
If no sort parameters are specified then the returned volumes are sorted
first by the 'created_at' key and then by the 'id' key in descending
ord... | fb53703e2c899bc18ed82871211cd13ce78aee60 | 48,467 |
import re
import subprocess
def parse(text: Text, morphind_loc="lib/morphind/MorphInd.pl"):
"""
Do morphological parsing with Morphind. for example:
menggunakan => ^meN+guna<n>+kan_VSA$
:param text:
:param morphind_loc:
:return:
"""
cleaned_text = re.sub("[^a-zA-Z0-9 ]", "", text)
... | 955df2b490c9f98b54868305fb77991f95f2a7ab | 48,468 |
from typing import Tuple
import re
def get_views(string : str) -> Tuple[int, int]:
"""A helper function that takes a string reresentation of total something and
daily amount of that same thing and returns both as a tuple of ints.
Parameters
------------
string : str
The string containing ... | 898d4faa89be8dcb40aede5d62fa1e4e03fb550c | 48,469 |
def set_input(interpreter, size, resize):
"""Copies a resized and properly zero-padded image to the input tensor.
Args:
interpreter: Interpreter object.
size: original image size as (width, height) tuple.
resize: a function that takes a (width, height) tuple, and returns an RGB
image resized to t... | be6b56549f1db8dce0ed81465b8e64d4e4387f02 | 48,470 |
import requests
from bs4 import BeautifulSoup
def crawl_naver_datalab():
"""
datalab.naver.com/robots.txt
(21/11/05)
User-Agent: *
Allow: /$
Allow: /index.naver
Disallow: /
"""
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, l... | 9824d3b15ab5139dbdf23c16fc40969d569224b6 | 48,471 |
def all_datasets():
"""
Return all data sets from the data set table.
:return: a list of dictionaries {name: (string), description: (string), id: (int) }
"""
#print('all_datasets: current_user:', current_user)
return db.session.query(Dataset).all() | 04365adc5250b8357dd1952d7e822292088a52ee | 48,472 |
import numpy
def min_dist(coord, surface):
"""Return minimum distance between coord and surface."""
d = surface - coord
d2 = numpy.sum(d * d, 1)
return numpy.sqrt(min(d2)) | 970da8ac11e8a3a1e087874a8ea3b0137fda5827 | 48,473 |
def get_keys_by_mode(mode):
"""Filtres `KEYS` by mode."""
return (key for key in KEYS if mode in key.modes) | 521d18aa1cf478628362ca596a923262f2c18b57 | 48,474 |
def bytes2np(bytesarray):
"""
bytes two numpy->array
:param bytesarray:
:return:
"""
nparr = np.frombuffer(bytesarray, np.uint8)
img_np = cv2.imdecode(nparr, cv2.IMREAD_COLOR) # cv2.IMREAD_COLOR in OpenCV 3.1
return img_np | b5dac7a661bc776fccd962817edb7b9eee843081 | 48,475 |
def cohort_membership(cohort_id):
"""
If full_detail flag is set to 'true', it returns a json with
a list of wikiusers grouped by username.
Otherwise, it renders the html with basic cohort information.
"""
session = db.get_session()
try:
cohort = g.cohort_service.get_for_display(
... | c5c5d9b4a1508e75156b8bb10bbf8668fc879505 | 48,476 |
def quote_identifier(dialect: Dialect, name: str) -> str:
"""
Add quotes around an identifier (e.g. a table or column name), and escape special characters in the name.
Note that the result of this function is not always a valid column name and/or table name. e.g. The
following string can be quoted by t... | c9a5791944c60cf6fe71451753331314830e5114 | 48,477 |
import ast
def mesh_update_attributes(mesh):
"""Update the attributes of a mesh.
Parameters
----------
mesh : :class:`compas.datastructures.Mesh`
A mesh object.
Returns
-------
bool
True if the update was successful.
False otherwise.
"""
names = sorted(me... | 08f36da20d74d3177c8cce6ef5d22e0e63f03d92 | 48,478 |
def load_data(database_filepath):
"""
Loading Data From Database.
Splitting X And Y Columns As TimeSeries Data By Calling get_rolling_data Method.
Parameters:
database_filepath (str): Filepath Where Database Is Located.
Returns:
X (DataFrame): Features
Y (DataFrame): Labe... | 74e9aadc9d3726572a72c6a96dcbbf30159f9fd1 | 48,479 |
import time
import torch
def test_exception_early_stop_asap():
"""Even the first partitions have finished to process, the partition before
the failed partition should be killed as soon as possible.
"""
class ExpectedException(Exception):
pass
class Pass(nn.Module):
def forward(sel... | 0f5326f427d582215ecb6d1a48a53891b8854087 | 48,480 |
def recover_path(shortest_path: tuple, path_to: dict, action_to: dict, time_to: dict) -> list:
"""Recover and return the path from start to goal."""
path = [time_to[shortest_path], shortest_path, action_to[shortest_path]]
previous = path_to[shortest_path]
while previous:
path.append(previous)
... | aa1a9431a30f35c48d3c54bad3d5b828bc853459 | 48,481 |
import time
def wait_timeout(proc):
"""
This function waits for a process to finish, else raises exception after timeout
"""
start = time.time()
end = start + float(sys_experiment_timeout)
interval = min(float(sys_experiment_timeout) / 1000.0, .25)
while True:
result = proc.poll()
... | 6bfba442550cec13db0f43e61c91c15ce5ba0c76 | 48,482 |
def polaritySanitizer(polarity):
"""Sanitize input polarity values.
Renames the, case-insensitive, values 'positive', 'pos', or '+' to 'positive'
and 'negative', 'neg', or '-' to 'negative'.
Errors on unrecognized polarity value.
Arguments:
polarity (str): unsanitized polarity type
""... | e328345ea48a9441f9ab323fd6a3ff5ca06f07d5 | 48,483 |
import os
def downloaded_datasets():
"""Lists downloaded datasets in ~/.agml/datasets"""
return [d for d in os.listdir(
data_save_path()) if os.path.isdir(
os.path.join(data_save_path(), d))] | 63c606c1925f845fb1e9e840f87036b53bc11560 | 48,484 |
from typing import List
import socket
def get_certificate_chain(host: str, port: int) -> List[str]:
"""Connect to the host on the port and obtain certificate chain"""
func_name: str = "get_certificate_chain"
cert_chain: list = []
soc = socket(AF_INET, SOCK_STREAM, proto=0)
soc.settimeout(3)
... | 34248e5bf1bcb30815d42d2769e44b53d3b3a3f8 | 48,485 |
def evaluation_step(loss_from_logits_fn, model,
per_device_batch: dt.BatchedTrainTocopoData,
rng: jnp.ndarray):
"""An evaluation step, running on each device.
Note the use of `pmean` to combine gradients and loss across devices (and
hosts).
Args:
loss_from_logits_fn... | cf0b05a70c864bf3c0e59077e1271f806dfea7fd | 48,486 |
def read_pkg_ini(path):
"""Read and check the `flit.ini` file with data about the package.
"""
cp = _read_pkg_ini(path)
return _validate_config(cp, path) | 2f2a9cff18dd74797972f0163bf46d35aa838148 | 48,487 |
def verifyCallback(connection, x509, errnum, errdepth, ok):
"""
Check SSL certificates.
@return (bool) True when the certificates are valid, else False.
"""
if not ok:
print 'invalid cert from subject:', x509.get_subject()
return False
else:
#Certs are fine
p... | 8aff15199e8d728219cad4e2d22957f0b9f1ef50 | 48,488 |
from typing import Optional
from datetime import datetime
import pytz
def get_data_granularity(
user: Optional[BlossomUser], after: Optional[datetime], before: Optional[datetime]
) -> str:
"""Determine granularity of the graph.
It should be as detailed as possible, but only require 1 API call in the best... | 4ea113cf6231fc8cd15dc41f0590be5a4207db5e | 48,489 |
import urllib
import mimetypes
def build_file_response(path, content_type=None):
"""
path (str) : Path to file relative to www-root folder next to your server script
content_type (str) : Mimetype; if set to None mimetype will automatically be determined
----
Return (bytes) HTTP response containing... | e3f45c079c42581d46a85374c61ed83ec77ad053 | 48,490 |
def NewSimulationRunAddDatastoreInit(builder, datastoreInit):
"""This method is deprecated. Please switch to AddDatastoreInit."""
return AddDatastoreInit(builder, datastoreInit) | cc6d53f586f6624323ca1a6613f0d31cfef5a0b5 | 48,491 |
def build_condensed_graph(G, min_epsilon, min_cluster_size, dont_merge=[]):
"""
Finds nodes in the graph that have edges weight weights above min_epsilon,
and both children have a size larger than min_cluster_size.
"""
def filter_node(n):
return G.nodes[n]['size'] > min_cluster_size
de... | 9c90e014e742102ff1f2d9c45c948afdb9d5fbae | 48,492 |
import types
from typing import Dict
import collections
def morph(doclike: types.DocLike) -> Dict[str, Dict[str, int]]:
"""
Count the number of times each value for a morphological feature appears
as a token annotation in ``doclike``.
Args:
doclike
Returns:
Mapping of morphologic... | db0426c78fe86916cb6aa821452d0862aeb3de2e | 48,493 |
import torch
import time
def validate(val_loader, model, criterion, verbose, args):
"""
验证
"""
batch_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
# top5 = AverageMeter()
recall = AverageMeter()
aver_acc = AverageMeter()
aver_loss = AverageMeter()
ave... | 77e7c1ec1171a27ea255a449f0bccb4e61eff63b | 48,494 |
def _tx_executor(contract_function):
""" modifies the contract instance interface function such that whenever a transaction is performed
it automatically waits until the transaction in included in the blockchain
(unless wait=False is specified, in the case the default the api acts as usual)
"""
... | b4844e1c754cbaade30ae879884e0a9699d154b7 | 48,495 |
def add_dtv(dtv):
"""
Given values for a date time value, generate the RDF necessary to add the
datetime value to VIVO
date_time datetime value
datetime_precision text string in tag format of VIVO date time precision,
example 'vivo:yearMonthDayPrecision'
"""
... | 8e0d3bb47b32b534a1478b038484f5ff0d5bc40a | 48,496 |
import math
def L2Norm(inputList):
"""
Return the norm of the supplied list
"""
return math.sqrt(SumSquare(inputList)) | fda95b956f819e057601cb5c1ec8a4bfb8863554 | 48,497 |
import json
def parse_json_file_to_dict(path):
"""
Convert JSON file into a project-specific representation of the data
internally.
NOTE: it's not the most Pythonic or elegant code you will find. It was
written "just to work".
"""
with open(path, 'r') as json_file:
json_contents =... | 16870e556dac0c469aec3aa67d8984a86d2c5430 | 48,498 |
def hash_table_size(item, tablesize):
"""
A hashing technique that involves
1. Converting the characters in a string to a list of ordinal values
2. Get the sum of the list
3. Get the remained by doing a modulo using tablesize
item - string
tablesize
"""
ordinal_list = [ord(i)... | cf47a023c35693681485331878dfd3eb9164a7bf | 48,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.