content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_input_fn_common(pattern, batch_size, mode, hparams: SmartComposeArg):
""" Returns the common input function used in Smart Compose training and evaluation"""
return _get_input_fn_common(pattern, batch_size, mode,
**_get_func_param_from_hparams(_get_input_fn_common, hparams... | 414a2281807f5ccba5534f4000a4837409dc0f1f | 3,651,500 |
def text_to_int(sentence, map_dict, max_length=20, is_target=False):
"""
对文本句子进行数字编码
@param sentence: 一个完整的句子,str类型
@param map_dict: 单词到数字的映射,dict
@param max_length: 句子的最大长度
@param is_target: 是否为目标语句。在这里要区分目标句子与源句子,因为对于目标句子(即翻译后的句子)我们需要在句子最后增加<EOS>
"""
# 用<PAD>填充整个序列
text_to_idx = ... | 9ac1928ff0a71e653c999a173ee4ea9127b29913 | 3,651,501 |
from datetime import datetime
def map_to_udm_users(users_df: DataFrame) -> DataFrame:
"""
Maps a DataFrame containing Canvas users into the Ed-Fi LMS Unified Data
Model (UDM) format.
Parameters
----------
users_df: DataFrame
Pandas DataFrame containing all Canvas users
Returns
... | 96cd04c425d3a4747a29d0297a8d97451fc18a6e | 3,651,502 |
def custom_shibboleth_institution_login(
selenium, config, user_handle, user_pwd, user_name
):
"""Custom Login on Shibboleth institution page."""
wait = WebDriverWait(selenium, config.MAX_WAIT_TIME)
input_user_id = wait.until(
EC.element_to_be_clickable((By.XPATH, "//input[@id='userid']"))
)... | c830180b6fad4d454a0ffae76d42015adca5b909 | 3,651,503 |
from numpy import array
def beamcenter_mask():
"""Returns beamcenter mask as an array. Given the PSF and the dimensions of
the beamstop, the minimum intensity around beamcenter occurs at a radius of
3 pixels, hence a 7x7 mask."""
return array([[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
... | 6efb592aa88c3da57010ab4a70144d645ae916ea | 3,651,504 |
def physical_conversion_actionAngle(quantity,pop=False):
"""Decorator to convert to physical coordinates for the actionAngle methods:
quantity= call, actionsFreqs, or actionsFreqsAngles (or EccZmaxRperiRap for actionAngleStaeckel)"""
def wrapper(method):
@wraps(method)
def wrapped(*args,**k... | 36501fc563a1de71320b205ef1795ea369cc578a | 3,651,505 |
import functools
import click
def pass_api_client(function):
"""Create API client form API key and pass it to subcommand.
:param function: Subcommand that returns a result from the API.
:type function: callable
:returns: Wrapped function that prints subcommand results
:rtype: callable
"""
... | af806b8420cfb50b00ed313c5ae35ac847059af4 | 3,651,506 |
import torch
def vecs_Xg_ig(x):
""" Vi = vec(dg/dxi * inv(g)), where g = exp(x)
(== [Ad(exp(x))] * vecs_ig_Xg(x))
"""
t = x.view(-1, 3).norm(p=2, dim=1).view(-1, 1, 1)
X = mat(x)
S = X.bmm(X)
#B = x.view(-1,3,1).bmm(x.view(-1,1,3)) # B = x*x'
I = torch.eye(3).to(X)
#V = sinc1... | dcd7276fbb1aa59128f7c321b36e561e3f90f3f2 | 3,651,507 |
def wide_factorial(x):
"""factorial returns x! = x * x-1 * x-2 * ...,
Args:
x: bytes to evaluate as an integer
Returns:
bytes representing the integer that is the result of the factorial applied on the argument passed
"""
return If(
BitLen(x) == Int(1), x, BytesMul(x, wide... | c6a7b01ec5f140c6bcfad45ae78879c210dd1f33 | 3,651,508 |
import pathlib
def spring_outpath(filepath: pathlib.Path) -> pathlib.Path:
"""Build a spring path based on a fastq file path"""
LOG.info("Create spring path from %s", filepath)
file_name = filepath.name
file_parent = filepath.parent
splitted = file_name.split("_")
spring_base = pathlib.Path("... | dfe9d7d0fb592c8bdbf8f2074e9316e8e1e7fc31 | 3,651,509 |
def expanded_bb( final_points):
"""computation of coordinates and distance"""
left, right = final_points
left_x, left_y = left
right_x, right_y = right
base_center_x = (left_x+right_x)/2
base_center_y = (left_y+right_y)/2
dist_base = abs(complex(left_x, left_y)-complex(right_x, right_y ) )
... | c033130b0d43ccf9cea3e075305cf464f958c62f | 3,651,511 |
def gen_file_get_url(token, filename):
"""
Generate httpserver file url.
Format: http://<domain:port>/files/<token>/<filename>
"""
return '%s/files/%s/%s' % (get_httpserver_root(), token, urlquote(filename)) | 5e8f3367d5872457edc5a8808c3aabb57a8a2748 | 3,651,512 |
def count_items():
"""
Get number of items in the DB
Per the AWS documentation:
DynamoDB updates this value approximately every six hours. Recent changes might not be reflected in this value.
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb.html#DynamoDB.Client.de... | ac580e172ef2571a4a154af4460cdc1598832ab7 | 3,651,513 |
def extract_uris(data):
"""Convert a text/uri-list to a python list of (still escaped) URIs"""
lines = data.split('\r\n')
out = []
for l in lines:
if l == chr(0):
continue # (gmc adds a '\0' line)
if l and l[0] != '#':
out.append(l)
return out | 9f6ce28ecf94e07e03afca9852dd9952ed2a2488 | 3,651,514 |
def createConnection(ps, graph, e, q, maxIter):
"""
Try to build a path along a transition from a given configuration
"""
for i in range(maxIter):
q_rand = shootConfig(ps.robot, q, i)
res, q1, err = graph.generateTargetConfig(e, q, q_rand)
if not res:
continue
... | 62d9c3a3bb5e90cfba5df86d9dbbab5cd3f7a8ea | 3,651,515 |
import re
def extract_info(filepath,pdbid,info_id_list):
"""Returns a dictionary where the key is pocket ID (starting at zero) and the value is a dictionary of information points."""
pockets_info = {}
pocket_file = open(filepath+pdbid+'_out/'+pdbid+'_info.txt')
pocket_lines = pocket_file.readlines()
... | aca4074bc1c48add487268641a66c6e80aa7dafb | 3,651,517 |
def eval_shape_fcn(w, x, N1, N2, yte):
"""
compute class and shape function
:param w:
:param x:
:param N1:
:param N2:
:param yte: trailing edge y coordinate
:return:
"""
C = x**N1 * (1-x)**N2
n = len(w) - 1 # degree of Bernstein polynomials
S = np.zeros_like(x)
for... | c1047f6a586f51b4fd82423429b087ca28d87510 | 3,651,518 |
def _pickle_path(file_name):
"""Returns an absolute path to the specified pickle file."""
return project_root_path('pickles', file_name) | 18aef638bf3b06eb33b638e7c2038cf07cbd0d7d | 3,651,519 |
def streamentry(parser, token):
"""
streamentry <entry_var>
"""
bits = token.split_contents()
bits.reverse()
tag_name = bits.pop()
try:
entry_var = bits.pop()
except IndexError:
raise template.TemplateSyntaxError, "%r is missing entry argument" % tag_name
... | 88e6abc56f817f0d4a0c814a672bf0173342347d | 3,651,520 |
def mult_int_list_int():
"""
>>> mult_int_list_int()
[1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2]
"""
return 3 * [1, 2] * 2 | cd34fa521ae3985f7770f96a1a8985e9473ee2b3 | 3,651,521 |
def _gcd_tf(a, b, dtype=tf.int64):
"""Calculates the greatest common denominator of 2 numbers.
Assumes that a and b are tf.Tensor of shape () and performs the extended
euclidean algorithm to find the gcd and the coefficients of Bézout's
identity (https://en.wikipedia.org/wiki/B%C3%A9zout%27s_identity)
Args:... | e012ceb40fe778c23687a118ed139f1ba4ea4527 | 3,651,522 |
def compute_running_mean(x, kernel_size):
""" Fast analogue of scipy.signal.convolve2d with gaussian filter. """
k = kernel_size // 2
padded_x = np.pad(x, (k, k), mode='symmetric')
cumsum = np.cumsum(padded_x, axis=1)
cumsum = np.cumsum(cumsum, axis=0)
return _compute_running_mean_jit(x, kernel_... | 8d687c246b584dc43ce80cdfeb585c0f503be37f | 3,651,523 |
def _historicDataUrll(symbol, sDate=(1990,1,1),eDate=date.today().timetuple()[0:3]):
"""
generate url
symbol: Yahoo finanance symbol
sDate: start date (y,m,d)
eDate: end date (y,m,d)
"""
urlStr = 'http://ichart.finance.yahoo.com/table.csv?s={0}&a={1}&b={2}&c={3}&d={4}&e={5}&f={6}'.\
f... | 433c345ae9a55cd628f4232a4dd80507f675b30e | 3,651,524 |
def to_dict(eds, properties=True, lnk=True):
"""
Encode the EDS as a dictionary suitable for JSON serialization.
"""
nodes = {}
for node in eds.nodes:
nd = {
'label': node.predicate,
'edges': node.edges
}
if lnk and node.lnk is not None:
nd... | c1a777a0a81ad2e3b9197b3df5e0d35a5174d61f | 3,651,525 |
def find_lineage(tax_id: int) -> Lineage:
"""Finds lineage for a single tax id"""
if tax_id % 50000 == 0:
_LOGGER.info("working on tax_id: %d", tax_id)
lineage = []
while True:
record = TAXONOMY_DICT[tax_id]
lineage.append((record["tax_id"], record["rank"], record["rank_name"]))... | 75aeb2a0e222f44e72ba315134278ec9e73de706 | 3,651,526 |
from datetime import datetime
import pytz
import json
import traceback
def modify(request):
"""
[メソッド概要]
グループのDB更新処理
"""
logger.logic_log('LOSI00001', 'None', request=request)
msg = ''
error_msg = {}
now = datetime.datetime.now(pytz.timezone('UTC'))
try:
with transactio... | d596f0e239d2017f61a9747e2a5ed9731ff9308d | 3,651,527 |
import inspect
def _function_args_doc(functions):
"""
Create documentation of a list of functions.
Return: usage dict (usage[funcname] = list of arguments, incl.
default values), doc dict (doc[funcname] = docstring (or None)).
Called by function_UI.
"""
usage = {}
doc = {}
for f in... | 848fb1c7629d8e4feb848293cd965da6edc2ff4a | 3,651,528 |
def mock_modules_list():
"""Standard module list without any issues"""
return [
{"name": "foo", "module_type": "app", "supported_platforms": ["macos"]},
{"name": "bar", "module_type": "app"},
] | c4f20e95e87950a414b0ac156e6a07ac79dcdf19 | 3,651,529 |
def cal_iou(box1, box1_area, boxes2, boxes2_area):
"""
box1 [x1,y1,x2,y2]
boxes2 [Msample,x1,y1,x2,y2]
"""
x1 = np.maximum(box1[0], boxes2[:, 0])
x2 = np.minimum(box1[2], boxes2[:, 2])
y1 = np.maximum(box1[1], boxes2[:, 1])
y2 = np.minimum(box1[3], boxes2[:, 3])
intersection = np.ma... | e27d942730cfe043034ec3f063934d94907314cf | 3,651,530 |
def hbonds_single_c(snap, id1, id2, cut1, cut2, angle, names=False):
"""
Binding of C++ routines in :mod:`.hbonds_c` for couting of hydrogen bonds in a single snapshot.
Args:
snap (:class:`.Snap`): single snapshot containing the atomic information
id1 (str): identifier for oxygen atoms (e.g... | f4d7c73b631225505f8140e67da950979159e6c6 | 3,651,531 |
def _find_event_times(raw, event_id, mask):
"""Given the event_id and mask, find the event times.
"""
stim_ch = find_stim_channel(raw)
sfreq = raw.info['sfreq']
events = find_events(raw, stim_ch, mask, event_id)
times = [(event[0] - raw.first_samp) / sfreq for event in events]
return times | 1ade6a18567767db64ed57880b2b0837feade5d4 | 3,651,532 |
def get_parameters():
"""Load parameter values from AWS Systems Manager (SSM) Parameter Store"""
parameters = {
"kafka_servers": ssm_client.get_parameter(
Name="/kafka_spark_demo/kafka_servers")["Parameter"]["Value"],
"kafka_demo_bucket": ssm_client.get_parameter(
Name="... | 0dbd8c505c5bf404d612bc83fb119f1291f5cbad | 3,651,533 |
async def get_accounts(context, names, observer=None):
"""Find and return lite accounts by `names`.
Observer: will include `followed` context.
"""
assert isinstance(names, list), 'names must be a list'
assert names, 'names cannot be blank'
assert len(names) < 100, 'too many accounts requested'
... | 9e088f691cb92cf495b238d20902b276943b6044 | 3,651,534 |
def softmax_crossentropy_logits(p, q):
"""see sparse cross entropy"""
return -(p * log_softmax(q)).sum(-1) | aa50eb4c7de8060a1ce9f9e7c879970db6d9b505 | 3,651,535 |
def SieveOfEratosthenes(limit=10**6):
"""Returns all primes not greater than limit."""
isPrime = [True]*(limit+1)
isPrime[0] = isPrime[1] = False
primes = []
for i in range(2, limit+1):
if not isPrime[i]:continue
primes += [i]
for j in range(i*i, limit+1, i):
isPr... | 6d1e12d289c9bfcdfadf64f764deba077a09ffd1 | 3,651,536 |
def generate_chromosome(constraint = False, constraint_levers = [], constraint_values = [],
threshold = False, threshold_names = [], thresholds = []):
"""
Initialises a chromosome and returns its corresponding lever values, and temperature and cost.
**Args**:
- constraint (*b... | 02fe7b4f34064410f635b68f2764fb50451e7cf0 | 3,651,538 |
def make_link_request(data: dict, user_token: str):
"""
https://yandex.ru/dev/disk/api/reference/response-objects-docpage/#link
- it will not raise in case of error HTTP code.
- see `api/request.py` documentation for more.
:param data: Data of link to handle.
:param user_token: User OAuth toke... | 4c3c183b7c8bd713594ee42623f5db0a43e98ffd | 3,651,539 |
import warnings
def load_sample_bathymetry(**kwargs):
"""
(Deprecated) Load a table of ship observations of bathymetry off Baja
California as a pandas.DataFrame.
.. warning:: Deprecated since v0.6.0. This function has been replaced with
``load_sample_data(name="bathymetry")`` and will be remov... | 085e2795f9f59a4222bdca5a97e8d1818aa11d75 | 3,651,540 |
async def ticket_channel_embed(
_: hikari.InteractionCreateEvent, bot: hikari.GatewayBot
) -> hikari.Embed:
"""Provides an embed for individual ticket channels."""
description = (
"Thanks for submitting a ticket! We take all tickets "
"very seriously. Please provide a full explanation in thi... | 1c45535c8a7b606ac80a8a2fefd7e78079ed25f6 | 3,651,542 |
from typing import List
def count_branching_factor(strips_ops: List[STRIPSOperator],
segments: List[Segment]) -> int:
"""Returns the total branching factor for all states in the segments."""
total_branching_factor = 0
for segment in segments:
atoms = segment.init_atoms
... | 155b7258f320a95ca56736331686470bc8c5a5f7 | 3,651,543 |
import torch
def iou_overlaps(b1, b2):
"""
Arguments:
b1: dts, [n, >=4] (x1, y1, x2, y2, ...)
b1: gts, [n, >=4] (x1, y1, x2, y2, ...)
Returns:
intersection-over-union pair-wise, generalized iou.
"""
area1 = (b1[:, 2] - b1[:, 0] + 1) * (b1[:,... | ba9b445223fea5ea8332a189b297c8c40205a4e5 | 3,651,544 |
def aggregate(data):
"""Aggregate the data."""
return NotImplemented | 2d7fd424d70858e6065dca34991308f0ed6c945c | 3,651,545 |
def get_valid_columns(solution):
"""Get a list of column indices for which the column has more than one class.
This is necessary when computing BAC or AUC which involves true positive and
true negative in the denominator. When some class is missing, these scores
don't make sense (or you have to add an e... | b5aeb01f3362dc8ab1ed22cd86ad7d6995e36a3e | 3,651,546 |
def fourier_transform(data, proc_parameters):
"""Perform Fourier Transform down dim dimension given in proc_parameters
.. Note::
Assumes dt = t[1] - t[0]
Args:
data (nddata): Data container
proc_parameters (dict, procParam): Processing parameters
Returns:
nddata: Fouri... | e3a9aafdb2661d112f1e02885477711c2c6d3d22 | 3,651,547 |
import copy
def iupac_fasta_converter(header, sequence):
"""
Given a sequence (header and sequence itself) containing iupac characters,
return a dictionary with all possible sequences converted to ATCG.
"""
iupac_dict = {"R": "AG", "Y": "CT", "S": "GC", "W": "AT", "K": "GT",
"M":... | 95a713e87564c4d8e807e1d476439568a562731b | 3,651,548 |
def integer_list_to_named_tuple(list_of_integers):
"""
Converts a list of integers read from the ultrak498 into a named tuple
based upon the type. The type is determiend by the first integer in the
list. Since all tuples contain five fields, the list of integers must
have a length of five.
Re... | 50aed101577c263f213c3487dc56d9d0886c6530 | 3,651,549 |
def get_final_shape(data_array, out_dims, direction_to_names):
"""
Determine the final shape that data_array must be reshaped to in order to
have one axis for each of the out_dims (for instance, combining all
axes collected by the '*' direction).
"""
final_shape = []
for direction in out_dim... | f1407936f9e1e7bebe55461abe4999a4fdf9636d | 3,651,551 |
import pytz
def create_assignment_payload(subsection_block):
"""
Create a Canvas assignment dict matching a subsection block on edX
Args:
subsection_block (openedx.core.djangoapps.content.block_structure.block_structure.BlockData):
The block data for the graded assignment/exam (in the... | 5c8327d0731aaae16769429833d80b87bf39fb9d | 3,651,552 |
def return_random_initial_muscle_lengths_and_activations(InitialTension,X_o,**kwargs):
"""
This function returns initial muscle lengths and muscle activations for a given pretensioning level, as derived from (***insert file_name here for scratchwork***) for the system that starts from rest. (Ex. pendulum_eqns.refe... | afaa5905e3ae978217ac7f7e2b677af62bb33dd9 | 3,651,553 |
def add_top_features(df, vocab, n=10):
"""
INPUT: PySpark DataFrame, List, Int
RETURN: PySpark DataFrame
Take in DataFrame with TFIDF vectors, list of vocabulary words,
and number of features to extract. Map top features from TFIDF
vectors to vocabulary terms. Return new DataFrame with terms
... | 741bcbb2fea0894f5218871e3f72360bf6f2caab | 3,651,554 |
from typing import Union
from typing import Tuple
from typing import List
def java_solvability(level: MarioLevel, time_per_episode=20, verbose=False, return_trajectories=False) -> Union[bool, Tuple[bool, List[Tuple[float, float]]]]:
"""Returns a boolean indicating if this level is solvable.
Args:
lev... | 8f4b282a8ae0b217ca12828cb20724e943de35b2 | 3,651,555 |
def get_trait_value(traitspec, value_name, default=None):
""" Return the attribute `value_name` from traitspec if it is defined.
If not will return the value of `default`.
Parameters
----------
traitspec: TraitedSpec
value_name: str
Name of the `traitspect` attribute.
default: any
... | 5bc4d23b326b59e0a542a5b3113f8906e9a88c49 | 3,651,556 |
import collections
def check_if_blank(cell_image: Image) -> bool:
"""Check if image is blank
Sample the color of the black and white content - if it is white enough
assume no text and skip. Function takes a small more centered section to
OCR to avoid edge lines.
:param cell_image: Image to OCR
... | 6cb3be0da1d15e1ba4fb2ccc7199709058792d5c | 3,651,557 |
def get_tpr_from_threshold(scores,labels, threshold_list):
"""Calculate the recall score list from the threshold score list.
Args:
score_target: list of (score,label)
threshold_list: list, the threshold list
Returns:
recall_list: list, the element is recall score calculated by the
... | 97796fb0f1ba9d41cf6e9c4bb21d1ca8f94499e3 | 3,651,558 |
def updating_node_validation_error(address=False, port=False, id=False,
weight=False):
"""
Verified 2015-06-16:
- when trying to update a CLB node's address/port/id, which are
immutable.
- when trying to update a CLB node's weight to be < 1 or > 100
At leas... | 68c5fdda121950c679afe446bfd7fb19331deb40 | 3,651,559 |
def gaussianDerivative(x):
"""This function returns the gaussian derivative of x
(Note: Not Real Derivative)
"""
return -2.0*x*(np.sqrt(-np.log(x))) | 6b8312b399f627708007e80e5c72cedde4e944fc | 3,651,560 |
def parse_numbers(numbers):
"""Return list of numbers."""
return [int(number) for number in numbers] | ee79d4e15cbfb269f7307710d9ad4735687f7128 | 3,651,561 |
import json
def add_server():
"""
Adds a server to database if not exists
"""
data = json.loads(request.data)
ip_addr = IPModel.get_or_create(address=data["ip_addr"])[0]
ServerModel.create(ip=ip_addr, port=data["port"])
return 'OK' | 31ed6860fb311e00e9ee266a121cb44c256723a6 | 3,651,562 |
def get_continuum_extrapolation( # pylint: disable=C0103
df: pd.DataFrame,
n_poly_max: int = 4,
delta_x: float = 1.25e-13,
include_statistics: bool = True,
odd_poly: bool = False,
) -> pd.DataFrame:
"""Takes a data frame read in by read tables and runs a continuum extrapolation
for the spec... | 7c4ce775b064142647259cf25c8f323c08fc99d0 | 3,651,565 |
def listvalues(d):
"""Return `d` value list"""
return list(itervalues(d)) | 2c0bcbc112e10afac3d6d958c6a494bdd19dea6c | 3,651,566 |
def _non_blank_line_count(string):
"""
Parameters
----------
string : str or unicode
String (potentially multi-line) to search in.
Returns
-------
int
Number of non-blank lines in string.
"""
non_blank_counter = 0
for line in string.splitlines():
if li... | dfa6f43af95c898b1f4763573e8bf32ddf659520 | 3,651,567 |
def load(map_name, batch_size):
"""Load CaraEnvironment
Args:
map_name (str): name of the map. Currently available maps are:
'Town01, Town02', 'Town03', 'Town04', 'Town05', 'Town06', 'Town07',
and 'Town10HD'
batch_size (int): the number of vehicles in the simulation.
... | 4433ad4fc4985a9ceaabd8e7ce3d8d3b0d419c80 | 3,651,568 |
def decrypt_password(encrypted_password: str) -> str:
""" b64 decoding
:param encrypted_password: encrypted password with b64
:return: password in plain text
"""
return b64decode(encrypted_password).decode("UTF-8") | e501a3da671f28f6f751ed289da961f30377d248 | 3,651,569 |
def walk(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None):
"""Returns the Walk task."""
# physics = Physics.from_xml_string(*get_model_and_assets())
physics = SuperballContactSimulation("tt_ntrt_on_ground.xml")
task = PlanarSuperball(move_speed=_WALK_SPEED, random=random)
environment_kwar... | 2b4de77661a7f0dd235c2f1d258e627ff110f3c3 | 3,651,571 |
def encode_direct(list_a: list):
"""Problem 13: Run-length encoding of a list (direct solution).
Parameters
----------
list_a : list
The input list
Returns
-------
list of list
An length-encoded list
Raises
------
TypeError
If the given argument is not ... | 9a20ffd2051003d5350f7e059d98c35310bc9bbe | 3,651,573 |
def handler500(request):
"""
HTTP Error 500 Internal Server Error
"""
return HttpResponse('<h1>HTTP Error 500 Internal server error</h1>', {}) | 92dc4cb815d34425e9c4f49ab878f6c57838d7b8 | 3,651,574 |
def increase_line_complexity(linestring, n_points):
"""
linestring (shapely.geometry.linestring.LineString):
n_points (int): target number of points
"""
# or to get the distances closest to the desired one:
# n = round(line.length / desired_distance_delta)
distances = np.linspace(0, linestr... | 9747a6277a6333b6f1e92e479e0f286a01c8ae4e | 3,651,575 |
def get_topic_prevelance(doc_topic_matrix, num_topics, total_num_docs):
"""Input: doc_topic_matrix, a numpy nd array where each row represents a doc, and each collumn is the assocication
of the doc with a topic. Num_topics and integer holding the number of topics. Total_num_docs is an int holding the
number of docs... | 752214cba87b8d1766ceba139b029197c4f51df2 | 3,651,576 |
async def drones_byDroneId_delete(request, droneId):
"""
Remove a drone from the fleet
It is handler for DELETE /drones/<droneId>
"""
return handlers.drones_byDroneId_deleteHandler(request, droneId) | 28900c7df711fde5833b50683a738fe5567202ff | 3,651,577 |
import six
def generate_sql_integration_data(sql_test_backends):
"""Populate test data for SQL backends for integration testing."""
sql_schema_info = get_sqlalchemy_schema_info()
vertex_values, edge_values, uuid_to_class_name = get_integration_data()
# Represent all edges as foreign keys
uuid_to_... | 1f8fe9550b069a942a900d547874c787d27576c3 | 3,651,578 |
def software_detail(request, context, task_id, vm_id):
""" render the detail of the user page: vm-stats, softwares, and runs """
softwares = model.get_software(task_id, vm_id)
runs = model.get_vm_runs_by_task(task_id, vm_id)
datasets = model.get_datasets_by_task(task_id)
# Construct a dictionary th... | 2e740426bc4f86d1b3d5dd2ddbaa4bdd5f6ae772 | 3,651,581 |
def compile_error_curves(dfs, window_size = 60):
"""
takes a list of timeseries dfs and
returns a DataFrame in which each column is
the monatonically decreasing version of % error
for one of the dfs in the list.
usefull for summarizing how a bunch of timeseries converge on
some value after ... | 602ec4563e2aa368db42b762db7f91c3f868fb73 | 3,651,582 |
def _get_cluster_medoids(idx_interval: np.ndarray, labels: np.ndarray,
pdist: np.ndarray, order_map: np.ndarray) \
-> np.ndarray:
"""
Get the indexes of the cluster medoids.
Parameters
----------
idx_interval : np.ndarray
Embedding indexes.
labels : np.n... | 88739d625b5a58d41d9103824f5c733d6e2fcbf9 | 3,651,583 |
import webbrowser
def perform_authorization_code_flow():
"""
Performs spotify's Authorization Code Flow to retrive an API token.
This uses the OAuth 2.0 protocol, which requires user input and consent.
Output
______
api_key: str
a user's api key with prompted permissions
... | 6939a4414be28f40d712cc1d54f994b02ce9a688 | 3,651,584 |
def calculate_empirical_cdf(variable_values):
"""Calculate numerical cumulative distribution function.
Output tuple can be used to plot empirical cdf of input variable.
Parameters
----------
variable_values : numpy array
Values of a given variable.
Returns
-------
numpy array... | 4c55f7b230318f212088a7218bac9929a9df01e5 | 3,651,585 |
def import_reference(filename):
"""
Imports object from reference node filename
:param filename: str
"""
return maya.cmds.file(filename, importReference=True) | 07747a3ceea95f222b81e7e3b938b758f30937b0 | 3,651,586 |
def remove_persons_with_few_joints(all_keypoints, min_total_joints=10, min_leg_joints=2, include_head=False):
"""Remove bad skeletons before sending to the tracker"""
good_keypoints = []
for keypoints in all_keypoints:
# include head point or not
total_keypoints = keypoints[5:, 1:] if not i... | 773e9317df75f5d4de12c574a3c599e2729bd427 | 3,651,588 |
def message_has_races(message):
"""
Checks to see if a message has a race kwarg.
"""
races = get_races_from_message(message)
return len(races) > 0 and races[0] != "" | e2f01498f8783d2c311e1e6e06f1e9cac3fe36a6 | 3,651,589 |
import re
def _find_word(input):
"""
_find_word - function to find words in the input sentence
Inputs:
- input : string
Input sentence
Outputs:
- outputs : list
List of words
"""
# lower case
input = input.lower()
# split by whitespace
input = re.split(pattern = '[\s]+', string = input)
# find w... | c2e4aa6b5c127bf03593a9aa2c1ae035e83f5a64 | 3,651,590 |
def logp1_r_squared_linreg(y_true, y_pred):
"""Compute custom logp1 r squared ((follows the scipy linear regression implementation of R2).
Parameters
----------
y_true
y_true.
y_pred
y_pred.
Returns
-------
r2
"""
y_pred, _ = tf.split(y_pred, num_or_size_splits=... | ea33ff1f16e9dcfd8ea4bdc27ca8388bd5086b1d | 3,651,591 |
from typing import Union
import json
def to_legacy_data_type(data_type: Union[JsonDict, dt.DataType]) -> JsonDict:
"""
Convert to simple datatypes ("String", "Long", etc) instead of JSON objects,
if possible.
The frontend expects the "type" field for enums and arrays to be lowercase.
"""
if n... | 913c5e523ee74d86c3a64b98b291fb213513ae84 | 3,651,592 |
def display_dictionary(dictionary, renormalize=False, reshaping=None,
groupings=None, label_inds=False, highlighting=None,
plot_title=""):
"""
Plot each of the dictionary elements side by side
Parameters
----------
dictionary : ndarray(float32, size=(s, n) OR (s,... | 58e363f7f14ec9bc8b88613777ff446ae63feb85 | 3,651,593 |
def rbinary_search(arr, target, left=0, right=None):
"""Recursive implementation of binary search.
:param arr: input list
:param target: search item
:param left: left most item in the search sub-array
:param right: right most item in the search sub-array
:return: index of item if found `-1` oth... | 23da6b29c122efe77c0dc592d2bfc42f324b1799 | 3,651,594 |
def get_redis_posts(author: str) -> (str, str):
"""Return user's first and other post IDs
Retrieve the user's first and other post IDs from Redis,
then return them as a tuple in the form (first, extra)
:param author: The username to get posts for
:return: Tuple of the first and other post IDs
... | 3653a1bdbc3cde8614098a705ae7f11de850165f | 3,651,595 |
from datetime import datetime
def template_localtime(value, use_tz=None):
"""
Checks if value is a datetime and converts it to local time if necessary.
If use_tz is provided and is not None, that will force the value to
be converted (or not), overriding the value of settings.USE_TZ.
This functio... | 7042696ae5291248ee2a2d56dcc5e943ccec92d8 | 3,651,596 |
def FilesBrowse(button_text='Browse', target=(ThisRow, -1), file_types=(("ALL Files", "*.*"),), disabled=False,
initial_folder=None, tooltip=None, size=(None, None), auto_size_button=None, button_color=None,
change_submits=False, enable_events=False,
font=None, pad=None, ... | d712e5e41afa1d09482971864ce1b9af66332394 | 3,651,597 |
def f2p(phrase, max_word_size=15, cutoff=3):
"""Convert a Finglish phrase to the most probable Persian phrase.
"""
results = f2p_list(phrase, max_word_size, cutoff)
return ' '.join(i[0][0] for i in results) | 51a6f518481097bbba49685f32fb87ed65cc19ec | 3,651,599 |
def read_sj_out_tab(filename):
"""Read an SJ.out.tab file as produced by the RNA-STAR aligner into a
pandas Dataframe.
Parameters
----------
filename : str of filename or file handle
Filename of the SJ.out.tab file you want to read in
Returns
-------
sj : pandas.DataFrame
... | bc96813e1e69c8017f7ad0e5c945d4bf8c17e645 | 3,651,600 |
def gc_subseq(seq, k=2000):
"""
Returns GC content of non − overlapping sub− sequences of size k.
The result is a list.
"""
res = []
for i in range(0, len(seq)-k+1, k):
subseq = seq[i:i+k]
gc = calculate_gc(subseq)
res.append(gc)
return gc | 9c2208f9dad291689ef97556e8aaa69213be6470 | 3,651,601 |
def pcursor():
"""Database cursor."""
dbconn = get_dbconn("portfolio")
return dbconn.cursor() | 50a19e3837a3846f10c44bcbb61933786d5bf84b | 3,651,603 |
import math
def truncate(f, n):
"""
Floors float to n-digits after comma.
"""
return math.floor(f * 10 ** n) / 10 ** n | ae7e935a7424a15c02f7cebfb7de6ca9b4c715c0 | 3,651,605 |
import math
def rotY(theta):
""" returns Rotation matrix such that R*v -> v', v' is rotated about y axis through theta_d.
theta is in radians.
rotY = Ry'
"""
st = math.sin(theta)
ct = math.cos(theta)
return np.matrix([[ ct, 0., st ],
[ 0., 1., 0. ],
... | 1ed327485f9861eb8cf045a60f0a7352de1b4b25 | 3,651,607 |
def get_core_blockdata(core_index, spltcore_index, core_bases):
"""
Get Core Offset and Length
:param core_index: Index of the Core
:param splitcore_index: Index of last core before split
:param core_bases: Array with base offset and offset after split
:return: Array with core offset and core le... | 85efb96fa45ecfa3f526374c677e57c70e3dc617 | 3,651,608 |
def make_bench_verify_token(alg):
""" Return function which will generate token for particular algorithm """
privk = priv_keys[alg].get('default', priv_key)
token = jwt.generate_jwt(payload, privk, alg, timedelta(days=1))
def f(_):
""" Verify token """
pubk = pub_keys[alg].get('default',... | 4e7da537ab7027711d338d6d3155c198c371391b | 3,651,609 |
def status():
""" Status of the API """
return jsonify({'status': 'OK'}) | 579c265c88ac8e2c3b5d19000564e90f106be3f5 | 3,651,610 |
def calc_median(input_list):
"""sort the list and return median"""
new_list = sorted(input_list)
len_list = len(new_list)
if len_list%2 == 0:
return (new_list[len_list/2-1] + new_list[len_list/2] ) / 2
else:
return new_list[len_list/2] | 28c0331d1f2dab56d50d63fa59d4dda79a177057 | 3,651,611 |
def _load_eigenvalue(h5_result, log):
"""Loads a RealEigenvalue"""
class_name = _cast(h5_result.get('class_name'))
table_name = '???'
title = ''
nmodes = _cast(h5_result.get('nmodes'))
if class_name == 'RealEigenvalues':
obj = RealEigenvalues(title, table_name, nmodes=nmodes)
elif cl... | f27d65d84481e1bb91a0d2282945da0944de1190 | 3,651,612 |
def _GenerateBaseResourcesAllowList(base_module_rtxt_path,
base_allowlist_rtxt_path):
"""Generate a allowlist of base master resource ids.
Args:
base_module_rtxt_path: Path to base module R.txt file.
base_allowlist_rtxt_path: Path to base allowlist R.txt file.
Returns:... | b6b3ef988b343115e4e1b2950667f07fd3771b19 | 3,651,613 |
def finite_min_max(array_like):
""" Obtain finite (non-NaN, non-Inf) minimum and maximum of an array.
Parameters
----------
array_like : array_like
A numeric array of some kind, possibly containing NaN or Inf values.
Returns
-------
tuple
Two-valued tuple containing the fin... | c300b55d2e53685fb0ade9809e13af4cfae4b1a8 | 3,651,614 |
def list_extend1(n):
"""
using a list to built it up, then convert to a numpy array
"""
l = []
num_to_extend = 100
data = range(num_to_extend)
for i in xrange(n/num_to_extend):
l.extend(data)
return np.array(l) | 7a2240a397e32fc438f4245b92f97f103752b60c | 3,651,615 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.