content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def text_3d(string, depth=0.5):
"""Create 3D text."""
vec_text = _vtk.vtkVectorText()
vec_text.SetText(string)
extrude = _vtk.vtkLinearExtrusionFilter()
extrude.SetInputConnection(vec_text.GetOutputPort())
extrude.SetExtrusionTypeToNormalExtrusion()
extrude.SetVector(0, 0, 1)
extrude.Se... | 7f851303bf9eea1a4777e70f697d7679a37cfcf8 | 25,409 |
from typing import Optional
def get_secret_version(project: Optional[str] = None,
secret: Optional[str] = None,
version: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetSecretVersionResult:
"""
Get a Secret ... | bda99d80fe49f7e799272c48418b605a327f6dfa | 25,410 |
import logging
def logged_class(cls):
"""Class Decorator to add a class level logger to the class with module and
name."""
cls.logger = logging.getLogger("{0}.{1}".format(cls.__module__, cls.__name__))
return cls | 4a6c878c0061b2b1587e8efcdfae21de87a96e71 | 25,411 |
def crop_point(image, height_rate, width_rate):
"""Crop the any region of the image.
Crop region area = height_rate * width_rate *image_height * image_width
Args:
image: a Image instance.
height_rate: flaot, in the interval (0, 1].
width_rate: flaot, in the interval (0, 1].... | f00992597aa5d03fd2aab724668071a17120efbd | 25,413 |
import ast
def test_name_rename():
"""
Test a simple transformer to rename
"""
class Renamer(NodeTransformer):
def visit_Name(self, node, meta):
node.id = node.id + '_visited'
return node
renamer = Renamer()
mod = ast.parse("bob = frank")
transform(mod, ren... | a609211bb1f7fc0055abe4cf99cdc0e131f0924b | 25,414 |
import logging
import random
import string
def fileobj_video(contents=None):
"""
Create an "mp4" video file on storage and return a File model pointing to it.
if contents is given and is a string, then write said contents to the file.
If no contents is given, a random string is generated and set as t... | d3fb1d9c9e97c53853489486e37af1f2497ae0d3 | 25,415 |
def _toIPv4AddrString(intIPv4AddrInteger):
"""Convert the IPv4 address integer to the IPv4 address string.
:param int intIPv4AddrInteger: IPv4 address integer.
:return: IPv4 address string.
:rtype: str
Example::
intIPv4AddrInteger Return
---------------------------------
... | ac5f55146eedaf0b7caca19327ae0a88c9d5282a | 25,416 |
def expand_case_matching(s):
"""Expands a string to a case insensitive globable string."""
t = []
openers = {"[", "{"}
closers = {"]", "}"}
nesting = 0
drive_part = WINDOWS_DRIVE_MATCHER.match(s) if ON_WINDOWS else None
if drive_part:
drive_part = drive_part.group(0)
t.appe... | 7d9f32e641671cf570c7c95397d9de559bab84b4 | 25,417 |
import re
def look_behind(s: str, end_idx: int) -> str:
"""
Given a string containing semi-colons, find the span of text after the last
semi-colon.
"""
span = s[: (end_idx - 1)]
semicolon_matches = [
(m.group(), m.start(), m.end()) for m in re.finditer(r"(?<=(;))", span)
]
if l... | 0cc478e73edd713fa72743f36e29001bb214e26c | 25,418 |
def sum_fspec(files, outname=None):
"""Take a bunch of (C)PDSs and sums them."""
# Read first file
ftype0, contents = get_file_type(files[0])
pdstype = ftype0.replace("reb", "")
outname = _assign_value_if_none(
outname, "tot_" + ftype0 + HEN_FILE_EXTENSION
)
def check_and_distribute... | 8d8eb0f9f75e44b2d1e34abcff4479a055c40483 | 25,419 |
import six
import pytz
def make_aware(dt, tz=None):
"""
Convert naive datetime object to tz-aware
"""
if tz:
if isinstance(tz, six.string_types):
tz = pytz.timezone(tz)
else:
tz = pytz.utc
if dt.tzinfo:
return dt.astimezone(dt.tzinfo)
else:
retur... | b5003de5055c5d283f47e33dfdd6fbe57d6fce96 | 25,420 |
def decrypt(ctxt, kx, spice, blocksize):
""" Main decryption function
Args:
ctxt: ciphertext
kx: key expansion table
spice: spice
blocksize: size of block
Returns:
Decrypted ciphertext
"""
spice = int_to_arr(spice, 512)
c... | 56ca0b7cb61f3eca1c20fcf174b14b6ba79c5dfe | 25,421 |
from itertools import product
def listCombination(lists) -> list:
"""
输入多个列表组成的列表,返回多列表中元素的所有可能组合
:param lists: 多个列表组成的列表
:return: 所有元素可能的组合
"""
result = []
resultAppend = result.append
for i in product(*lists):
resultAppend(i)
return result | 6023cdc205b2780c5cd2cf56113d48a0675b98bf | 25,422 |
import warnings
def write_frame(frame, name, con, flavor='sqlite', if_exists='fail', **kwargs):
"""DEPRECIATED - use to_sql
Write records stored in a DataFrame to a SQL database.
Parameters
----------
frame : DataFrame
name : string
con : DBAPI2 connection
flavor : {'sqlite', 'mysql'... | 0fe3bf204d48489c65ad2497c54f009000ce89b8 | 25,424 |
def edge_slope(e):
"""Calculate the slope of an edge, 'inf' for vertical edges"""
v = edge_vector(e)
try:
return v.z / round(v.xy.length, 4)
except ZeroDivisionError:
return float("inf") | 742427d4f97712504fcb9dc09c2168178f500ac8 | 25,425 |
import torch
def token_downup(target_dict, source_dict):
"""Transform token features between different distribution.
Returns:
x_out (Tensor[B, N, C]): token features.
Args:
target_dict (dict): dict for target token information
source_dict (dict): dict for source token information... | 2fab5ef8aabc9231b0342d74fb07b2b89000dca3 | 25,427 |
def get_score(train_data,train_labels,test_data,test_labels,problem_type):
"""
Returns the f1 score resulting from 3NN classification if problem_type = 'classification',
or the mse from regression if problem_type = 'regression'
"""
if (problem_type=="classification"):
predictor = KNeighborsClassifier(n_neighb... | fc957b09d0d0a60ea21b0fc50fbca94ac8ba4647 | 25,428 |
def build_client_datasets_fn(train_dataset, train_clients_per_round):
"""Builds the function for generating client datasets at each round.
Args:
train_dataset: A `tff.simulation.ClientData` object.
train_clients_per_round: The number of client participants in each round.
Returns:
A function which re... | bcdb7d9c450401bff88635b5bd74c0eb6a0e7da5 | 25,429 |
def get_simple_grid(xbounds, ybounds, shift_origin=None):
""" """
xbounds = np.atleast_1d(xbounds)
if len(xbounds)==1:
xmin,xmax = 0,xbounds[0]
else:
xmin,xmax = xbounds
ybounds = np.atleast_1d(ybounds)
if len(ybounds)==1:
ymin,ymax = 0,ybounds[0]
else:
... | 8580e37ca98dc5d8214b7da563b31e8819b870cd | 25,430 |
def query_hecate(session, ra, dec, _radius, _verbose: bool = True):
""" Query the HECATE catalog """
m=0
gal_offset = []; mag = []; filt = []; dist = []; dist_err = []; gal_ra = []; gal_dec = []; distflag = []; source = []
# set up query
try:
query = session.query(HecateQ3cRecord)
... | bf321d6151226d801479ef5c9170bed597cac903 | 25,431 |
def all_main_characters(raw_data: AniListRawResponse) -> list[Character]:
"""Returns all of the main characters from the data."""
characters: list[Character] = anime_media(raw_data)["mainCharacters"]["nodes"]
return characters | 9ec3f0cc2757fdbec24923aa0953a0c8f094bd24 | 25,432 |
from typing import List
def sequence_to_ngram(sequence: str, N: int) -> List[str]:
"""
Chops a sequence into overlapping N-grams (substrings of length N)
:param sequence: str Sequence to convert to N-garm
:type sequence: str
:param N: Length ofN-grams (int)
:type N: int
:return: List of n... | 8cbe97ee34c75ca3aad038236bd875ea0c3450cd | 25,433 |
def _convert_for_receive(profile):
"""Convert profile to be fed into the receive model.
Args:
profile (pandas.DataFrame): Profile to convert.
Returns:
pandas.DataFrame: Converted profile.
"""
without_profile = profile[profile.age.isna()].reset_index(drop=True)
profile = profil... | 16196499547c7f6e25e75ee8e814d8c89f8ea30d | 25,434 |
def _format_path(path):
"""Format path to data for which an error was found.
:param path: Path as a list of keys/indexes used to get to a piece of data
:type path: collections.deque[str|int]
:returns: String representation of a given path
:rtype: str
"""
path_with_brackets = (
''.j... | 1809080453af154824e867cd8104cedbd616b937 | 25,435 |
def GetLayouts():
"""Returns the layout proxies on the active session.
Layout proxies are used to place views in a grid."""
return servermanager.ProxyManager().GetProxiesInGroup("layouts") | 8099264d77e4daab61d24eb22edb397aeacfa294 | 25,437 |
def decomposition_super1(centroid, highway, coherence,coordinates,input):
"""
Function to perform Experiment 2: Differential Decomposition with level-specific weight
Args:
centroid: Cluster centroid of super pixels
highway: Super pixels after Stage I Super pixeling
coherence: Coherence value a... | 9649d1d267bc442cd999f3afd622156f4c5e1895 | 25,440 |
from typing import List
import math
def get_deck_xs(bridge: Bridge, ctx: BuildContext) -> List[float]:
"""X positions of nodes on the bridge deck.
First the required X positions 'RX' are determined, positions of loads and
abutments etc.. After that a number of X positions are calculated between
each ... | 75447a1929035685aeb14f212beea74bb7b814ad | 25,441 |
def helicsGetFederateByName(fed_name: str) -> HelicsFederate:
"""
Get an existing `helics.HelicsFederate` from a core by name.
The federate must have been created by one of the other functions and at least one of the objects referencing the created federate must still be active in the process.
**Parame... | a262ee67a4b87212be401442d99482a569862f92 | 25,442 |
import functools
import logging
def persistant_property(*key_args):
"""Utility decorator for Persistable-based objects. Adds any arguments as properties
that automatically loads and stores the value in the persistence table in the database.
These arguments are created as permanent persistent propert... | bba4de85830496d414c80960b59422d51af30572 | 25,443 |
import pkg_resources
import csv
def states():
"""
Get a dictionary of Backpage city names mapped to their respective states.
Returns:
dictionary of Backpage city names mapped to their states
"""
states = {}
fname = pkg_resources.resource_filename(__name__, 'resources/City_State_Pairs.csv')
with ope... | 4781170b9f8c8ab654ebb39dd733577351571b3e | 25,444 |
def matrix_set_diag(input_x, diagonal, k=0, alignment="RIGHT_LEFT"):
"""
Calculate a batched matrix tensor with new batched diagonal values.
Args:
input_x (Tensor): a :math:`(..., M, N)` matrix to be set diag.
diagonal (Tensor): a :math`(..., max_diag_len)`, or `(..., num_diags, max_diag_le... | e8dddc42438ae2bc8bf70ef9a0db1b1cdce9dad3 | 25,445 |
def execute_payment(pp_req):
"""Executes a payment authorized by the client."""
payment = paypalrestsdk.Payment.find(pp_req['paymentId'])
if payment.execute({"payer_id": pp_req['PayerID']}):
return True
return False | 4d7f94610b6f8360371099d3774fd4902e47b6c7 | 25,446 |
def create_structural_eqs(X, Y, G, n_nodes_se=40, n_nodes_M=100, activation_se='relu'):
"""
Method to create structural equations (F:U->X) and the original prediction model (M:X->Y). This also calculates and stores residuals.
Parameters
----------
X : pandas DataFrame
input features of the ... | f8ebc336360fa7d04ac1aa90dbb8165e54181f6b | 25,447 |
import random
import math
def random_walk(humans, dt, energy, temperature):
"""
calculates location, speed and acceleration by adding random values to the speed
Args:
humans (list): list of all humans
dt (float): time step in which the movement is calculated
energy (float): amount... | bfc04b4d0ae1a5c6a7c510a72a9ae2607a225a37 | 25,449 |
def format_name(name_format: str, state: State):
"""Format a checkpoint filename according to the ``name_format`` and the training :class:`~.State`.
The following format variables are available:
+------------------------+-------------------------------------------------------+
| Variable ... | 72c9d5a50f1c05e726702f33befe3373a0ba4486 | 25,450 |
from mpi4py import MPI
def allsync(local_values, comm=None, op=None):
"""Perform allreduce if MPI comm is provided."""
if comm is None:
return local_values
if op is None:
op = MPI.MAX
return comm.allreduce(local_values, op=op) | d10174d7774e5691193ae4c08d7fe6838e8c1ee4 | 25,451 |
def vec_bin_array(arr, m):
"""
Arguments:
arr: Numpy array of positive integers
m: Number of bits of each integer to retain
Returns a copy of arr with every element replaced with a bit vector.
Bits encoded as int8's.
"""
to_str_func = np.vectorize(lambda x: np.binary_repr(x).zfill(m))
... | bb56f94413ef611b9a685b835203aad9064b3092 | 25,452 |
from typing import Iterator
from typing import List
def parse_bafs(stream: Iterator[str]) -> List[BAF]:
"""Parses allelic counts output from GATK ModelSegments, which is a SAM-style
header comprising lines starting with @ followed by single line with column
names (CONTIG, POSITION, REF_COUNT, ALT_COUNT,... | b490b007841afd707576780f436175aec6526f14 | 25,453 |
import mpmath
def logpdf(x, chi, c):
"""
Logarithm of the PDF of the ARGUS probability distribution.
"""
if c <= 0:
raise ValueError('c must be positive')
if chi <= 0:
raise ValueError('chi must be positive')
if x < 0 or x > c:
return mpmath.mp.ninf
with mpmath.ex... | 8df44305dfaeaa9b725de7a9224259929c4c8900 | 25,454 |
def sample(colors: list, max_colors: int = 8, sensitivity: int = 75) -> list:
"""
Sample most common colors from a PIL Image object.
:param colors: list of RGB color tuples eg. [(0, 0, 0), (255, 255, 255)]
:param max_colors: maximum number of colors to return
:param sensitivity: how perceptively di... | 5d90dfa3d097ea923f25deafda5b907a41c5909d | 25,455 |
def tf_example_to_feature_description(example,
num_timesteps=DEFAULT_NUM_TIMESTEPS):
"""Takes a string tensor encoding an tf example and returns its features."""
if not tf.executing_eagerly():
raise AssertionError(
'tf_example_to_reverb_sample() only works under eag... | edf4f829b1c0746a34093ea36672a094412794f1 | 25,456 |
import numpy
def generateStructuredGridPoints(nx, ny, v0, v1, v2, v3):
"""
Generate structured grid points
:param nx: number of x cells
:param ny: number of y cells
:param v0: south west corner
:param v1: south east corner
:param v2: north east corner
:param v3: north west corner
:... | 0de9a3a3a47b26c3c3d56088c7ec55d241edeff3 | 25,458 |
def Keywords(lang_id=0):
"""Returns Specified Keywords List
@param lang_id: used to select specific subset of keywords
"""
return [PY_KW, PY_BIN] | 1a0f0ac7d22e4da00438d823c50258cb5ade8574 | 25,459 |
def clear(keyword):
"""``clear`` property validation."""
return keyword in ('left', 'right', 'both', 'none') | c16cc980b9af82b4210e3c8c430cd65934596aa1 | 25,460 |
from typing import List
def PermissionsListOfUser(perm_list: List[str]) -> List[str]:
"""
Takes a list of items and asserts that all of them are in the permissions list of
a user.
:param perm_list: A list of permissions encoded as ``str``
:return: The input perm_list
:raises Invalid... | 811adedcdc9b90a066d6253269de33e0813c8d7b | 25,461 |
import collections
def PrepareForBuild(input_proto, output_proto, _config):
"""Prepare to build toolchain artifacts.
The handlers (from _TOOLCHAIN_ARTIFACT_HANDLERS above) are called with:
artifact_name (str): name of the artifact type.
chroot (chroot_lib.Chroot): chroot. Will be None if the chroot ... | 5c77d9ad318e0b5dd604e5127e9864aac50e7d77 | 25,462 |
from pathlib import Path
import json
def for_properties(path: Path = Path('config.json')):
"""
Simple externalized configuration loader. Properties are loaded from a file containing a JSON object.
:param path: Path to the file.
:return: Simple namespace with the key/value pairs matching the loaded jso... | 44e377ff28cef3b77adbbcc653f6b1ec196f2a2d | 25,463 |
def get_instance_tags(ec2_client: boto3.Session.client, instance_id: str):
"""Get instance tags to parse through for selective hardening"""
tag_values = []
tags = ec2_client.describe_tags(
Filters=[
{
"Name": "resource-id",
"Values": [
... | 94506f230e44d730a89b15263ef74367c777f654 | 25,465 |
from typing import Dict
def getmasterxpub(client: HardwareWalletClient, addrtype: AddressType = AddressType.WIT, account: int = 0) -> Dict[str, str]:
"""
Get the master extended public key from a client
:param client: The client to interact with
:return: A dictionary containing the public key at the ... | 58e20780672b0c7cd1dc0912ef3565e83e220a53 | 25,467 |
from typing import Any
def serialize(
obj: Any,
annotation: Any,
config: SerializerConfig
) -> str:
"""Convert the object to JSON
Args:
obj (Any): The object to convert
annotation (Annotation): The type annotation
config (SerializerConfig): The serializer confi... | 6fc0fab725798c4d5b643c2dfb6a76929173f601 | 25,468 |
def validate_dvprel(prop_type, pname_fid, validate):
"""
Valdiates the DVPREL1/2
.. note:: words that start with integers (e.g., 12I/T**3) doesn't
support strings
"""
if validate:
msg = 'DVPREL1: prop_type=%r pname_fid=%r is invalid' % (prop_type, pname_fid)
#if prop... | fa3129485081d4b7312fda74e87b1203c97e9adc | 25,469 |
def is_ligature(archar):
"""Checks for Arabic Ligatures like LamAlef.
(LAM_ALEF, LAM_ALEF_HAMZA_ABOVE, LAM_ALEF_HAMZA_BELOW, LAM_ALEF_MADDA_ABOVE)
@param archar: arabic unicode char
@type archar: unicode
@return:
@rtype:Boolean
"""
return archar in LIGUATURES | 721c6135064e21ba681c43fc776c0f64f290e2d3 | 25,470 |
def _get_embl_key(line):
"""Return first part of a string as a embl key (ie 'AC M14399;' -> 'AC')"""
# embl keys have a fixed size of 2 chars
return line[:2] | b54f1a94f120f7ac63a0dd2a22bd47d5a5d5eeb9 | 25,471 |
import scipy
def get_region_data(region, lastday=-1, printrows=0, correct_anomalies=True,
correct_dow='r7'):
"""Get case counts and population for one municipality.
It uses the global DFS['mun'], DFS['cases'] dataframe.
Parameters:
- region: region name (see below)
- lastday... | e35b41eca663d25d065d2b656745e7c41e038dc1 | 25,474 |
def MONTH(*args) -> Function:
"""
Returns the month of the year a specific date falls in, in numeric format.
Learn more: https//support.google.com/docs/answer/3093052
"""
return Function("MONTH", args) | 86a44c35e989ccc149935515550d3176549ee82e | 25,475 |
import logging
import time
def Install(browser):
"""Installs |browser|, if necessary. It is not possible to install
an older version of the already installed browser currently.
Args:
browser: specific browst to install.
Returns:
whether browser is installed.
"""
# Only dynamic installation o... | 93bc5b7ad0b1bc8b4d4496a9ae608d2b9fa1848f | 25,477 |
def get_query_string_from_process_type_string(process_type_string: str) -> str: # pylint: disable=invalid-name
"""
Take the process type string of a Node and create the queryable type string.
:param process_type_string: the process type string
:type process_type_string: str
:return: string that c... | 1380ad90a98da26237176890c52a75684e92964e | 25,478 |
def get_column(fn):
"""Get column from Cellomics filename.
Parameters
----------
fn : string
A filename from the Cellomics high-content screening system.
Returns
-------
column : string
The channel of the filename.
Examples
--------
>>> fn = 'MFGTMP_14020618000... | 5582b6952af2cfcc6c2bcf0aeb7d472420766c9c | 25,479 |
def add_tables():
"""
Generates tables in postgres database according to SQLAlchemy
model when this script is invoked directly via terminal.
"""
return database.Base.metadata.create_all(bind=database.engine) | e7da7d2ccef81197faa3393a4e0a04cf1a656b7d | 25,480 |
def label_vertices(ast, vi, vertices, var_v):
"""Label each node in the AST with a unique vertex id
vi : vertex id counter
vertices : list of all vertices (modified in place)
"""
def inner(ast):
nonlocal vi
if type(ast) != dict:
if type(ast) == list:
# pr... | 1216c3ff1f5995e24f0f3a245fad5db820335f4d | 25,483 |
def bias_variable(shape):
"""Create a bias variable with appropriate initialization."""
#initial = tf.constant(0.1, shape=shape)
initial = tf.constant(0.0, shape=shape)
return tf.Variable(initial) | 046c9fc01bba5af90b166e16d3dce9a294decc58 | 25,485 |
def object_gatekeeper(obj, is_auth, ignore_standalone=False):
"""
It's OK to use available_to_public here because the underlying logic is identical.
"""
if not obj:
return False
if is_auth:
return True
else:
try:
return obj.available_to_public
except:
... | 66f0749788f462ba9a0dfee6edf890245aca15ba | 25,487 |
def l1_l2_regularizer(scale_l1=1.0, scale_l2=1.0, scope=None):
"""Returns a function that can be used to apply L1 L2 regularizations.
Args:
scale_l1: A scalar multiplier `Tensor` for L1 regularization.
scale_l2: A scalar multiplier `Tensor` for L2 regularization.
scope: An optional scope name.
Retur... | 6fe25d5f90d23d192c2b0d9897d5e025d534813c | 25,488 |
def test013_ip_range():
"""
to run:
kosmos 'j.data.types.test(name="iprange")'
"""
ipv4 = j.data.types.get("iprange", default="192.168.0.0/28")
assert ipv4.default_get() == "192.168.0.0/28"
assert ipv4.check("192.168.23.255/28") is True
assert ipv4.check("192.168.23.300/28") is False
... | 4ac18b32aef77b5d4c1080150dd218a8f96efcf3 | 25,489 |
def _create_hive_cursor():
"""
Initializes a hive connection and returns a cursor to it
:return: hive cursor
"""
_print_info('Initializing hive cursor.')
return _initialize_hive_connection() | 52e0250b1a163a6ae8f43bbb3ce723cd79518e98 | 25,490 |
def to_vector_single(text, embeddings, maxlen=300):
"""
Given a string, tokenize it, then convert it to a sequence of word embedding
vectors with the provided embeddings, introducing <PAD> and <UNK> padding token
vector when appropriate
"""
tokens = tokenizeAndFilterSimple(clean_text(text))
... | 3000691c9bbb75c9c86b6d740ff2559e10228db4 | 25,492 |
import numpy
def eval_tensor_density(
tens: tf_compat.Tensor, sess: tf_compat.Session = None
) -> float:
"""
Get the density (fraction of non zero values) in a tensor
:param tens: the tensor to get the density for
:param sess: the session to use for evaluating the tensor,
if not supplied ... | 38ed298cdef732a1465a4221a9fbac82535b6d2c | 25,493 |
import collections
def get(key, default):
"""Get a config bloc from the YAML config file.
Args:
default (dict): The default bloc if the key is not available
Returns:
dict: The config bloc (or the default one)
"""
if not key.lower() in _YAML_DICT or isinstance(_YAML_DICT[key.lower... | 40a7ac19bf64667bccd183c28c2fb0c772c8f748 | 25,494 |
def adaptsim(f, a, b, eps=1e-8, max_iter=10000):
"""自适应 Simpson 求积
P.S. 这个函数名来自 Gander, W. and W. Gautschi, “Adaptive
Quadrature – Revisited,” BIT, Vol. 40, 2000, pp. 84-101.
该文档可以在 https://people.inf.ethz.ch/gander/ 找到。
但该函数的实现并没有使用此文中的递归方法。
Args:
f: 要求积的函数
... | b24ed3c2493b8ece19a69cf781a75e7a9e0f9cd0 | 25,495 |
def get_next_position(grid):
"""Returns best next position to send."""
width = len(grid[0])
unprepared = [inspect_around_position(grid, x)
for x in range(1, width - 1)]
return unprepared.index(max(unprepared)) + 2 | 8d1a75766e830ee49c895a5fe90adc3208011c3d | 25,496 |
from typing import Optional
def which_subdir(sha: str) -> Optional[str]:
""" Determine which subset (if any) sha is represented in """
fname = sha + '.json'
for k, v in subdir_contents.items():
if fname in v:
subdir_contents[k].remove(fname)
return k
subdir_contents[MIS... | f5a32354724604f15710bbf9a69c1e5d38e84a83 | 25,497 |
import numpy as np
def smoothedEnsembles(data,lat_bounds,lon_bounds):
"""
Smoothes all ensembles by taking subsamples
"""
### Import modules
print('\n------- Beginning of smoothing the ensembles per model -------')
### Save MM
newmodels = data.copy()
mmean = newmodels[-1,:,:,:... | ed8fe2bc3d4e77384179d6a1a1406ca9446dc973 | 25,498 |
def conv7x7_block(in_channels,
out_channels,
strides=1,
padding=3,
use_bias=False,
use_bn=True,
bn_eps=1e-5,
activation="relu",
data_format="channels_last",
*... | 9de1518d95417877a0bf5e094ebb907c3534434f | 25,499 |
def alpha_to_weights(alpha):
"""归一化. 最终截面绝对值和为2. """
alpha = alpha - np.nanmean(alpha, axis=1, keepdims=True)
mask_pos = (alpha > 0)
mask_neg = (alpha < 0)
alpha_pos = imposter(alpha)
alpha_pos[mask_pos] = alpha[mask_pos]
alpha_pos = alpha_pos / np.nansum(alpha_pos, 1, keepdims=True)
alp... | a2a4436b3457fe644a130d463cf501c6cd623f2c | 25,500 |
def complete_with_fake_data_for_warmup(minimum_n_rows_to_fit, X=None, fv_size=None):
"""Makes fake data to warmup a partial fit process.
If no X is given, will return a random minimum_n_rows_to_fit x fv_size matrix (with values between 0 and 1)
If X is given, will repeat the rows in a cycle until the minimu... | e201fc50f06945b57a166e4c006252cc892865ed | 25,501 |
from typing import Dict
from pathlib import Path
def check_integrity(signify: Dict[str, str], snapshot: Path, url: str) -> bool:
"""Check the integrity of the snapshot and retry once if failed files.
signify -- the signify key and a signify signed file with SHA256 checksums
snapshot -- the directory wher... | 4e33ba5a2652eaba229815eec93dede4aaf6ef5f | 25,502 |
def exp_slow(b, c):
"""
Returns the value b^c.
Property: b^c = b * b^(c-1)
Parameter b: the number to raise to a power
Precondition: b is a number
Parameter c: the exponent
Precondition: c is an int >= 0
"""
# get in the habit of checking what you can
assert type(b) in [floa... | 0d58a98f2b7785c9ac69c8a3f4539cdf71d3f27b | 25,503 |
def pick_theme(manual):
"""
Return theme name based on manual input, prefs file, or default to "plain".
"""
if manual:
return manual
pref_init()
parser = cp.ConfigParser()
parser.read(PREFS_FILE)
try:
theme = parser.get("theme", "default")
except (cp.NoSectionError, c... | 6e815a0f46b5de1f1a0ef16ffa0ba21b79ee048f | 25,504 |
import socket
def ip2host(ls_input):
"""
Parameters : list of a ip addreses
----------
Returns : list of tuples, n=2, consisting of the ip and hostname
"""
ls_output = []
for ip in ls_input:
try:
x = socket.gethostbyaddr(ip)
ls_output.append((ip, x[0]))... | 234b42bf0406ae5fb67d2c1caba9f7f3a1e92a0c | 25,505 |
from typing import Tuple
from typing import List
from pathlib import Path
def process_all_content(file_list: list, text_path: str) -> Tuple[list, list]:
"""
Analyze the whole content of the project, build and return lists
if toc_items and landmarks.
INPUTS:
file_list: a list of all content files
text_path: the... | 51514892d173adf8a4fe9c3196781c558bc24c6a | 25,506 |
import aiohttp
import json
def fuel(bot, mask, target, args):
"""Show the current fuel for Erfurt
%%fuel [<city> <value> <type>]...
"""
"""Load configuration"""
config = {
'lat': 50.9827792,
'lng': 11.0394426,
'rad': 10
}
config.update(bot.config.get(__name__,... | 371ecd5e8a7c99032f2544d8256e89475a8d0cd5 | 25,507 |
def findElemArray2D(x, arr2d):
"""
:param x: a scalar
:param arr2d: a 2-dimensional numpy ndarray or matrix
Returns a tuple of arrays (rVec, cVec), where the corresponding elements in
each are the rows and cols where arr2d[r,c] == x.
Returns [] if x not in arr2d. \n
Example: \n
arr2d =... | 37428b16b6f634483d584ef878eea90646d77028 | 25,509 |
import itertools
def merge(cluster_sentences):
"""
Merge multiple lists.
"""
cluster_sentences = list(itertools.chain(*cluster_sentences))
return cluster_sentences | ec5c9bf7a89bf0d047050d3684876ed481617706 | 25,510 |
def reverse_str(s: str) -> str:
"""Reverse a given string"""
# Python strings are immutable
s = list(s)
s_len = len(s)
# Using the extra idx as a temp space in list
s.append(None)
for idx in range(s_len // 2):
s[s_len] = s[idx]
s[idx] = s[s_len - idx - 1]
s[s_len - id... | 8568ed59d004afde11bd97e0dba58189a447f954 | 25,511 |
def readme():
"""Get text from the README.rst"""
with open('README.rst') as f:
return f.read() | 3cf992e2f983d71445e743599dc8b78411bab288 | 25,512 |
def exact_account(source_account_id):
"""
Get the BU id, OU id by the account id in dynamodb table.
"""
try:
response = dynamodb_table.get_item(Key={'AccountId': source_account_id})
except Exception as e:
failure_notify("Unable to query account id {0}, detailed exception {1}".format(... | 07ff5ef933d00208a5b1aba573c24c5f5987a558 | 25,513 |
import re
def filter_output(output, regex):
"""Filter output by defined regex. Output can be either string, list or tuple.
Every string is split into list line by line. After that regex is applied
to filter only matching lines, which are returned back.
:returns: list of matching records
... | d9760a644bb83aee513391966522946a6514ab72 | 25,514 |
def carteiralistar(request):
"""
Metódo para retornar o template de listar carteiras
"""
usuario = request.user
try:
# Pega o objeto carteira se já existir
carteira = CarteiraCriptomoeda.objects.get(usuario=usuario)
# Pega a chave da API e o saldo
chave_api = carteira... | 32fa51e5c8e6d5a3765b72755cefe24b0ce906a2 | 25,515 |
def scrub(text, stop_chars=DEFAULT_STOP_CHARS, reorder_chars=DEFAULT_REORDER_CHARS):
"""
Scrub text. Runs the relevant functions in an appropriate order.
"""
text = reorder_stop_chars(text, stop_chars=stop_chars, reorder_chars=reorder_chars)
text = remove_columns(text)
text = split_as_one_senten... | c24a072e83b6936c04a2e591d2072b0e49849758 | 25,516 |
def simulate_evoked_osc(info, fwd, n_trials, freq, label, loc_in_label=None,
picks=None, loc_seed=None, snr=None, mu=None,
noise_type="white", return_matrix=True,
filtering=None, phase_lock=False):
"""Simulate evoked oscillatory data based on a... | 45a7fe74c4f84c96cdbf0aa09059778180064460 | 25,517 |
import requests
def token_request():
"""
Request a Access Token from Vipps.
:return: A Access Token
"""
headers = config['token_request']
url = base_url + '/accesstoken/get'
response = requests.post(url, headers=headers)
return response.json() | 3363179cf526422c53a0eafc8c353ba3f7f29e9f | 25,518 |
from apex import amp
def train(args, train_dataset, model, tokenizer, labels, pad_token_label_id):
""" Train the model """
if args.local_rank in [-1, 0]:
tb_writer = SummaryWriter()
args.train_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu)
train_sampler = RandomSampler(train_... | 9d475baa8865f932dd09265d7269eb58f3f31dc2 | 25,519 |
def extract_tunneled_layer(tunnel_packet: scapy.layers.l2.Ether, offset: int, protocol: str):
"""
Extract tunneled layer from packet capture.
Args:
tunnel_packet (scapy.layers.l2.Ether): the PDU to extract from
offset (int): the byte offset of the tunneled protocol in data field of 'packet'... | 69596ba7cc5c9db41a2622aa68be1cad89855eb0 | 25,520 |
def draw_bbox(img, detections, cmap, random_color=True, figsize=(10, 10), show_text=True):
"""
Draw bounding boxes on the img.
:param img: BGR img.
:param detections: pandas DataFrame containing detections
:param random_color: assign random color for each objects
:param cmap: object colormap
... | f88bb4267d9d389dce589ee26058f4ad1e0fb096 | 25,521 |
def print_total_eval_info(data_span_type2model_str2epoch_res_list,
metric_type='micro',
span_type='pred_span',
model_strs=('DCFEE-O', 'DCFEE-M', 'GreedyDec', 'Doc2EDAG'),
target_set='test'):
"""Print the final pe... | e5b754facbf0d203cb143514e143844170400280 | 25,522 |
def build_sentence_representation(s):
""" Build representation of a sentence by analyzing predpatt output.
Returns a weighted list of lists of terms.
"""
s = merge_citation_token_lists(s)
s = remove_qutation_marks(s)
lemmatizer = WordNetLemmatizer()
raw_lists = []
rep_lists = []
... | dd070aef016cc034a79412528aabc951605aa83c | 25,523 |
def create_glucose_previous_day_groups(day_groups: dict) -> dict:
"""
Create a dictionary of glucose subseries, unique to each day in the parent glucose series.
Subseries data of each dictionary item will lag item key (date) by 1 day.
Keys will be (unique dates in the parent series) + 1 day.
Values ... | 6b5373b25ab286291cc351bc115c016c83ea660b | 25,525 |
def mean_abs_scaling(series: pd.Series, minimum_scale=1e-6):
"""Scales a Series by the mean of its absolute value. Returns the scaled Series
and the scale itself.
"""
scale = max(minimum_scale, series.abs().mean())
return series / scale, scale | 00f397993a3c51761ef634371d6e26885602e340 | 25,526 |
def count_total_parameters():
"""
Returns total number of trainable parameters in the current tf graph.
https://stackoverflow.com/a/38161314/1645784
"""
total_parameters = 0
for variable in tf.trainable_variables():
# shape is an array of tf.Dimension
shape = variable.get_shape(... | 8ee1b116ac3338158c7a43acc570776940bb7e0f | 25,528 |
def create_gradient_rms_plot(sticher_dict: dict[str, GDEFSticher], cutoff_percent=8, moving_average_n=1,
x_offset=0, plotter_style: PlotterStyle = None) -> Figure:
"""
Creates a matplotlib figure, showing a graph of the root meean square of the gradient of the GDEFSticher objects ... | e628250d2c1d4548e6b52d48a8313ffa1b5131fe | 25,529 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.