content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import AnyStr
from typing import List
from typing import Dict
def get_node_namespace_total_rating(node: AnyStr,
namespace: AnyStr,
start: AnyStr,
end: AnyStr,
ten... | f63fb597ddb9f1c4b55c13e37985b72dc97531fd | 78,074 |
async def messages(request: web.Request):
"""
Sends a message in the specified guild and channel
Needs to be called with a json payload:
{
"message": Optional[str],
"embed_title": Optional[str],
"embed_description": Optional[str],
"guilds": [
{
... | 7660c0f9caf9652c0bf4b4933037840a0be47f2b | 78,076 |
def getPCModule(moduleName, moduleDir=None):
"""
@type moduleName: str
@param moduleDir: if specified, the directory where the module can
be loaded from; allows discerning between modules
with the same name in a different directory.
Note... | f665053eaa1b56c085ad2aaaff4309cc36d04d48 | 78,077 |
def white(ntaps):
"""Compute impulse response for white noise.
:param ntaps: Length of impulse response.
:returns: Impulse response of length `ntaps`.
"""
ir = np.zeros(ntaps)
ir[0] = 1
return np.fft.ifftshift(ir) | 51149c35a566afe937c67af4fde6cd0b84057a8e | 78,078 |
def sort_by_absolute_val(df, column):
"""Sort df column by descending order in terms of the absolute value."""
df = df.reindex(df[column]
.abs()
.sort_values(ascending=False)
.index)
return df | bf9fdba373cd93c3b385154710b9b310e2a26ac8 | 78,079 |
def gluon_resnet50_v1d(pretrained=False, num_classes=1000, in_chans=3, **kwargs):
"""Constructs a ResNet-50 model.
"""
default_cfg = default_cfgs['gluon_resnet50_v1d']
model = GluonResNet(BottleneckGl, [3, 4, 6, 3], num_classes=num_classes, in_chans=in_chans,
stem_width=32, deep_... | a351da79af862dc69f4d19b24c55ab050b4e8eee | 78,080 |
def GetTableIncrValue(tablename):
"""
"""
database = dbpool.config.get('db')
sql = """SELECT AUTO_INCREMENT FROM information_schema.`TABLES` \
WHERE TABLE_SCHEMA='%s' AND TABLE_NAME='%s';"""%(database,tablename)
conn = dbpool.connection()
cursor = conn.cursor()
cursor.execute(sql)
re... | dcc1cb9f6ab659570c854898b5be32f49a328f1b | 78,081 |
def IndexFramesWithCrashedGroup(stacktrace, crashed_group_factory,
dependencies):
"""Index frames in stacktrace by dep_path and crashed_groups.
Args:
stacktrace (Stacktrace): The stacktrace to parse.
crashed_group_factory (callable): A callable to factory crashed_group.
... | b6c8a36b6d4063e2b3dc7dc6da74b680731ae118 | 78,082 |
import optparse
def process_cmd_line():
"""Set up and parse command line options"""
usage = "Usage: %prog [options] <file>"
parser = optparse.OptionParser(usage)
parser.add_option("-b", "--batchmode", action="store_true", dest="batchmode",
help="Does not interact with user (no windows etc.)",... | a01dae9b17b706c994970e710ff2aadf609f58a5 | 78,083 |
from .project.project import list_projects
from .project.project import get_project
from .project.project import create_project
from .project.project import delete_project
def project():
"""
methods=='GET':获取指定项目id的信息
Args:
'id'(str, optional):项目id,可选,如果存在就返回项目id对应项目的信息
Return:
... | 87f6ace22f743434405b3bd92a9ddbddee7e3ec3 | 78,084 |
def tokenise_stream(stream):
"""Process stream to an array of tokens."""
return [token for token in stream] | f45ba92834f7b05245dbe9b75a7be9902bd6d19d | 78,085 |
from typing import Mapping
from typing import List
from typing import Any
def read_capabilities(capabilities) -> Mapping[str, List[Any]]:
"""
Reads the capabilities from the relevant section of the config of a building's blueprint
:param capabilities: the config section
:return: a mapping of capabilit... | 65d5f358c33cc75b838c2087d44fe4a8d3acca08 | 78,086 |
def get_ness(log_weights, dx):
"""Normalized ESS (ESS / N)"""
xvals, yvals = get_ess(log_weights, dx=dx)
return xvals, yvals / xvals | b839f48615615a63588977e719e6a134cc4e338c | 78,087 |
def post_message(*args, **kwargs):
"""
Post a message to Slack.
"""
return client().chat_postMessage(*args, **kwargs) | fe45c451c8dd30ce0ef10b242526c409dae0e869 | 78,088 |
def exprClausesToIndexClauses(clauses, symbol_dict):
"""
Convert each Expr in a list of clauses (CNF) into its corresponding index in
the symbol_dict (see mapSymbolAndIndices)
"""
clauses_int = []
for c in clauses:
c_disj = disjuncts(c)
c_int = []
for lit in... | 83061af292fe0b34f071d2f939a855286edae7f2 | 78,089 |
def dvr_response_default_status():
"""
Helper to get/set the default status for response records
@return: the default status_id
"""
s3db = current.s3db
rtable = s3db.dvr_response_action
field = rtable.status_id
default = field.default
if not default:
stable = s3d... | 3c87823b2c8027cb47f8efa6944441056466b264 | 78,090 |
def __compute_percentiles(img, mask, cutoff):
"""
Create the list of percentile values to be used as landmarks for the
linear fitting.
:param img: Image on which to determine the percentiles
:param mask: Mask to use over the image to constraint to the relevant
information
:param cutoff: Val... | f3b08c60818f54bc1bea5d14fce6d87de8733443 | 78,091 |
def pawn_collision(offsets):
"""
Return True if the pawn, after moving with the given offsets, will be on the same cell as another pawn. Otherwise, return False.
"""
current_pawn, others_pawns = split_pawns()
for p in others_pawns.values():
if p == [current_pawn[0] + offsets[0], current_pawn... | 13dc2610c1fe97327e8a764c30c7b7dcb62afd00 | 78,092 |
from numpy import isnan,maximum,seterr
def VPC_dict(N,Dvar,Imean,Ivar):
"""Generates VPC and VPCvar from Imean and Ivar data given N and
Dvar. It is assumed the background offset (Dmean) has been subtracted from
Imean. VPC corresponds to variance per count; when mulitplied by counts,
this scale factor... | a1576a75850c39da37ce2ba1ff925d227a5ff719 | 78,093 |
import math
def area_of_pixel_km2(pixel_size, center_lat):
"""Calculate km^2 area of a wgs84 square pixel.
Adapted from: https://gis.stackexchange.com/a/127327/2397
Parameters:
pixel_size (float): length of side of pixel in degrees.
center_lat (float): latitude of the center of the pixel... | 739502f5983cd51f31a4a4641db6aa27acfee98f | 78,094 |
def get_topic_tele_will(config: ConfigType) -> str:
"""Get topic for tele will."""
return _get_topic_tele(config) + "LWT" | f145a10f0fdc6cb498e3babc86abf682d521bd92 | 78,096 |
def get_timetuples_since_event(timing_grid: list, target_labels: list,
start_label: str, end_label: str=None,
convert_clk_to_ns: bool=False) ->list:
"""
Searches for target labels in a timing grid and returns the time between
the the events and t... | f0a26a795f3c1692e004d0fb42942c69444db3f7 | 78,097 |
def zplane(b, a, filename=None, fignum=1):
"""Plot the complex z-plane given a transfer function.
"""
# get a figure/plot
plt.figure(fignum)
ax = plt.subplot(111)
# create the unit circle
uc = patches.Circle((0, 0), radius=1, fill=False,
color='black', ls='dashed')
... | 1a3037c87cdf278084c80f56cd1b84bc9fe70d96 | 78,098 |
def pishop(pishop_url : str) -> dict:
"""Scrape product information from pishop.us
Keyword arguments:
pishop_url -- a product url from pishop.us
"""
pishop_product = _pishop._pishop(pishop_url)
return pishop_product | 214b857816924c37877ce1906159ab608c835f71 | 78,099 |
def to_label(row):
"""Convert a Region or (chrom, start, end) tuple to a region label."""
return "{}:{}-{}".format(row.chromosome, row.start + 1, row.end) | bf2f8e51301e7f157c8398f0a85c57d4df1619ed | 78,100 |
def bool_check(arg, config, default):
"""Return bool from `arg` or `config` str, or `default` bool.
Arguments from the parser and configuration file are represented as strings.
Arguments that represent boolean values need string compares, and then
return the actual boolean object.
Args:
ar... | 1b0e7f0bf82bbb535ae05fda24ede06f4e50b54c | 78,101 |
def wraps(func):
"""
Nearly identical to functools.wraps, except that it also
maintains the ``__wraps__`` attribute, which will always
be the origin function.
"""
def wrapped(wrapper):
actual = getattr(func, "__wraps__", func)
for attr in ("__module__", "__name__", "__doc__"):
if hasattr(actual... | af2e2de150bebf0addf450f3d05093e153019f75 | 78,103 |
def glVertexAttribPointerARB(
baseOperation, index, size, type,
normalized, stride, pointer,
):
"""Set an attribute pointer for a given shader (index)
index -- the index of the generic vertex to bind, see
glGetAttribLocation for retrieval of the value,
note that index is a global variable, not per-shader
s... | f9baf5dc1b9906915ffc7f9dec3dcb1229ce2f68 | 78,105 |
from typing import List
from typing import Set
def _reconstruct(vals: List[float], weights: List[int], budget: int, cap: int,
dp: List[List[List[float]]]) -> Set[int]:
"""
Private helper function to reconstruct the included items according to the
optimal solution using backtracking.
:... | d11a2584b717d2159fc3466cacc3a3b854428aa8 | 78,106 |
def cosine_similarity(a: carla.Vector3D, b: carla.Vector3D) -> float:
"""-1: opposite vectors (pointing in the opposite direction),
0: orthogonal,
1: exactly the same (pointing in the same direction)
"""
return dot_product(a, b) / (vector_norm(a) * vector_norm(b)) | 39f130fce63d33dd29fd333368265265300948f0 | 78,107 |
from pathlib import Path
def pytest_collect_file(
file_path: Path, parent: pytest.File
) -> pytest.Collector | None:
"""
This hook is called when collecting test files, and can be used to
modify the file or test selection logic by returning a list of
``pytest.Item`` objects which the ``pytest`` co... | d07a00d44a28d2c3c1ba0c7d269f7990d99b4257 | 78,110 |
def compute_component_suffstats(x, mean, S, N, p_mu, p_k, p_nu, p_L):
"""
Update mean, covariance, number of samples and maximum a posteriori for mean and covariance.
Arguments:
:np.ndarray x: sample to add
:np.ndarray mean: mean of samples already in the cluster
:np.ndarray ... | f7f8d0512f57e6a627255f339e0425b8f4c66bd0 | 78,111 |
def advisors(request):
"""
Renders the advisors page template
"""
return render(request, "advisors.html", {}) | a52dc27e8b6313cf7537c7fc405cc4cab0a56e3b | 78,112 |
def to_unbounded_array(args:list, cursor:int) -> (bool, int, list):
"""Consume any number of values until either reaching the end of args,
or until finding a value starting with '-', denoting the beginning of a new argument.
Return success, the cursor, and the list of values.
Currently this can't actual... | 30b9efb7f5f9c38e00f937846886f759f348d22a | 78,113 |
def _cap_str_to_mln_float(cap):
"""If cap = 'n/a' return 0, else:
- strip off leading '$',
- if 'M' in cap value, strip it off and return value as float,
- if 'B', strip it off and multiple by 1,000 and return
value as float"""
if cap == 'n/a':
return 0
mult = 1
if ... | 071ddd86ab44cbf7b5521cdf8ddfaf7b7a4b0870 | 78,115 |
def make_cylinder_with_tags(outer_radius, inner_radius, insert_angles, tag_widths):
"""Creates a wire outline of a cylinder with inserts to a smaller
cylinder for part of the radius.
Args:
outer_radius (float): Radius main cylinder.
inner_radius (float): Radius of the inner surface of th... | a39741668944874429565e2e99e0853fee752034 | 78,118 |
def _add_secondary_index(dataframe, system):
"""
Get a 2-indices dataframe from a dataframe with a DateTimeIndex index
with (dataframe.DateTimeIndex, system) as the new index
"""
# Add a secondary index based in the value of `system` in order to avoid
# breaking cluster statistics, i.e. data com... | 89729a1b2ac4e224ddb248c1092c75237e077c4e | 78,119 |
def is_palindrome_permutation_solution(input_string):
"""Same goal as is_palindrome_permutation, but using more efficient
solution from book, using a bit vector.
"""
bit_vector = create_bit_vector(input_string)
# bit_vector must be all 0s, or just have 1 bit set (to 1)
return bit_vector == 0 or ... | a99ed0578bbd3a9ce174758cd9106170cbf763c4 | 78,120 |
def is_fragment_compatible(sequence):
"""check fragment for compatibility
"""
# attach fwd primer and cut site, and confirm cut sites
fragment_extended = MPRA_PARAMS.FWD_PCR_PRIMER + sequence + MPRA_PARAMS.RS_XHOI
if fragment_extended.count(MPRA_PARAMS.RS_ECORI) != 0: return False
if fragment_ex... | 8bf95103a82d33839613369ab62d8d9ff038433f | 78,121 |
def convert_vds_schema_string_to_annotate_variants_expr(
top_level_fields="",
info_fields="",
other_source_fields="",
other_source_root="",
root="",
split_multi=True):
"""Takes a string representation of the VDS variant_schema and generates a string expression
tha... | 73c32d66f743cfa2f2e99691271b336174083723 | 78,122 |
def get_public_key(key, passphrase=None, asObj=False):
"""
Returns a string containing the public key in PEM format.
key:
A path or PEM encoded string containing a CSR, Certificate or
Private Key from which a public key can be retrieved.
CLI Example:
.. code-block:: bash
... | 0386c430d80caf2281786fdddea49ee0045cb2e0 | 78,123 |
import json
def authenticate(user, api, version):
"""Returns google service"""
with open('/code/client_secret.json', 'r') as file:
client_secret_file = json.load(file)
try:
credentials = client.OAuth2Credentials(
access_token=None,
client_id=client_secret_file['web... | c2a70d35913f7f51bd9d2e8881720f42df8ca1e6 | 78,124 |
def ensure_enum(value, cls):
"""确保返回值是对应的 class 对象"""
if type(value) == cls:
return value
return cls(value) | 0dc4b7feee1d6bc04ca6d59786f76723f075fc1e | 78,125 |
def vit_deit_tiny_patch16_224(cfg):
""" DeiT-tiny model @ 224x224 from paper (https://arxiv.org/abs/2012.12877).
ImageNet-1k weights from https://github.com/facebookresearch/deit.
"""
model = VisionTransformer(patch_size=cfg.CONFIG.MODEL.PATCH_SIZE,
embed_dim=192,
... | 38d5c402a96a545f4e8721834231b4bf2fc1752b | 78,126 |
def create_saveable_object(factory, name, call_with_mapped_captures):
"""Creates a SaveableObject while potentially in a different graph.
When creating the frozen saver for SavedModel, the save and restore ops are
placed in a separate graph. Since RestoredSaveableObject uses tf.functions to
save and restore, t... | 90cc7874d00c91ce99e44203dda4edd14153887a | 78,127 |
def temperate_seasons(year=0):
"""Temperate seasons.
Parameters
----------
year : int, optional
(dummy value).
Returns
-------
out : dict
integers as keys, temperate seasons as values.
Notes
-----
Appropriate for use as 'year_cycles' function in :class:`Calenda... | ddf229ef993f64402c2179a3c725a0407e4c3822 | 78,128 |
import glob
def folderCount(path, wildcard= "*",position = "m"):
"""
retuns the count of folders or files in a folder
>>>folderCount(fillpath, wildcard= "*",position = "m")
fullpath --> path to the folder
wildcard --> if not set, it will use '*' as default
position --> to sp... | 4b39dfb9aba359494925eb0dd3fe3558831103e0 | 78,129 |
def manual_stepping(global_step, boundaries, rates):
"""Manually stepped learning rate schedule.
This function provides fine grained control over learning rates. One must
specify a sequence of learning rates as well as a set of integer steps
at which the current learning rate must transition to the next. For... | 225ffbbe8cffdb020a1ecddcb1b5a358ebdfbeb5 | 78,130 |
def create_look_ahead_mask(size):
""" decoder里的遮盖机制 mask """
mask = 1 - tf.linalg.band_part(input=tf.ones((size, size)), num_lower=-1, num_upper=0)
return mask | 5f73b21e8fc83ad9c86b765cacc047a5f4813d25 | 78,131 |
def is_boolean(M):
"""
@brief Test if a matrix M is a boolean matrix.
"""
for i in M:
for j in i:
if j != 0 and j != 1:
return False
return True | d9514e3b268d1726893ff53395b4a039341eba71 | 78,132 |
def DateWidget(*args, **kw):
"""
DateWidget to pick datetime type, if bounds but no default is
defined default to min.
"""
if kw.get('value') is None and 'min' in kw:
kw['value'] = kw['min']
return DatePicker(*args, **kw) | 7f16facbb8394e1678397389eb8240fcbca12a20 | 78,133 |
def find_clique_embedding(k, m=None, target_graph=None):
"""Find an embedding of a k-sized clique on a Pegasus graph (target_graph).
This clique is found by transforming the Pegasus graph into a K2,2 Chimera graph and then
applying a Chimera clique finding algorithm. The results are then converted back in ... | b8dffbb360299755cb07be61ccb4176c16b25bc8 | 78,134 |
def get_week_day(integer):
"""
Getting weekday given an integer
"""
if integer == 0:
return "Monday"
if integer == 1:
return "Tuesday"
if integer == 2:
return "Wednesday"
if integer == 3:
return "Thursday"
if integer == 4:
return "Friday"
if in... | 5bd0431e8598d56e99f970da738e532630665163 | 78,136 |
def syscmd(cmd, encoding=''):
"""
Execute Shell Command
Args:
cmd: str, cmd command
encoding: str, encoding
Returns:
Output on Success or Returncode in Failure
"""
p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
p.wai... | da159998016e5b418391e5753d464ac3c1791109 | 78,138 |
def get_chatt(user):
"""
This function returns all the branches ID's for a user,
If the user does not exist then False is returned.
"""
chatt_object = Chatt.query.filter_by(user_id=user).first()
if chatt_object is not None:
return [x.id for x in chatt_object.branch]
else:
re... | fef0597f37923d846f00256b25937f7e98a2fe0a | 78,140 |
import base64
import six
def deserialize(obj):
"""Deserialize the given object
:param obj: string representation of the encoded object
:return: decoded object (its type is unicode string)
"""
result = base64.urlsafe_b64decode(obj)
# this workaround is needed because in case of python 3 the
... | a76a6f396b5e0992d4c942d4ede73e16594b7173 | 78,141 |
def _pt_to_axes_units(ax, x, y):
"""Convert (x, y) from point units to axes units on axes `ax`."""
t = ax.transAxes.inverted()
return t.transform((x, y)) - t.transform((0, 0)) | b2a7e0435b147b90903116ab691ea1af8fe89e1e | 78,143 |
def write_encrypted_file(filename, content, password):
"""
Writes the given content to the specified file and encrypts it with the specified password.
:param str filename: File to which the content should be written.
:param str content: Content to be written.
:param str password: Password to encrypt... | 805090ab6682105a4de7a0f9de8dcd834ab871bd | 78,144 |
import yaml
def ydump(data, *args, sort_keys=False, **kwargs):
"""
Create YAML output string for data object. If data is an OrderedDict, original key ordering
is preserved in internal call to yaml.dump().
:param data:
:type data: dict or Bunch
:param args: Additional args passed on to yaml.d... | 4ebf80264a2755bcbbbc620e83064d69f3c76a57 | 78,145 |
import pandas as pd
def shareseq_palette_df():
"""Defines the dataframe for colors pertaining to the celltypes of the SHARE-seq dataset."""
d = {
"celltypes": [
"alpha-high-CD34+ Bulge",
"alpha-low-CD34+ Bulge",
"Isthmus",
"K6+ Bulge/Companion Layer",... | 851a9e8f78e50c2167adfb2a7fc72e0741e7a405 | 78,146 |
def html_parts(
input_string,
source_path=None,
destination_path=None,
input_encoding="unicode",
doctitle=True,
initial_header_level=1,
):
"""
Given an input string, returns a dictionary of HTML document parts.
Dictionary keys are the names of parts, and values are Unicode strings;
... | a5d2eb11460ddc4e528c81233b0e1154bc8b556f | 78,147 |
import base64
import hashlib
def x5t_calculation(cert):
"""
base64url-encoded SHA-1 thumbprint (a.k.a. digest) of the DER
encoding of an X.509 certificate.
:param cert: DER encoded X.509 certificate
:return: x5t value
"""
if isinstance(cert, str):
der_cert = base64.b64decode(cert.... | e5a411ab0da4b01ded08a362e2254b50f1b977a3 | 78,148 |
def binom_coeff_all(N, MAX = None):
""" Sum all all binomial coefficients up to MAX.
"""
B = generatebinary(N, MAX)
s = np.sum(B, axis=1)
c = np.zeros(N+1, dtype=np.int64)
for i in range(N+1):
c[i] = np.sum(s == i)
return c | f2abbbcce6a5b5c1cc718645d81cd9f2a5d8297d | 78,149 |
import requests
import re
def get_cse_tickers_df() -> pd.DataFrame:
"""Grab cse dataframe from exported xlsx sheet
Returns:
clean_df
Dataframe with with randomly selected values. Data columns are as follows:
========== ==================================================================... | a0896c03e43c21852e076fc86f6e3b774bbda305 | 78,151 |
import requests
def push(command: str, f: str = "root", a: str = "cyberlab"):
"""
Push command to repo
:param command : command for push on repository
:param f: folder for push (default : root )
:param a: author of command (default: cyberlab)
:return:
Message of success or error
... | dd3b857738ceb23a9c68da6c2e82d47abc19eb12 | 78,152 |
def tf_slim_with_softmax(inp):
""" Function for returning tf slim model ending in softmax """
net = slim.conv2d(inp, 32, [3, 3])
net = slim.batch_norm(net, decay=.7, epsilon=.65, is_training=False)
net = slim.conv2d(net, 16, [2, 2])
net = slim.batch_norm(net, decay=.6, epsilon=.25, is_training=False... | e040570d34eb837683aa4bbd8d47c6357d1c07b6 | 78,154 |
import torch
def compute_pairwise_distance(data_x, data_y=None, device=None):
"""
Args:
data_x: numpy.ndarray([N, feature_dim], dtype=np.float32)
data_y: numpy.ndarray([N, feature_dim], dtype=np.float32)
Returns:
numpy.ndarray([N, N], dtype=np.float32) of pairwise distances.
""... | 09111e3b7320f1679e6316e510018d232807467a | 78,155 |
def tell(inp, *, user, message):
"""
Send messages to other users.
Saves the message and delivers them to the target next time they're in
the same channel with the bot.
"""
db.Tell.create(
recipient=user,
sender=inp.user,
text=message,
time=arrow.utcnow().timesta... | 4b5016e8a288bf3cfc782867a48c1fbce5c02210 | 78,156 |
def make_table_from_exploded_df(exploded_df: pd.DataFrame, row_heading_cols, column_heading_cols, dfs_dict=None,
value_col: str = "text", concat_with: str = " | ",
convert_numeric_items=False, sort_headers=True) -> pd.DataFrame:
"""
takes in the ex... | aa5b7dbc5e2557e694da04021c6c7598c5727f9e | 78,157 |
from typing import Tuple
def _calc_antihub_occurrence(k_occurrence: np.ndarray) -> Tuple[np.ndarray, float]:
"""Proportion of antihubs in data set.
Antihubs are objects that are never among the nearest neighbors
of other objects.
Parameters
----------
k_occurrence: ndarray
Reverse ne... | 129414c48dcff3d14b9ad88e4e0f17f721648533 | 78,158 |
def serv_gets(tn) -> str:
"""
Reads a string from the server. Keeps on reading with elabora_input()
until it receives a non-command string.
"""
while command_queue.qsize() == 0:
elabora_input(tn)
#print('serv_gets', command_queue.qsize())
line = command_queue.get()
#print('serv_... | 183487898d8f71fd095a6ae58f12c13d14459108 | 78,161 |
def simple_image_collection(im_glob, load_func=skimage.io.imread,
conserve_memory=True, **load_func_kwargs):
"""
Load a collection of images.
Parameters
----------
load_pattern : string or list
If string, uses glob to generate list of files containing
ima... | eb3b04c41c63c031cbebc52ba24bcedcc1d1794d | 78,162 |
def simmat_g(info, covmat, sub_id, chrinterest, save=False, stdsim=False,
progress=False):
"""
Compute similarity matrices using gametic approach.
Parameters
----------
info : class object
A class object created using the function "datacheck"
covmat : A list of pop cov matr... | 615979b74870435182bfd50880f2ec230c64ddaa | 78,163 |
from datetime import datetime
def dosdate(dosdate, dostime):
"""
`dosdate`: 2 bytes, little endian.
`dostime`: 2 bytes, little endian.
returns: datetime.datetime or datetime.datetime.min on error
"""
try:
t = ord(dosdate[1]) << 8
t |= ord(dosdate[0])
day = t & 0b0000000... | 26d5b6cf48128d1a50e6429a1d10e24dcb157e74 | 78,164 |
import logging
def prepare_go_environ():
"""Returns dict with environment variables to set to use Go toolset.
Installs or updates the toolset if necessary.
"""
bootstrap(LAYOUT, logging.INFO)
return get_go_environ(LAYOUT) | ece0bb6096f885de54b1fb3ae3594200ba90c554 | 78,165 |
def svn_wc_revert3(*args):
"""
svn_wc_revert3(char path, svn_wc_adm_access_t parent_access, svn_depth_t depth,
svn_boolean_t use_commit_times,
apr_array_header_t changelists, svn_cancel_func_t cancel_func,
svn_wc_notify_func2_t notify_func,
apr_pool_t pool) -> svn_error_t
"... | eca7bea85bd1a15db7b895cc386233428b7f5336 | 78,166 |
from urllib.parse import urlparse
def get_domain(url: str) -> str:
""" get domain from url by given
Args: str type
Return: str type, return domain if can get
"""
parsed_uri = urlparse(url)
domain = '{uri.netloc}'.format(uri=parsed_uri)
return domain | 9b9847dbca29be4e87f8bcc463adad0c003b1f3a | 78,167 |
def get_random_string(length):
"""Create a random string that is length-chars
long comprised of upper, lower, and digits.
"""
char_pool = [c for c in ascii_letters + digits]
char_list = [choice(char_pool) for _ in range(length)]
return ''.join(char_list) | 805d3fdb644a461a70f11e3226cca96de0164b48 | 78,168 |
def ScheduledGradOptimizer(loss, baseLearningRate, momentum=0.9, decaySteps=1000, decayRate=0.5):
"""
Given the network loss, constructs the training op needed to train the
network using exponential learning rate decay and Nesterov Accelerated Gradient Descent with momentum.
Returns:
the operat... | 0d511f223dbe7f66100d727e5f18e60baef1f44c | 78,171 |
def _get_global_gloo_group():
"""
Return a process group based on gloo backend, containing all the ranks
The result is cached.
Returns:
(group): pytorch dist group.
"""
return dist.group.WORLD | 39821d2848f31101576afbd60dd8d89df9eac491 | 78,172 |
def desired_caps(apk_path, apk_name,
platform_version='4.4',
device_name='Nexus_5X_API_19'):
"""Return capabilities related to emulator."""
return {
'platformName': 'Android',
'newCommandTimeout': 3000,
'autoGrantPermissions': 'True',
'platformVe... | b80ce3090d49569c24df357456e7a09d851ec045 | 78,173 |
def filename_with_size(media, size):
"""Returns the filename with size, e.g. IMG1234.jpg, IMG1234-small.jpg"""
# Strip any non-ascii characters.
filename = media.filename.encode("utf-8").decode("ascii", "ignore")
if size == 'original':
return filename
return ("-%s." % size).join(filename.rsp... | fc77d0b234c1a69fc1d61793cc5e07cf2ae25864 | 78,174 |
from sympy.ntheory.modular import crt
def _decipher_rsa_crt(i, d, factors):
"""Decipher RSA using chinese remainder theorem from the information
of the relatively-prime factors of the modulus.
Parameters
==========
i : integer
Ciphertext
d : integer
The exponent component
... | 17200b88d545d8c3d16a191e6e607389619694a9 | 78,175 |
def circles(circle_1, circle_2):
""" vvvv YOUR CODE STARTS HERE vvvv """
""" ^^^^ YOUR CODE ENDS HERE ^^^^ """
return message_out, overlap_out | 32ee9aeae54e102e84cb1ee9c19db64c0d333a28 | 78,176 |
def test_defaults():
"""
Test the default values for the @event decorator
"""
@event
def f():
return "data"
ce = f()
assert ce["type"] == "parliament.response"
assert ce["source"] == "/parliament/function"
assert ce.data == "data" | cca50c47d17f8eb81937d4e86ce4ce62a97f7d03 | 78,177 |
from typing import Any
import dataclasses
from enum import Enum
def recurse_jsonify(d: Any) -> Any:
"""
Makes bytes objects and unhashable types into strings with 0x, and makes large ints into
strings.
"""
if dataclasses.is_dataclass(d):
new_dict = {}
for field in dataclasses.field... | 679e1b9b2c9105dbe23dab72787afe017863807d | 78,178 |
def expand_node(node):
"""Returns a list of expanded nodes"""
expanded_nodes = []
if(node.position=='L'):
expanded_nodes.append(create_node(move_right(node.state,0,1), node, [0,1], node.depth + 1,'R'))
expanded_nodes.append(create_node(move_right(node.state,0,2), node, [0,2], node.depth + 1,... | 5d4359326b9ac2c2bd8d83422dce3f7678715eb2 | 78,179 |
def get_item(dictionary, key):
"""Return value from dictionary.
Args:
dictionary (dict): Dictionary to retrieve value from.
key (str): Key to perform lookup.
Returns:
Value of key in dictionary.
"""
return dictionary.get(key) | d79fac838e31ff8eb8ac14b7f7f5abec5073f46c | 78,182 |
def trunc(x, out=None, where=True, dtype=None):
"""
Returns the truncated value of the input, element-wise.
The truncated value of the scalar `x` is the nearest integer `i` which is closer to zero
than `x` is. In short, the fractional part of the signed number `x` is discarded.
Note:
Numpy... | 4137f5f081e8fce74273db2dc57d949f2172466e | 78,184 |
from typing import Optional
from typing import Mapping
from typing import Any
from typing import Collection
import tqdm
def upload_word2vec_embedding_file(
path: str,
*,
package_name: str,
package_version: str,
extras: Optional[Mapping[str, Any]] = None,
session: Option... | da3e89482af91dc2e4d8e2b9a6ea12bcf5fc0aca | 78,185 |
def _convert_featuregroup_version_dict(featuregroups_version_dict):
"""
Converts a featuregroup->version dict into a list of {name: name, version: version}
Args:
:featuregroups_version_dict:
Returns:
a list of {featuregroup_name: name, version: version}
"""
parsed_featuregroup... | b5bf961c608917f15cc836f2fdeee82bff89dff2 | 78,186 |
import time
import getpass
def intro(objectlist, name):
"""setting up the introduction of the file and reporting the statements to the attribute list"""
nid = 0
header = u"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<gexf xmlns=\"http://www.gexf.net/1.2draft\" version=\"1.2\">\n"
date = u" <meta lastmodifiedd... | e143fd7dd7702c95b0d9d0f21929c2d336e67100 | 78,187 |
from typing import OrderedDict
def index_schema_builder(table):
"""
Returns a dictionary loaded with all of the indexes available in the table.
``table`` must be an instance of TableSchema.
.. note::
This function is automatically called for you and set to
``schema.databases[name].tables[... | 34fd5d021f5e2140ceac9a728a62683cebb6de2d | 78,188 |
from typing import Tuple
def rsa_keypair() -> Tuple[str, str]:
"""
Generate an RSA keypair with a key size of 2048 bits and an
exponent of 65537. Serialize the public key in the the
X.509 SubjectPublicKeyInfo/OpenSSL PEM public key format
(RFC 5280). Serialize the private key in the PKCS#8 (RFC 34... | 871866a4e68f786c9b7c0ba31a363e58d0eae104 | 78,189 |
def parse_proj(scores, gold=None):
# pylint: disable=too-many-locals
"""
Parse using Eisner's algorithm.
"""
nr, nc = np.shape(scores)
if nr != nc:
raise ValueError("scores must be a squared matrix with nw+1 rows")
N = nr - 1 # Number of words (excluding root).
# Initialize CK... | 55808360b06f62384dca57f753e418efbab47127 | 78,190 |
def root_block_fn_for_beta_variant(net):
"""Gets root_block_fn for beta variant.
ResNet-v1 beta variant modifies the first original 7x7 convolution to three
3x3 convolutions.
Args:
net: A tensor of size [batch, height, width, channels], input to the model.
Returns:
A tensor after three 3x3 convolut... | 90320a2c933517942de18245342bf806b775026e | 78,191 |
def get_layout_size(layout: qc3const.PyCapsule = PANGO_LAYOUT) -> tp.Tuple[int, int]:
"""Returns text layout size
:param layout: (PyCapsule) Pango source layout
:return: (tuple) text layout size
"""
return _libpango.get_layout_pixel_size(layout) | f26f064f475a69d3d7488d15f3df7efc9ea8ac0f | 78,192 |
import io
def markdown_table(headings, records, fields=None, alignment=None, file=None):
"""Generate a Doxygen-flavor Markdown table from records.
See https://stackoverflow.com/questions/13394140/generate-markdown-tables
file -- Any object with a 'write' method that takes a single string
para... | 7105b90fcea41a7aff529318abd2f4e885d3be00 | 78,193 |
import functools
def as_points(f):
"""Decorator utility to help coerce arguments as points
"""
@functools.wraps(f)
def wrapper(*ps):
return f(*(coerce_to_point(p) for p in ps))
return wrapper | cd075c75fee6f005c5a0da49e8ce19bdf2bc4212 | 78,194 |
def _should_save_report_msg(msg):
"""Returns True if the given ForwardMsg should be serialized into
a shared report.
We serialize report & session metadata and deltas, but not transient
events such as upload progress.
"""
msg_type = msg.WhichOneof("type")
return msg_type == "initialize" o... | 8e78580aee25ab4a6d1bf40a774a05031231c2e4 | 78,196 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.