content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def floor(x: ndarray) -> ndarray:
"""Returns the floor of the input, element-wise.."""
return _which_np(x).floor(x) | 58eae0a1b0802514041dc445ac246dc0345c3640 | 3,628,038 |
def brightness_classification(ms_image):
"""
Description of brightness_classification
Classifies pixels of image using a simplified version of the method described in:
- http://www.sciencedirect.com/science/article/pii/S0169204617301950
Geometrical rules are not applied.
Args:
... | 2201b0bbd9cff115709fa73c4dda412cc6fdbb75 | 3,628,039 |
def build_lights(cfg):
"""Build lights."""
return LIGHTS.build(cfg) | 7d6bbca9676f78d849b95f81df49e39e36bdb04a | 3,628,040 |
def get_obo(force: bool = False) -> Obo:
"""Get miRBase as OBO."""
version = bioversions.get_version(PREFIX)
return Obo(
ontology=PREFIX,
name="miRBase",
iter_terms=get_terms,
iter_terms_kwargs=dict(version=version, force=force),
typedefs=[from_species, has_mature],
... | 9202600c1e24a2582fadb62269e21a0f30aea1c0 | 3,628,041 |
import token
import requests
def create_invitation(secrets) -> dict:
"""
Create an invitation for an existing share.
"""
subscription_id = secrets["SUBSCRIPTIONID"]
resource_group_name = "rg_crosstenant"
account_name = "kmdatashare"
share_name = "publishershare1"
invitation_name = "inv... | 6be8cb7aa5d5eef2cababb8e9e918fe0de5f16d0 | 3,628,042 |
def allocate_lock():
"""Dummy implementation of _thread.allocate_lock()."""
return LockType() | 2163feff679d8ea7535e2db13b38e44bf6778e0b | 3,628,043 |
import copy
def cropped_thumbnail(instance, field_name, width=None, height=None, scale=None, **kwargs):
"""Cropper"""
thumbnail_options = copy(kwargs)
ratiofield = instance._meta.get_field(field_name)
image = getattr(instance, ratiofield.image_field)
if ratiofield.image_fk_field:
image = g... | 2f33e33e4591bd16291f5411912596ffff578d3e | 3,628,044 |
import math
def find_roots_quadratic(a: float, b: float, c: float) -> set:
"""Return a set containing the solutions to the equation ax^2 + bx + c = 0.
Each solution is a float.
You may ASSUME that:
- a != 0
- (b * b) - (4 * a * c) >= 0
>>> find_roots_quadratic(1, -15, 56) == {8.0, 7.0}
... | 664f3ec213200ac2ed3a1cc4f8001da4331938bc | 3,628,045 |
def reconcile(
column_to_reconcile,
type_id=None,
top_res=1,
property_mapping=None,
reconciliation_endpoint="https://wikidata.reconci.link/en/api",
):
"""
Reconcile a DataFrame column
This is the main function of this package, it takes in a Pandas Series,
that is, a column of a Data... | f43b14df7016714207612e755231ca17515d46a8 | 3,628,046 |
def dilute_mask(mask, dilute_distance=0):
"""Expand mask regions with given distance
mask: image with dim (H, W, C)
"""
if dilute_distance == 0: # no dilution
return mask
background = np.zeros_like(mask)
# left, right, up, down dilute
l_dilute = background.copy()
r_dilute = back... | 94599454e65c1a55c324d99547bd325c268138fb | 3,628,047 |
def with_expected_arguments(args, env={}):
"""Python script that checks its argv and environment."""
arg_string = ', '.join(['"{}"'.format(arg) for arg in args])
return _SCRIPT_WITH_EXPECTED_ARGUMENTS_TEMPLATE.format(arg_string, env) | 8ae6545da4dbc175501e80af277f84e6f9b32498 | 3,628,048 |
import numpy
def createisosurfacemesh(grid, step=None, offset=None, isolevel=None):
"""
This function creates an isosurface from voxel data using the
marching cubes algorithm.
Returns a mesh.
**Parameters:**
`grid` : 3D numpy array containing the voxel data
`step` : voxel sizes ... | 0dbb1bb4a4d468ec3fc4c30366137f0218904067 | 3,628,049 |
def get_project_cls_by_name(project_name: str) -> tp.Type[bb.Project]:
"""Look up a BenchBuild project by it's name."""
for project_map_key in bb.project.ProjectRegistry.projects:
if not _is_vara_project(project_map_key):
# currently we only support vara provided projects
continu... | 23b346628841cd6de4159cf7ca67db40929b76f8 | 3,628,051 |
def get_next_non_summer_quarter(request):
"""
Return the Term object for the non-summer quarter after the quarter
refered in the current user sesssion.
"""
return get_next_non_summer_term(get_current_quarter(request)) | a3339645813d3835ba33c552ad8ef04fc33fe1fb | 3,628,052 |
def trick_for_mountaincar(state, done, reward, state_):
"""
-1 for each time step, until the goal position of 0.5 is reached.
As with MountainCarContinuous v0, there is no penalty for climbing the left hill,
which upon reached acts as a wall.
state[0] means position: -1.2 ~ 0.6
state[1] veloc... | 7ef703f6df9c1d10a250c18cb85def2702a3378d | 3,628,053 |
def create_optimizer(
learning_rate, num_train_steps,
warmup_steps=0, warmup_proportion=0, lr_decay_power=1.0,
layerwise_lr_decay_power=-1, n_transformer_layers=None):
"""Creates an optimizer and training op."""
global_step = tf.train.get_or_create_global_step()
increment_global_step_op = t... | 03218eb5861388bb5042e8006224a6dddd8b83a2 | 3,628,054 |
def build_cpo_transition_matrix(val):
""" Builds a TransitionMatrix model expression from a Python value.
If active, this method uses the value cache to return the same CpoExpr for the same value.
Args:
val: Value to convert. Iterator or iterators of integers, or existing TransitionMatrix expressi... | eff10fd7cc1a6d7cffb15b1b6589e9a7d9624ec8 | 3,628,055 |
from datetime import datetime
def quarter_to_month(str_date):
"""
Transform string representing year and quarter in date.
Parameters
----------
str_date : string
String representing year (YYYY) and quarter (qq) as YYYYQq.
Returns
-------
date : datetime.date
Transform... | f3cb5fa80df0638c26525fb8f50413a72e125572 | 3,628,056 |
def edge_failure_sampling(failure_scenarios,edge_column):
"""Criteria for selecting failure samples
Parameters
---------
failure_scenarios - Pandas DataFrame of failure scenarios
edge_column - String name of column to select failed edge ID's
Returns
-------
edge_failure_samples - List ... | 91c251241dcde7d457b69b2033a1751b3ae963fd | 3,628,057 |
def basicClusteringProperties(network, clustering):
"""
compute diversity and related properties for the given clustering
adds results to node attributes
"""
if clustering == 'Cluster':
properties = ['InterclusterFraction', 'ClusterDiversity', 'ClusterBridging', 'ClusterCentrality']
else... | bcfed0fb0b6aaf8e7e5d3fb21f212ad165b6ad54 | 3,628,058 |
def deserializer(chain) -> Contract:
"""Set crowdsale end strategy."""
# Create finalizer contract
args = []
contract, hash = chain.provider.deploy_contract('TestBytesDeserializer', deploy_args=args)
return contract | 2db7302256cb7b2d500852ae9012ebf5bf07c04f | 3,628,059 |
from typing import List
def repl_remove_attributes_from_sgr(matchobj, remove: List[str]) -> str:
"""Addapted remove_sequence_from_text function to be used with regex"""
return remove_attributes_from_sgr(matchobj.group(0), remove) | b235361f59565f1095d488d06c4b07a2005a61d4 | 3,628,061 |
def _update_data(entity_id, public_key, sso_url, expires_at):
"""
Update/Create the SAMLProviderData for the given entity ID.
Return value:
False if nothing has changed and existing data's "fetched at" timestamp is just updated.
True if a new record was created. (Either this is a new provide... | 73d05b2531a35b202ea9d365051c53052f836df6 | 3,628,062 |
import time
import random
def my_solver(filename: str) -> str:
"""Dummy solver function.
It does nothing apart from waiting on average 2.5sec
:type filename: object
:Return: the same filename a the input
"""
print("Running my solver")
time.sleep(random.random() * 2)
return filename | 8aac2ebe64e8c3d1596441942e4c9a348c977f8f | 3,628,063 |
def distance_reward_predator(dx, dy, dz):
"""
Returns: Reward = $\exp(-c \cdot d^2)$
"""
distance = np.linalg.norm([dx, dy, dz])
rw = np.exp(-config.reward.coef_distance_reward_predator * distance * distance)
return rw, distance | eb99bfa00746b545ee13f4b3b52203c567744d38 | 3,628,064 |
def flags_t_v_chan(data, chan, targets, freq_range=None, pol=[0, 1], **plot_kwargs):
"""Waterfall plot of flagged data in channels vs time.
Parameters
----------
data : :class:`np.ndarray`
complex, shape(num_times, num_chans, num_pol)
chan : :class:`np.ndarray`
real, shape(num_chans... | ac8146cd765620918384347cb4933de3439324e7 | 3,628,066 |
import numpy
import copy
def canonical_pruning(X, y, sample_weight, initial_mx_formula,
loss_function,
iterations=100,
n_candidates=100,
n_kept_best=0,
learning_rate=0.1,
regularization=... | 02b7b95638cb25250f36ad6a5ff799238c1230af | 3,628,067 |
import re
def count_arg_nums(method_signature):
"""
Based on the method signature(jni format) to count the arguments number.
:param method_signature: method signature(jni format)
:return: arguments number
"""
arg_signature = re.findall(re.compile(r'\((.*?)\)'), method_signature)[0]
pattern... | 6703653e26ced05baf1a639d93d6435ea8b6ff8e | 3,628,068 |
def voiceProgression(key, chordProgression):
"""Voices a chord progression in a specified key using DP.
Follows eighteenth-century voice leading procedures, as guided by the cost
function defined in the `chordCost` and `progressionCost` functions.
Returns a list of four-pitch chords, corresponding to s... | cb989f59a9b51d09903985c8be55b8f034bbff23 | 3,628,070 |
def metade(valor:float, formatado:bool = False):
"""
Retorna a metade do valor que você botou
:param valor: o valor que você quer a metade
:param formatado: Se você quer que o valor estaja formatado para R$
:return: A metade do valor
"""
valor /= 2
if(formatado == True):
valorfo... | df6c3fb48ac68620e5d585361e277503902fe476 | 3,628,071 |
def may_data():
"""
Values of a few transport coefficients calculated with
the closed analytic Fermi-Dirac expressions for the
free electron mass at 300 K. The values assume acoustic
phonon scattering.
Parameters
----------
None
Returns
-------
data : ndarray
| Dime... | 14bfb558c2a75a417979c7b112d000f7bd5084d2 | 3,628,072 |
def and_nominal_group(sentence):
"""
add 'and' between nominal groups separated with nothing
Input=sentence Output=sentence
"""
# init
i = 0
list_nominal_group = our_list = []
while i < len(sentence):
# We start by finding the first nominal g... | f204797743326c6146fb2e363bd3f783a6da7a32 | 3,628,073 |
import base64
import zlib
def decompressData(contentData):
"""
Handles the actual decompression of Base64 data.
Args:
contentData: String of Base64 content
Returns:
contentData: Decompressed content of ASCII printable
"""
decoded = base64.b64decode(contentData)
# IO.Comp... | 98ca474f64f7eed2e87fda1602f21a5cbfe517c7 | 3,628,074 |
def compute_edge_measures(ntwk):
"""
These return edge-based measures
"""
iflogger.info("Computing edge measures:")
measures = {}
# iflogger.info('...Computing google matrix...' #Makes really large networks (500k+ edges))
# measures['google_matrix'] = nx.google_matrix(ntwk)
# iflogger.in... | cc426521836ece0dbaa219fade1bc94a7948b5a7 | 3,628,075 |
def gen_new_axis(x_axis, expr, precision):
"""evaluate lagrange interpolation"""
new_x = np.arange(min(x_axis), max(x_axis), precision)
f = lambdify('x', expr, "numpy")
new_y = f(new_x)
return new_x, new_y | 576f52d2b94098472e8f2ed91cffe3587011949c | 3,628,076 |
from typing import Tuple
def calc_fresnel_coefficients(n1, n2, cos_theta1, cos_theta2 = None) -> Tuple:
"""
Args:
n1: Refractive index in first medium.
n2: Refractive index in second medium
cos_theta1: Cosine of angle of incidence.
Returns:
"""
assert np.all(cos_theta1>=... | df37ddb4dece7ee0f89b1974dfe8093deba50b0c | 3,628,077 |
def _fetch_detailed_dataset(args=None):
"""
Fetch detailed info by crawling the detailed artwork pages, using
the links from the basic dataset.
Parallelized with vislab.utils.distributed.map_through_rq.
"""
basic_df = get_basic_df(args)
print("Fetching detailed Wikipaintings dataset by scr... | 9a2c20f1f39046cfff4402066105b0256803bffd | 3,628,078 |
def crop_image(image):
"""
Crop an image that has a padding of 0 value so that there is no empty
margin. Return the cropped image, and the x, y offsets of the new image
coordinates relative to the uncropped image. If there is no non-zero value
in the image, returns False.
Parameters
-------... | 005e4b5ea79bccfffe04a2ccef3c33df2f29f249 | 3,628,079 |
def create_node_from_server(server):
""" Translate AWS EC2 Instance representation into a Node object.
"""
return Node(
id=server.id,
ip=server.private_ip_address,
extIp=server.public_ip_address,
az=server.placement['AvailabilityZone'],
name="",
state=server_s... | 2406e611c60ed5be9240cc09dec7d85bd7f673a2 | 3,628,080 |
def if_nametoindex(name):
"""
Converts interface name to ifindex
@name - inteface name
@return - ifindex in case of success, else raises exception
"""
ret = libc.if_nametoindex(name)
if not ret:
raise RuntimeError("Invalid Name")
return ret | 04c57a397b2b9f62a90ab6b6e4478a8cfc9e238c | 3,628,081 |
def gauss_seidel_split(A):
""" split A matrix in additive lower and upper triangular matrices
Args:
A (ndarray): input matrix
Returns:
L (ndarray): lower triangular matrix
U (ndarray): upper triangular matrix (zero diagonal)
"""
L = np.tril(A)
U = np.triu(A)
np.... | 411f38c48540c8072994e3300da6e49c5d57f7e9 | 3,628,083 |
def _define_annuli(angle_list, ann, n_annuli, fwhm, radius_int, annulus_width,
delta_rot, n_segments, verbose, strict=False):
""" Function that defines the annuli geometry using the input parameters.
Returns the parallactic angle threshold, the inner radius and the annulus
center for each... | 8681ec5e94f5779439c6715a56508cf30fe01cad | 3,628,084 |
from HTMLParser import HTMLParser
def get_links_from_html(html_body):
"""
Extract all <a></a> links from html body
:returns: list of dicts with links data
:param html_body:
"""
links = []
class MyHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs):
self.... | 99a5dd8445e97588d58fda50052ccdbfcea09036 | 3,628,086 |
def adj_to_networkx(graphs):
"""Convert adj matrices to networkx graphs."""
return [nx.from_numpy_array(g) for g in graphs] | 69f05f305f5e34385a02092443b907ecfc375d09 | 3,628,087 |
async def add_datasource(request: Request, call_next):
"""
Attach the data source to the request.state.
"""
# Retrieve the datas ource from query param.
source = data_source(request.query_params.get("source", default="jhu"))
# Abort with 404 if source cannot be found.
if not source:
... | a4624752b3c7a3ede7f7fc564e97a3394350fb9d | 3,628,088 |
from typing import Optional
from typing import List
from typing import Union
from typing import OrderedDict
def summary(
data,
var_names: Optional[List[str]] = None,
fmt: str = "wide",
kind: str = "all",
round_to=None,
include_circ=None,
stat_funcs=None,
extend=True,
credible_inter... | 9d69b4f305a05dcc85f7b02d1e4cef5a80f6a099 | 3,628,089 |
def matrix_multiply(MM):
"""Multiplies a list of matrices: M[0] * M[1] * M[2]..."""
P = MM[0]
for M in MM[1:]:
P = dot(P, M)
return P | d63a9ecad8c951383e9fac4bb35e976972fdd658 | 3,628,090 |
import requests
import html
def urban_lookup(word):
""" returns definitions for a given word from urban dictionary """
resp = requests.get(UD_URL % word)
if resp.ok: # check for 200
doc = html.fromstring(resp.read())
return [d.text for d in doc.xpath('//div[@class="definition"]')]
... | bfba0040c5fbd36570a035abe96d7e2862bb6799 | 3,628,091 |
from typing import List
from typing import Dict
from typing import Optional
from typing import Any
def encode_sequences(
sequences: List[str],
vocab: Dict[str, int],
target_size: Optional[int] = None,
eos: int = -1,
sos: Optional[int] = None,
pad: Optional[int] = None,
**kwargs: Any,
) -> ... | dc0edd5bac8356df6a491efb8a331516573306b5 | 3,628,092 |
def form_columns(form):
"""
:param form: Taken from requests.form
:return: columns: list of slugified column names
labels: dict mapping string labels of special column types
(observed_date, latitude, longitude, location)
to names of columns
"""
labels = {}
... | a3a2fdaa17310c04bb28675f88976cd7283f65a9 | 3,628,093 |
def resolve_bbox_order(bbox, crs, size):
"""
Utility that puts the OGC WMS/WCS BBox in the order specified by the CRS.
"""
crs = pyproj.CRS(crs)
r = 1
if crs.axis_info[0].direction != "north":
r = -1
lat_start, lon_start = bbox[:2][::r]
lat_stop, lon_stop = bbox[2::][::r]
siz... | 13c29fe44b241f262c1c07b144f9592b1649714e | 3,628,094 |
import collections
def _r(val):
"""
Convert val to valid R code
"""
if isinstance(val, str):
# no quoting quote
if val.startswith("quote("):
return val
return '"{0}"'.format(val)
if val is True:
return "TRUE"
if val is False:
return "FALSE"... | 6a6fbcbfd0a32105aa2b2d796525421e9d156d25 | 3,628,095 |
def bin2int(buf):
"""the reverse of int2bin, convert a binary buffer to an integer"""
x = 0
for b in bytearray(buf):
x <<= 8
x |= b
return x | 0c0edd88d7d4157f60641bc05f810184ef56f133 | 3,628,096 |
from vardefunc.noise import decsiz
from vsutil import get_y
from typing import Union
from typing import Tuple
def main() -> Union[vs.VideoNode, Tuple[vs.VideoNode, ...]]:
"""Vapoursynth filtering"""
src = JP_BD.clip_cut
panorama = flt.panner_x(src, JP_BD.workdir.to_str() + r"/assets/ED/FGCBD_NCED1_panora... | b8a2d52e66f42ab23f5e31ea8cf8907d1da6c453 | 3,628,097 |
import base64
import six
def UrlSafeB64Decode(message):
"""wrapper of base64.urlsafe_b64decode.
Helper method to avoid calling six multiple times for preparing b64 strings.
Args:
message: string or binary to decode
Returns:
decoded data in string format.
"""
data = base64.urlsafe_b64decode(six.e... | f675c56f0bbd35661adfbea85135a9434fd7b107 | 3,628,098 |
def crypto_box_open_afternm(ciphertext, nonce, k):
"""
Decrypts and returns the encrypted message ``ciphertext``, using the shared
key ``k`` and the nonce ``nonce``.
:param ciphertext: bytes
:param nonce: bytes
:param k: bytes
:rtype: bytes
"""
if len(nonce) != crypto_box_NONCEBYTES... | 05cdce773ac9537e18661713f491bedafcd2d836 | 3,628,099 |
def imei_parse_nibble(nibble):
"""Parse one nibble of an IMEI and return its ASCII representation."""
if nibble < 10:
return chr(nibble + ord('0'))
if nibble == 0xa:
return '*'
if nibble == 0xb:
return '#'
if nibble == 0xc:
return 'C'
if nibble == 0xd:
ret... | 837445a7679bc5355978d7d4e69c5c9fa166cb3f | 3,628,100 |
def check_command_succeeded(reply):
"""
Return true if command succeeded, print reason and return false if command
rejected
param reply: BinaryReply
return: boolean
"""
if reply.command_number == 255: # 255 is the binary error response code.
print ("Danger! Command reject... | a320b5000f59790e314108398339b9a66dbf6520 | 3,628,101 |
def format_interval(seconds):
""" Format an integer number of seconds to a human readable string."""
units = [
(('week', 'weeks'), 604800),
(('day', 'days'), 86400),
(('hour', 'hours'), 3600),
(('minute', 'minutes'), 60),
#(('second', 'seconds'), 1)
]
result = []
... | 8deae4627807f4c5e0cc1844499ebb39f658f2d0 | 3,628,102 |
def make_arguments_parser():
"""Build and return a command line agument parser."""
parser = ArgumentParser(description=__doc__, epilog="""CSS-HTML-JS-Minify:
Takes a file or folder full path string and process all CSS/HTML/JS found.
If argument is not file/folder will fail. Check Updates works on Python... | 5acdc6c18edaad874f9a0f3328545c57028ceaa4 | 3,628,103 |
def split_on_comma(tokens):
"""Split a list of tokens on commas, ie ``,`` DELIM tokens.
Only "top-level" comma tokens are splitting points, not commas inside a
function or other :class:`ContainerToken`.
:param tokens:
An iterable of :class:`~.token_data.Token` or
:class:`~.token_data.C... | 8b89dc6857a7b3e9bcc02f3a291e0ff0cd8d5f20 | 3,628,104 |
def filter_grps(grps, rcs, irr_col, low, high, **kwargs):
"""
Apply irradiance filter around passsed reporting irradiances to groupby.
For each group in the grps argument the irradiance is filtered by a
percentage around the reporting irradiance provided in rcs.
Parameters
----------
grps ... | 772600b5d6f9d35c4751db6a566b4d886b2790de | 3,628,105 |
from readDB import query_plug_set
async def get_weapon_plug_hashes(perk_socket_set: SocketSet) -> list[PerkColumn]:
"""
get perks for all random and origin perk sockets
:param perk_socket_set: weapon's perk sockets
:return: weapon perks as List of PerkColumn
"""
plug_sets: list[PlugSet] = []
... | 9a66c742ce3ff1cf027585bcd6c360536da7d1c2 | 3,628,106 |
def export_inventory_information():
"""export the inventory search result to cvs, html or excel format."""
db_session = DBSession()
export_results_form = ExportInventoryInformationForm(request.form)
export_data = dict()
export_data['export_format'] = export_results_form.export_format.data
expor... | 5b517f9a195e595ef04410bb4aa11384b2c73729 | 3,628,107 |
from typing import Set
def decide_unsat(K: Set[CNFClause]) -> bool:
"""
Returns if given set of clauses is in CNF, or not
:param K: Set of Clauses in CNF
:return: bool, whether this formula is undecidable or not
"""
R: set[CNFClause] = set()
S: set[CNFClause] = K
while R != S:
... | 6a479d4f2017f7e60f03e9ef85064940bff6581a | 3,628,108 |
def find(db, user):
"""
find the notelist
:param db:
:param user:
:return:
"""
document = db.notelist.find_one({"_id": user})
return document | 04c6ad64e9b8ff2f5cd5462cebb9d37127b6d176 | 3,628,109 |
def clip(x, xmin, xmax, dtype=None):
"""
Clips (limits) the values in an array.
Given an interval, values outside the interval are clipped to the interval edges.
For example, if an interval of :math:`[0, 1]` is specified, values smaller than 0 become 0,
and values larger than 1 become 1.
Note:... | c99ba428593c589e6844cfd5e355d27cb36c5904 | 3,628,110 |
import math
def jump(distance, delta_piece_y):
"""
跳跃一定的距离
"""
# 计算程序长度与截图测得的距离的比例
scale = 0.945 * 2 / head_diameter
actual_distance = distance * scale * (math.sqrt(6) / 2)
press_time = (-945 + math.sqrt(945 ** 2 + 4 * 105 *
36 * actual_distance)) / (2 * ... | 45c7ade5213d7997a6742373fc92026ab56280b3 | 3,628,111 |
def get_mean_hourly_sleep_mr_df(sleep_profile, colnames):
"""
Creates summary df for mean hourly sleeping metabolic rate for each fly.
Exported as sheet to excel.
"""
mr_hourly = sleep_profile.iloc[:,1::3]
# sleep profile is split into top half: day; bottom half: night
night_bool_list = [x >... | 167c58bba7bc8e3a5e456a9c20d4a7a55ba722d0 | 3,628,112 |
def characters(probabilities):
"""Turn a 1-hot encoding or a probability distribution over the possible
characters back into its (most likely) character representation."""
return [id2char(c) for c in np.argmax(probabilities, 1)] | 7b516b63df60953519fb6ba4b529039b10944947 | 3,628,114 |
def system(t, state, u):
"""
differential system equation
:param t: time
:param state: current state
:param u: input
:return: derivative of the current state
"""
x = state[0]
y = state[1]
result = np.array([3 * x + 5 * y - 2 * x * y + 3 * x ** 2 - 0.5 * y ** 2,
... | 03a61dc8e1447c4ca636aaabd43dc95b63e5c031 | 3,628,115 |
import torch
def LR_classifier(train_set, train_labels, test_set, test_labels, n_way):
""" Wrapper function which trains a logistic regression on train_set/train_labels and return the accuracy on test_set.
Parameters:
train_set -- torch.tensor (n_sample, n_feature), contains training data
trai... | 30ee4a2e5b3585f086a69304564a3e288166e17f | 3,628,116 |
import numpy
def preprocess_image(x, mode='caffe'):
""" Preprocess an image by subtracting the ImageNet mean.
Args
x: numpy.array of shape (None, None, 3) or (3, None, None).
mode: One of "caffe" or "tf".
- caffe: will zero-center each color channel with
respect to ... | a5fe2fe24e9dcef65a7f704a17ab14d4ddb72f97 | 3,628,119 |
def calculate_metric(threshold, args):
"""
给定阈值得到预测类别后,计算precision和recall,其中precision是avg_sample(hit_cnt/pred_cnt), recall是avg_sample(hit_cnt/label_cnt),在当前场景下label_cnt恒等于1
"""
# 格式:label:pred_cls,pred_score;pred_cls,pred_score;
# 78089261739417600:78089261739417600,0.995399;
# 获取label_list... | 97bb7a81e9731a3f0c48000f98669d03f1d48ca4 | 3,628,120 |
from datetime import datetime
def current_time() -> datetime:
"""Return timezone-aware current time as datetime."""
return datetime.now().astimezone() | 2b7237f4c5a0d88ab7643dfdd3b1f8c524683884 | 3,628,122 |
def test_metamodel_callable_must_return_a_metamodel():
"""
Test that meta-model callable must return an instance of TextXMetaModel.
"""
def invalid_metamodel_callable():
return 42
clear_language_registrations()
register_language('test-lang',
pattern='*.test',
... | 8d639c0a0abedb1ad80dc8aa4bbc4f46bc3499a7 | 3,628,123 |
def Reynold(V, D):
""" Calculate Reynold number
Parameters
----------
V : float
velocity
D : float
diameter
Returns
-------
Re : float
Reynold number
"""
nu = 1.004e-6 # kinematic viscosity [m^2/s]
Re = np.abs(V*D/nu)
return Re | c36280eb501ea792ecce7057973d3837d862f05a | 3,628,124 |
def compile(self):
"""Compile AssignNode."""
global register_index
register_type = ""
if '"' not in self.children[1].compile():
register_type = "$N"
else:
register_type = "$S"
byte_code = register_type + "%s = " % register_index
byte_code += self.children[1].compile() + "\... | f0458e66d8245bba69c8f456e9b21785c7f7bee6 | 3,628,125 |
def create_client(*args):
"""
Create an EC2 client for downstream use. Must have a valid AWS configuration for boto3 to use.
:param args: optional profile name for the AWS shared config file.
:return: returns a boto3 EC2 client.
"""
try:
if len(args) == 0:
client = boto3.Ses... | 41ce3acc7e3e443058d3ab01ef05c6b7399da63f | 3,628,126 |
def Uint32ToUint8(z, lsb_first=True):
"""
Example:
np.all(Uint32ToUint8([0x01020304, 0x05060708]) == np.array([4,3,2,1,8,7,6,5], 'uint8'))
"""
return BinToUint8(Uint32ToBin(z, lsb_first)) | 6cb775731c6ec967f02da6b69a48b533e2f3ce3e | 3,628,127 |
from typing import List
def _decode(encoding: Encoding, decoder: Decoder) -> List[int]:
"""Generic decoder using subcalsses to decode different formats.
It works by nitializing a list of timestamps and the decoder with the
initial timestamp from the encoding data structure. The stateful decoder
is t... | 594833d1d518a6dc055ed4769027bd36a44f8038 | 3,628,128 |
def merge_diff(
initial_config=None,
initial_path=None,
merge_config=None,
merge_path=None,
saltenv="base",
):
"""
Return the merge diff, as text, after merging the merge config into the
initial config.
initial_config
The initial configuration sent as text. This argument is ... | bd61a70cfb9c4ebb2ff4399fe7825ea2abcac2e8 | 3,628,130 |
def make_label(label_text):
"""
returns a label object
conforming to api specs
given a name
"""
return {
'messageListVisibility': 'show',
'name': label_text,
'labelListVisibility': 'labelShow'
} | 8c388d138136af4f01ec02db1565d66049b38cf1 | 3,628,131 |
import socket
def ip_to_str(address):
"""Print out an IP address given a string
Args:
address (inet struct): inet network address
Returns:
str: Printable/readable IP address
"""
return socket.inet_ntop(socket.AF_INET, address) | e62099babab38dc16a16f431512741ee532db4e1 | 3,628,132 |
import torch
def _empty_memory(memory_dim):
"""Get a empty memory, assuming the memory is a row vector
"""
return torch.zeros(1, memory_dim) | b7454e52bbc3c20061d53716c2e805603eb041ff | 3,628,133 |
def label_to_roi(label, expansion_mm=[0, 0, 0], return_as_list=False):
"""Generates a region of interest (ROI), defined by a starting index (z,y,x)
and size (s_z, s_y, s_x). This can be used to crop images/labels.
Args:
label (sitk.Image | list): Binary label image/mask/structure to define to ROI
... | efc2278019f8a27c4e792ad71ee8d7dbda2dbc68 | 3,628,134 |
def get_topk_correct(outputs, targets, ks=(1,)):
"""
Computes the precision@K for the specified values of K
"""
maxk = max(ks)
_, pred = outputs.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(targets.view(1, -1).expand_as(pred))
res = []
for k in ks:
correct_k =... | f657e850cff85ede7040f1b46123fc0cc1cadf7e | 3,628,135 |
def _create_spectrogram(signal: np.ndarray,
should_graph: bool = False) -> np.ndarray:
"""Creates spectrogram for signal, and returns it.
Shows graph for the signal with a Gaussian filter overlayed, the
filtered signal, and the FFT of the signal.
"""
n = len(signal) # 128
... | 7e82cf45c1f5be2dbde929293b48110da61a43b6 | 3,628,136 |
import scipy.stats
def test_reblocking():
"""
Tests reblocking against known distribution.
"""
def corr_data(N, L):
"""
Creates correlated data. Taken from
https://pyblock.readthedocs.io/en/latest/tutorial.html.
"""
return np.convolve(np.random.randn(2 ** N), n... | c9caa94e57a38d80d5a599546a00415abb4fdedd | 3,628,137 |
def get_rproj_czdisp(galaxyra, galaxydec, galaxycz, galaxygrpid, HUBBLE_CONST=70.):
"""
Compute the observational projected radius, in Mpc/h, and the observational
velocity dispersion, in km/s, for a galaxy group catalog. Input should match
the # of galaxies, and the output will as well. Based on FoF4 c... | 558e6b5acb6363ba23dc1b95b0628b951eea6138 | 3,628,138 |
def colormap_to_ev_blocks_equidistant(colormap, stops):
"""
For a given number of stops, the colormap is divided into equal length segments. The colors are sampled at the
start and end of these segments. They are then used to create "blocks", a constant color for a range between two
exposure values.
... | 21b69ffae9e867c2326eded9efe797369087a429 | 3,628,139 |
import copy
def turn_acs_into_acsK(actions_taken_so_far, all_samples, K, N, horizon):
"""
start with array, where each entry is (a_t)
end with array, where each entry is (a_{t-(K-1)}..., a_{t-1}, a_{t})
"""
#this will become [K-1, acDim]
past_Kminus1_actions = actions_taken_so_far[-(K - 1):]... | 28d5bda4155f6610361f328c16486e43c0beb472 | 3,628,140 |
def fetch_top_chapter_checkins():
"""
Show checkin count of chapters in this week
"""
re = frappe.db.sql(
"""
SELECT sc.parent_chapter, c.sub_chapter, COUNT(*) AS checkin_count
FROM `tabCheckin` c
JOIN `tabSub Chapter` sc ON c.sub_chapter=sc.name
WHERE c.creation ... | 1b725c0199d28acedf1e941938e924b79c835bc1 | 3,628,142 |
from bitcodin import api_base
def get_api_base():
"""
Get the api base url
:return: string
"""
return api_base | f909de3dae62ce73ad03d813c325801e5a69a9b1 | 3,628,143 |
def simple_reduce_error(
filename,
conservative,
precision,
target_error,
convergence_rate_scale_factor,
):
"""Determine points to add (first) or extend (second) to meet target error.
FILENAME is the data file containing lambda, dhdl_average, and error_est.
"""
points = np.loadtxt(f... | 697f6a100b246ebc783dd0fb7f8e712b989e42da | 3,628,144 |
def read_artist_albums(id, name):
"""get lists of albums for artist
"""
list_a = [(x.name, str(x.release_year), str(x.id))
for x in dmla.list_albums_by_artist('', id, 'Jaar')]
list_c = [(x['album'], x['year']) for x in dmlc.list_albums(DB_C, name)]
return list_a, list_c | f4bdcb3cb7a65bd765fce2c960560367e3be2e9f | 3,628,145 |
def client_add(request):
""" Add new client and see the list of clients """
success_message, error_message = None, None
form = ClientForm
clients = Client.objects.all()
enquiry_form = EnquiryClientForm
enquiry_clients = EnquiryClient.objects.all()
if request.metho... | 4c1023656e307b135e8e9c5b9f1d5875194c0304 | 3,628,146 |
def mult(A, B):
"""
Function to multiply two values A and B, use as "mult(A, B)"
"""
return A * B | 586c9077303dd8a36ae6007ff74756f77ec8fb3b | 3,628,147 |
def remove_stopwords(sentence):
"""
Transforms a given text to its lemmatized form. Assumes clean text separated by spaces.
:param sentence: the text to be lemmatized
:type: string
:return: lemmatized text
:type: string
"""
return ' '.join([w for w in word_tokenize(sentence) if not w in ... | 52b8fd43a710b02b825779ff4d93cb6d988e512d | 3,628,148 |
import re
def fileparse(*args):
"""Split a path into basename, dirpath, and (optional) suffixes.
Translated from perl File::Basename for unix, plus annotations"""
fullname = args[0]
suffixes = args[1:]
if fullname is None:
raise Die("fileparse(): need a valid pathname")
fullname = str(... | cbc2a6b09b9c04647de2d6f65b71bc93f0f92051 | 3,628,149 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.