content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def tcl_delta_remote(curef):
"""
Prepare remote version for delta scanning.
:param curef: PRD of the phone variant to check.
:type curef: str
"""
remotedict = networkutilstcl.remote_prd_info()
fvver = remotedict.get(curef, "AAA000")
if fvver == "AAA000":
print("NO REMOTE VERSION... | 65d1aeb25ce58c066465c3b7eb3e560a54224ba7 | 32,400 |
from typing import Iterable
def prodi(items: Iterable[float]) -> float:
"""Imperative product
>>> prodi( [1,2,3,4,5,6,7] )
5040
"""
p: float = 1
for n in items:
p *= n
return p | 3b8e52f40a760939d5b291ae97c4d7134a5ab450 | 32,401 |
def transformer_prepare_encoder(inputs, target_space, hparams):
"""Prepare one shard of the model for the encoder.
Args:
inputs: a Tensor.
target_space: a Tensor.
hparams: run hyperparameters
Returns:
encoder_input: a Tensor, bottom of encoder stack
encoder_self_attention_bias: a Tensor, con... | af9c5e2ab8fe3508722af822f19671461e92e62d | 32,402 |
from typing import Tuple
def get_bottom_left_coords(
text_width: int,
text_height: int,
text_x: int,
text_y: int,
) -> Tuple[TextOrg, BoxCoords]:
"""Get coordinates for text and background in bottom left corner.
Args:
text_width: Width of the text to be drawn.
text_height: Hei... | 8cf1f88f98990bb727de86152ea5239b725c0fbc | 32,403 |
def read_gcs_zarr(zarr_url, token='/opt/gcsfuse_tokens/impactlab-data.json', check=False):
"""
takes in a GCSFS zarr url, bucket token, and returns a dataset
Note that you will need to have the proper bucket authentication.
"""
fs = gcsfs.GCSFileSystem(token=token)
store_path = fs.get_map... | f6ac1e149639afbc10af052a288eb6536a43a13a | 32,404 |
import operator
def bor(*args: int) -> int:
"""Bitwise or.
Example:
bor(0x01, 0x10) == 0x01 | 0x10
Returns:
int: Inputs.
"""
return list(accumulate(args, operator.or_))[-1] | 6e40612b0117fef5584857c947910fa4a0fa865f | 32,405 |
from Scikit.ML.DocHelperMlExt import MamlHelper
def mlnet_components_kinds():
"""
Retrieves all kinds.
"""
kinds = list(MamlHelper.GetAllKinds())
kinds += ["argument", "command"]
kinds = list(set(kinds))
titles = {
'anomalydetectortrainer': 'Anomaly Detection',
'binarycla... | f5a365f2054a263786ca17a96d58d9f39c7061fe | 32,406 |
import os
import pickle
def get_model(model_name, recompile=False):
""" Get compiled StanModel
This will compile the stan model if a cached pickle does not exist.
Args:
model_name (str): model name without `.stan`
recompile (bool): Force force recompilation.
"""
model_file = model... | 488e939370bc0b7b1a1c36e8c2d63610f275c206 | 32,407 |
from pathlib import Path
import os
def get_pkr_path(raise_if_not_found=True):
"""Return the path of the pkr folder
If the env. var 'PKR_PATH' is specified, it is returned, otherwise a
KeyError exception is raised.
"""
full_path = Path(os.environ.get(PATH_ENV_VAR, os.getcwd())).absolute()
pkr... | 2e43dc9121db910c0b7c9bfa4e21e63203bc0411 | 32,408 |
import time
import json
def wait_for_aee_finish_v1(cfs_name, cfs_namespace): # noqa: C901
"""
Consults k8s API for status information about our CFS/AEE instance; returns
its exit code.
"""
try:
config.load_incluster_config()
except ConfigException: # pragma: no cover
config.l... | 2acf11a74aa71c8645cd9b2118b82c2513518451 | 32,409 |
def hexString(s):
"""
Output s' bytes in HEX
s -- string
return -- string with hex value
"""
return ":".join("{:02x}".format(ord(c)) for c in s) | 22c1e94f0d54ca3d430e0342aa5b714f28a5815b | 32,410 |
def hydrate_board_from_model(a, radius, rect_width):
"""
:type a: ndarray
:type radius: int
:return: Board
"""
b = Board(radius)
for cellId in b.cells:
thid = get_thid_from_cellId(cellId, rect_width)
value = a[thid.y][thid.x]
b.change_ownership(cellId, get_player_name_from_resource(value), in... | d7486e43beb2676aed32da627d03f018b4b91d65 | 32,411 |
from pathlib import Path
def tree_walk():
"""Walk the source folder using pathlib. Populate 3 dicts, a folder dict,
a file dict, and a stats dict.
- Returns:
- [dict]: k: folders; v: size
- [dict]: k: files; v: size
- [dict]:
'file_size'
'num_dirs'
... | e7edf9897560ee5d0ddab5344e0993e4185e6009 | 32,412 |
def handle_response(response, content_type, file_path=None):
"""handle response. Extract, transform and emit/write to file"""
if content_type == "application/json":
if file_path is None:
return response.json()
else:
save_json(response.json(), file_path)
elif conte... | 43291fdf367f27ee3c982235518d6bf28d600691 | 32,413 |
import logging
def parse_request(env) -> tuple[str, dict]:
""" Parse request: resolve method, load method config, merge request method params with defaults.
Return: method name string, method params dict """
request_method = env['REQUEST_METHOD'].upper()
url_parts = urlparse(unquote(env['REQUEST_U... | 36632a86abb34fef79eed6f8a0438ab5e1dc7696 | 32,414 |
import random
def randomCaptchaText(char_set=CAPTCHA_LIST, captcha_size=CAPTCHA_LENGTH):
"""
随机生成定长字符串
:param char_set: 备选字符串列表
:param captcha_size: 字符串长度
:return: 字符串
"""
captcha_text = [random.choice(char_set) for _ in range(captcha_size)]
return ''.join(captcha_text) | ee426c26051e720636659cd013617abce2f77a5e | 32,415 |
def integral_total(Nstrips):
"""
The total integral.
"""
return integral_4(Nstrips) + integral_1(Nstrips) | cc2468c69a3e6c98ee139125afc2f4a571cc588b | 32,416 |
def calculate_amplitude(dem, Template, scale, age, angle):
"""Calculate amplitude and SNR of features using a template
Parameters
----------
dem : DEMGrid
Grid object of elevation data
Template : WindowedTemplate
Class representing template function
scale : float
Scale o... | b286ed97952667052a8ecfacb152b70a7a1be2ba | 32,417 |
import os
def app(request):
"""Session-wide Testable Flask Application
"""
_app.config.from_mapping(
TESTING=True,
SECRET_KEY=os.environ.get('SECRET_KEY'),
SQLALCHEMY_DATABASE_URI=os.getenv('TEST_DATABASE_URL'),
SQLALCHEMY_TRACK_MODIFICATIONS=False,
WTF_CSRF_ENABLE... | bdb383cfdb5a3c857d6b2111ca2b3a1628392f69 | 32,418 |
from typing import OrderedDict
def number_limit_sub_validator(entity_config: OrderedDict) -> OrderedDict:
"""Validate a number entity configurations dependent on configured value type."""
value_type = entity_config[CONF_TYPE]
min_config: float | None = entity_config.get(NumberSchema.CONF_MIN)
max_conf... | 96c33af5e3764cc6cfe0f355de216945b0ab3920 | 32,419 |
from typing import Tuple
from typing import Union
def patch_2D_aggregator(
patches: np.ndarray,
orig_shape: Tuple[int],
patch_loc: np.array,
count_ndarray: Union[np.array, None] = None,
) -> np.ndarray:
"""
Aggregate patches to a whole 2D image.
Args:
patches: shape is [patch_num,... | 3fd7d98c7b792cb3df646045ad32d0cde2c94e56 | 32,420 |
from typing import Callable
def vmap_grad(forward_fn: Callable, params: PyTree, samples: Array) -> PyTree:
"""
compute the jacobian of forward_fn(params, samples) w.r.t params
as a pytree using vmapped gradients for efficiency
"""
complex_output = nkjax.is_complex(jax.eval_shape(forward_fn, params... | 411a3ce1a38c31fef9422ed740d1a7d0a4cf887b | 32,421 |
def random_crop_list(images, size, pad_size=0, order="CHW", boxes=None):
"""
Perform random crop on a list of images.
Args:
images (list): list of images to perform random crop.
size (int): size to crop.
pad_size (int): padding size.
order (string): order of the 'height', 'wi... | e4e7933a02c356c509bbd3d7dbc54814ec1f7bc1 | 32,422 |
from typing import List
def normalize_resource_paths(resource_paths: List[str]) -> List[str]:
"""
Takes a list of resource relative paths and normalizes to lowercase
and with the "ed-fi" namespace prefix removed.
Parameters
----------
resource_paths : List[str]
The list of resource re... | ec7e5020ae180cbbdc5b35519106c0cd0697a252 | 32,423 |
def GetDegenerateSites(seq1, seq2,
degeneracy=4,
position=3):
"""returns two new sequenes containing only degenerate sites.
Only unmutated positions are counted.
"""
new_seq1 = []
new_seq2 = []
for x in range(0, len(seq1), 3):
c1 = seq1[x:... | de9aa02b6ef46cb04e64094b67436922e86e10bb | 32,424 |
def ransac(a, b, model: str ='rigid', inlier_threshold: float = 1.0, ransac_it: int = 100):
"""Estimates parameters of given model by applying RANSAC on corresponding point sets A and B
(preserves handedness).
:param a: nx4 array of points
:param b: nx4 array of points
:param model: Specify the mod... | bbbf3c7695437ef00f4fc4570033575808d84604 | 32,425 |
from typing import List
from datetime import datetime
def create_telescope_types(session: scoped_session, telescope_types: List, created: datetime):
"""Create a list of TelescopeType objects.
:param session: the SQLAlchemy session.
:param telescope_types: a list of tuples of telescope type id and names.
... | 011a8f3950fd0f4bdd3809085d74c45ae5756716 | 32,426 |
from functools import reduce
def update(*p):
""" Update dicts given in params with its precessor param dict
in reverse order """
return reduce(lambda x, y: x.update(y) or x,
(p[i] for i in range(len(p)-1,-1,-1)), {}) | de7f5adbe5504dd9b1be2bbe52e14d11e05ae86f | 32,427 |
def alphabet_to_use(three_letter_code, parity, direction):
"""Return tuple of alphabet to be used for glue in given direction on tile of
given parity.
Note that this refers to the alphabet used for the CANONICAL direction, which
may be the opposite of direction."""
if not parity in (0,1):
r... | b7bb02d5a5b9d5144ab8a6026600bd16096680aa | 32,428 |
def get_tipranks_sentiment(collection):
"""
:param collection: "100-most-popular", "upcoming-earnings", "new-on-robinhood", "technology", "oil-and-gas",
"finance", "software-service", "energy", "manufacturing", "consumer-products", "etf", "video-games", "social-media",
"health", "entertainme... | a6a6527314d2610f20de640aa8e17ad9234d5664 | 32,429 |
def lBoundedForward(x, lower):
"""
Transform from transformed (unconstrained) parameters to physical ones with upper limit
Args:
x (float): vector of transformed parameters
lower (float): vector with lower limits
Returns:
Float: transformed variables and log Jacobian
... | af3b7613f4b08917c835c51c38b6e506f619ab6a | 32,430 |
from datetime import datetime
def date_range(begin_date, end_date):
"""
:param begin_date: 起始日期,string
:param end_date: 结束日期,string
:return: dates: 指定日期范围内日期列表,元素类型string
"""
dates = []
dt = datetime.datetime.strptime(begin_date, "%Y-%m-%d")
date = begin_date[:]
while date <= e... | e168f291226fa00806992f85b3ac2c89f96b8426 | 32,431 |
import os
def in_water(latitude: float, longitude: float) -> bool:
"""
Simple function to parse a shapefile from OpenStreet Maps.
Returns a boolean signifying a location is or is not over
water.
LRU Caching provided via functools.lru_cache. Uses memoization
to cache recently scanned results a... | 8f2a0a5ff9adb6d16cbaefb656481e9825fb7b00 | 32,432 |
import collections
def createNeighDict(rP, lP, b, c):
"""Finds the neighbours nearest to a lost packet in a particular tensor plane
# Arguments
rP: packets received in that tensor plane
lp: packets lost in that tensor plane
b,c : batch and channel number denoting the tensor plane
... | 0b67024dac04678b8cb084eb18312ed8df468d93 | 32,433 |
def get_norm_3d(norm: str, out_channels: int, bn_momentum: float = 0.1) -> nn.Module:
"""Get the specified normalization layer for a 3D model.
Args:
norm (str): one of ``'bn'``, ``'sync_bn'`` ``'in'``, ``'gn'`` or ``'none'``.
out_channels (int): channel number.
bn_momentum (float): the ... | 2def355c8b775512fec9d58a4fa43a0b54734f96 | 32,434 |
import json
def cancel_cheque():
"""取消支票"""
user_id = '96355632'
sn = request.values['sn']
result = pay_client.app_cancel_cheque(user_id, sn, ret_result=True)
return render_template('sample/info.html', title='取消支票结果',
msg=json.dumps({'status_code': result.status_code, '... | 6734aa86a1300f678a22b45407a8597255ad0a33 | 32,435 |
def to_relative_engagement(lookup_table, duration, wp_score, lookup_keys=None):
""" Convert watch percentage to relative engagement.
:param lookup_table: duration ~ watch percentage table, in format of dur: [1st percentile, ..., 1000th percentile]
:param duration: target input duration
:param wp_score: ... | cfecebe5830a7681417d6fbd14485adc6908cb5d | 32,436 |
import dmsky.factory
def factory(ptype, **kwargs):
"""Factory method to build `DenityProfile` objects
Keyword arguments are passed to class c'tor
Parameters
----------
ptype : str
Density profile type
Returns
-------
profile : `DensityProfile`
Newly created object
... | 9acb4b93fc3e82e22ec0360a38def9058cea5640 | 32,437 |
import re
import difflib
def _search_signals(name, stype, intf):
""" Given a port name and signal type find a match in the inteface.
:param name: name of the port
:param stype: the port signal type
:param intf: the interface to search for matching signal
:return:
@todo: this function is hack... | d4b785ecd1da6043180f4654ae6fae8c49455b65 | 32,438 |
def r2_score(y, y_predicted):
"""Calculate the R2 score.
Parameters
----------
y : array-like of shape = number_of_outputs
Represent the target values.
y_predicted : array-like of shape = number_of_outputs
Target values predicted by the model.
Returns
-------
loss : flo... | 00e8004f076e8147f70896bd5304cd73c389522e | 32,439 |
def vcg_solve(goal):
"""Compute the verification conditions for a hoare triple, then
solves the verification conditions using SMT.
"""
assert goal.is_comb("Valid", 3), "vcg_solve"
P, c, Q = goal.args
T = Q.get_type().domain_type()
pt = vcg_norm(T, goal)
vc_pt = [ProofTerm("z3", vc,... | 9f496edd1a3725640582f4016a086fd5dfe70d72 | 32,440 |
def ism_extinction(av_mag: float,
rv_red: float,
wavelengths: np.ndarray) -> np.ndarray:
"""
Function for calculating the optical and IR extinction with the empirical relation from
Cardelli et al. (1989).
Parameters
----------
av_mag : float
Extinct... | cb2bba0cbb396fbac900492fe9b49d70646a4255 | 32,441 |
def rangify(values):
"""
Given a list of integers, returns a list of tuples of ranges (interger pairs).
:param values:
:return:
"""
previous = None
start = None
ranges = []
for r in values:
if previous is None:
previous = r
start = r
elif r ==... | 672b30d4a4ce98d2203b84db65ccebd53d1f73f5 | 32,442 |
def load_balancers_with_instance(ec2_id):
"""
@param ec2_id: ec2 instance id
@return: list of elb names with the ec2 instance attached
"""
elbs = []
client = boto3.client('elb')
paginator = client.get_paginator('describe_load_balancers')
for resp in paginator.paginate():
for elb ... | b9ad53b7cafdbc44f88044e976a700a187605b2d | 32,443 |
def parse_json_frequency_high(df, column, key):
"""
Takes a JETS dataframe and column containing JSON strings
and finds the highest 'Mode' or 'Config' frequency.
Excludes intermediate frequencies
Parameters
----------
df : pandas dataframe
JETS dataframe
column : str
... | e8489ed7bca2357d4be3421932898696daf27bac | 32,444 |
def adapter_checker(read, args):
"""
Retrieves the end sequences and sorts adapter information for each end.
"""
cigar = read.cigartuples
seq = read.query_sequence
leftend, check_in_softl, left_match = get_left_end(seq, cigar, args)
rightend, check_in_softr, right_match = get_right_end(seq, ... | 096fff89eafe7ce7915daac55e95a2ea51e7f302 | 32,445 |
def create_pane(widgets, horizontal, parent_widget=None, compact=False,
compact_spacing=2):
"""Create a widget containing an aligned set of widgets.
Args:
widgets (list of `QWidget`).
horizontal (bool).
align (str): One of:
- 'left', 'right' (horizontal);
... | f291b6482c8d5bb8ecb312b5f5747cf6c4e36e53 | 32,446 |
from typing import List
from typing import Dict
import collections
import sys
def filterbyasn(ips: List[Dict], max_per_asn: Dict, max_per_net: int) -> List[Dict]:
""" Prunes `ips` by
(a) trimming ips to have at most `max_per_net` ips from each net (e.g. ipv4, ipv6); and
(b) trimming ips to have at most `m... | c26c3b0d5a4191ade6b4e25134bc72d0c4792b32 | 32,447 |
def image_TOKEN_search_by_word_query_TOKEN(query_snd_ix, multi_distances,
snd_fnames, img_fnames,
id2pic):
"""map a word token query into the embedding space and find images in the same space
return rank of first neighbor whos... | 81fcd8ef466e4712cbab396ed55626e61f297fac | 32,448 |
import os
import jinja2
def get_package_environment():
"""Loads templates from the current Python package"""
templates_dir = os.path.dirname(templates.__file__)
template_loader = jinja2.FileSystemLoader(searchpath=templates_dir)
return jinja2.Environment(loader=template_loader) | 434d59d97109f369bca31d42b476a9f3810296b5 | 32,449 |
import auth
import os
import sys
def import_token():
"""
Attempts to to get the discord token from auth file then env variable
Returns:
(string)
"""
try:
return auth.DISCORD_HACKSPACE_TOKEN
except ImportError:
try:
return os.environ["DISCORD_HACKSPACE_T... | 6728a6cb4d54ad66d0512fb2aacb85540dd689c5 | 32,450 |
from packaging import version
def _evolve_angles_forwards(
mass_1, mass_2, a_1, a_2, tilt_1, tilt_2, phi_12, f_start, final_velocity,
tolerance, dt, evolution_approximant
):
"""Wrapper function for the SimInspiralSpinTaylorPNEvolveOrbit function
Parameters
----------
mass_1: float
pri... | b4a000db741aab65076ca2257230aaac45634465 | 32,451 |
import logging
def get_execution(execution):
"""Get an execution"""
logging.info('[ROUTER]: Getting execution: '+execution)
include = request.args.get('include')
include = include.split(',') if include else []
exclude = request.args.get('exclude')
exclude = exclude.split(',') if exclude else [... | dfaba70a41e74423f86eca2c645f71dd2c4117ac | 32,452 |
def fz_Kd_singlesite(K: float, p: np.ndarray, x: np.ndarray) -> np.ndarray:
"""Fit function for Cl titration."""
return (p[0] + p[1] * x / K) / (1 + x / K) | 8054447e87c70adb4d6f505c45336ccd839a69c9 | 32,453 |
def show_exam_result(request, course_id, submission_id):
""" Returns exam result template """
course_obj = get_object_or_404(Course, pk=course_id)
submission_obj = get_object_or_404(Submission, pk=submission_id)
submission_choices = submission_obj.choices.all()
choice_ids = [choice_obj.id for choic... | e61ffc8748e3a9aa2cb62e4ed277a08f0be05c07 | 32,454 |
def createInvoiceObject(account_data: dict, invoice_data: dict) -> dict:
"""
example: https://wiki.wayforpay.com/view/852498
param: account_data: dict
merchant_account: str
merchant_password: str
param: invoice_data
reqularMode -> one of [
... | 0ea61d68916c5b6f43e568cb1978bcb05b8eba04 | 32,455 |
from sklearn.cluster import KMeans
def _kmeans_seed_points(points, D, d, C, K, trial=0):
"""A seed point generation function that puts the seed points at customer
node point cluster centers using k-Means clustering."""
kmeans = KMeans(n_clusters=K, random_state=trial).fit(points[1:])
return kmean... | 7131b53b9cf0c8719daa577f7a03c41f068df90d | 32,456 |
def site_geolocation(site):
""" Obtain lat-lng coordinate of active trials in the Cancer NCI API"""
try:
latitude = site['org_coordinates']['lat']
longitude = site['org_coordinates']['lon']
lat_lng = tuple((latitude, longitude))
return lat_lng
except KeyError: # key ['org... | 9fefcd3f49d82233005c88e645efd1c00e1db564 | 32,457 |
def get_scaling_desired_nodes(sg):
"""
Returns the numb of desired nodes the scaling group will have in the future
"""
return sg.get_state()["desired_capacity"] | 5a417f34d89c357e12d760b28243714a50a96f02 | 32,458 |
def _BitmapFromBufferRGBA(*args, **kwargs):
"""_BitmapFromBufferRGBA(int width, int height, buffer data) -> Bitmap"""
return _gdi_._BitmapFromBufferRGBA(*args, **kwargs) | 91fc08c42726ad101e1d060bf4e60d498d1f0b0f | 32,459 |
def get_user_analysis_choice():
"""
Function gets the user input to determine what kind of data
quality metrics s/he wants to investigate.
:return:
analytics_type (str): the data quality metric the user wants to
investigate
percent_bool (bool): determines whether the data will be seen
... | 58ebda03cd4eb12c92951649fc946b00eb1a8075 | 32,460 |
def points_to_segments(points):
"""Convert a list of points, given in clockwise order compared to the inside of the system to a list of segments.
The last point being linked to the first one.
Args:
points (list): list of lists of size 2
Returns:
[np.ndarray]: 2D-array of segments - ea... | 1e560d8e752d34250f73c6e2305c7741a14afe04 | 32,461 |
def resnet_v1_34(inputs,
num_classes=None,
is_training=True,
global_pool=True,
output_stride=None,
spatial_squeeze=True,
reuse=None,
scope='resnet_v1_34', **kwargs):
"""ResNet-34 model of [1]. See ... | 26e7d866a14d6a17acf92c10e4c5d48883c6b5c7 | 32,462 |
from typing import Union
def from_dlpack(x: Union[ivy.Array, ivy.NativeArray]) -> ivy.Array:
"""Returns a new array containing the data from another (array) object with a
``__dlpack__`` method.
Parameters
----------
x object
input (array) object.
Returns
-------
ret
... | c3213a607eb150791e74ffb8a5781e789dcd989f | 32,463 |
def render_webpage_string(vegalite_spec: str) -> str:
"""
Renders the given Vega-lite specification into a string of an HTML webpage
that displays the specified plots.
:param vegalite_spec str: The Vega-lite plot specification to create a
webpage for.
:returns: A string of a webpage with th... | 6b9c410046d6aba3b3de04bcb2cce4779f55b3d1 | 32,464 |
def _parse_blog(element):
"""
Parse and return genral blog data (title, tagline etc).
"""
title = element.find("./title").text
tagline = element.find("./description").text
language = element.find("./language").text
site_url = element.find("./{%s}base_site_url" % WP_NAMESPACE).text
blog_... | a2678c0e55a8db5aee042744f1f343c96c7fe6f1 | 32,465 |
def summarize_block(block):
"""
Return the sentence that best summarizes block.
"""
sents = nltk.sent_tokenize(block)
word_sents = map(nltk.word_tokenize, sents)
d = dict((compute_score(word_sent, word_sents), sent)
for sent, word_sent in zip(sents, word_sents))
return d[max(d.k... | 991d389366f0587f7dc7fe2eaf6966d0b531012f | 32,466 |
def weekend_subsets_3_2_rule(M, i, t, w, e, d1, d2):
"""
TODO: Write me
:param M: Model
:param i:
:param t:
:param w:
:param e:
:param d1:
:param d2:
:return:
"""
days_subset = [d1, d2]
return sum(M.TourTypeDay[i, t, d, w] for d in days_subset) <= \
sum(M... | 16623cac436f51ef70e5c3448737d74b0e4d47c9 | 32,467 |
def get_club_result() -> list:
""" Returns the club's page. """
d = api_call("ion", "activities")
while "next" in d and d["next"] is not None:
for result in d["results"]:
if "cube" in result["name"].lower():
return result
d = api_call("ion", d["next"], False) | 3f335aeb2c476dc29e0d335b00722e5b56eb6716 | 32,468 |
def DiffuserConst_get_decorator_type_name():
"""DiffuserConst_get_decorator_type_name() -> std::string"""
return _RMF.DiffuserConst_get_decorator_type_name() | 97c9a68d35b079a1ecbf71a742c6799c4b6411bb | 32,469 |
import tqdm
def lemmatizer():
"""
Substitutes words by their lemma
"""
lemmatizer = WordNetLemmatizer()
preprocessor = lambda text: [lemmatizer.lemmatize(w) for w in \
text.split(" ")]
def preprocess(name, dataset):
description = " Running NLTK Lemmatizer - preprocessing dataset "
description += "{}..."... | 627ce460abb71969ac3f19832f2854a1a00db7c3 | 32,470 |
import io
def convert_numpy_array(numpy_array: np.ndarray):
"""
Converts a numpy array into compressed bytes
:param numpy_array: An array that is going to be converted into bytes
:return: A BytesIO object that contains compressed bytes
"""
compressed_array = io.BytesIO() # np.savez_compressed... | 1fe24003d00736b86361cf5eef03da304edc6bf6 | 32,471 |
def notas(* valores, sit=False):
"""
-> Função para analisar notas e situações de vários alunos.
:param valores: uma ou mais notas dos alunos (aceita várias)
:param sit: valor opcional, indicando se deve ou não adicionar a situação
:return: dicionário com várias informações sobre a situação da turma... | a6915e9b7b1feef0db2be6fdf97b6f236d73f282 | 32,472 |
def append_OrbitSection(df):
"""Use OrbitDirection flags to identify 4 sections in each orbit."""
df["OrbitSection"] = 0
ascending = (df["OrbitDirection"] == 1) & (df["QDOrbitDirection"] == 1)
descending = (df["OrbitDirection"] == -1) & (df["QDOrbitDirection"] == -1)
df["OrbitSection"].mask(
... | 4f2cad6cb2facf6a7a8c7a89ed7b3df0a56a54c2 | 32,473 |
def _get_old_time(request):
"""
Get's the alarm time the user wants to change
Args:
request (Request): contains info about the conversation up to this point
(e.g. domain, intent, entities, etc)
Returns:
string: resolved 24-hour time in XX:XX:XX format
"""
old_time_entit... | 6a2929ccffb4b397bd9f1dd044e70c871e302e33 | 32,474 |
def sxxxxx(p, nss):
"""
Defines a scalar wavefunction. Input momenta have shape (num events, 4).
Parameters
----------
p: tf.Tensor, scalar boson four-momenta of shape=(None,4)
nss: tf.Tensor, final|initial state of shape=(), values=(+1|-1)
Returns
-------
phi: tf.Tenso... | 429fe82c9781ec8918fe57a68e899f899df8f32f | 32,475 |
import os
def get_user_directories_directory():
"""
Determines the directory where user directories are stored. This is actually
not that easy, and different systems have different ways of doing it. So,
we try adding a user called '_chaptest_' just to see where the directory goes,
and use that.
... | 7546d4d67b4b74fda1ce9cf80aa4fdec185b471c | 32,476 |
def target_risk_contributions(target_risk, cov):
"""
Returns the weights of the portfolio that gives you the weights such
that the contributions to portfolio risk are as close as possible to
the target_risk, given the covariance matrix
"""
n = cov.shape[0]
init_guess = np.repeat(1 / n, n)
... | 82d338f2bc8c6b712e7489b70a3122eee21d0aab | 32,477 |
import urllib, datetime
import xarray as xr
import numpy as np
def read_monthly_indices_from_CLIMEXP(name_of_index):
"""
Try reading various monthly indices from KNMI's Climate Explorer
"""
name_to_url = {
'M1i': 'http://climexp.knmi.nl/data/iM1.dat', # 1910 ->
'M2i': 'http://clim... | 8ea42dbca11e587267ef8e2c13ee1787be9db430 | 32,478 |
def generate_xdataEMX(parm):
"""
Generate the x data from the parameters dictionary
Parameters:
parm: [dict] parameters
Returns:
xdata = nd.array[XNbPoints]
"""
# Extracts the x axis data from the parameter file
try:
xpoints = parm['SSX']
except KeyError:
... | a65b48e51f5013fe82d0b9baafe70330b15f0477 | 32,479 |
import csv
def csv_2d_cartesian(filename, polar=False, scan=False):
"""extract 2d cartesian coordinates from a file"""
x_values = []
y_values = []
with open(filename) as data_file:
odom_data = csv.reader(data_file)
for row in odom_data:
# if scan:
# row[1] =... | 648a8f9bbee8b0b61284bf5a8b93c729bb085c9d | 32,480 |
def get_edge_similarity(node_pos,neighbor_positions):
"""
useful for finding approximate colinear neighbors.
"""
displacements = get_displacement_to_neighbors(node_pos,neighbor_positions)
n_neighbors = neighbor_positions.shape[0]
# Quick and dirty, can reduce computation by factor 2.
similar... | b1b64384d84ffbdd6a042b1e2c3a8a9a2212e61e | 32,481 |
def high_pass_filter(x_vals, y_vals, cutoff, inspectPlots=True):
"""
Replicate origin directy
http://www.originlab.com/doc/Origin-Help/Smooth-Algorithm
"rotate" the data set so it ends at 0,
enforcing a periodicity in the data. Otherwise
oscillatory artifacts result at the ends
This uses a ... | 8a114e1868c28f1de8ee4ac445bd620cb45482ff | 32,482 |
def hyetograph(dataframe, col="precipitation", freq="hourly", ax=None, downward=True):
"""Plot showing rainfall depth over time.
Parameters
----------
dataframe : pandas.DataFrame
Must have a datetime index.
col : string, optional (default = 'precip')
The name of the column in *data... | 17deb837058ddd8ad8db9ed47c960cacfde957db | 32,483 |
def objective(z, x):
""" Objective. """
return park2_3_mf(z, x) | fb65c09f084b0af8848e78582703a1bb4e11e735 | 32,484 |
import json
import re
def validate_config(crawler_path):
"""
Validates config
"""
with open(crawler_path) as file:
config = json.load(file)
if 'total_articles_to_find_and_parse' not in config:
raise IncorrectNumberOfArticlesError
if 'seed_urls' not in config:
raise I... | ba46667fcc0d75be6b28d19c0f5fa2d41f9123dd | 32,485 |
def parse_FORCE_SETS(natom=None, filename="FORCE_SETS", to_type2=False):
"""Parse FORCE_SETS from file.
to_type2 : bool
dataset of type2 is returned when True.
Returns
-------
dataset : dict
Displacement dataset. See Phonopy.dataset.
"""
with open(filename, "r") as f:
... | 54b39f8b111292f53c6231facafb177109972965 | 32,486 |
import time
def DeserializeFileAttributesFromObjectMetadata(obj_metadata, url_str):
"""Parses the POSIX attributes from the supplied metadata.
Args:
obj_metadata: The metadata for an object.
url_str: File/object path that provides context if a warning is thrown.
Returns:
A POSIXAttribute object wi... | 3fb3d3f4e45a622cc12ce1d65b6f02d59efd3f58 | 32,487 |
def hex_to_64(hexstr):
"""Convert a hex string to a base64 string.
Keyword arguments:
hexstr -- the hex string we wish to convert
"""
B64CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
## internals
# bits contains the bits read off so far that don't make enou... | ca8c48bedf4ac776288a8faad06ec80c0289c11e | 32,488 |
def get_frozen_graph(graph_file):
"""Read Frozen Graph file from disk."""
with tf.gfile.FastGFile(graph_file, "rb") as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
return graph_def | e3a7bb3e1abf7eb09e6e11b325176eb95109e634 | 32,489 |
def wrap_functional_unit(dct):
"""Transform functional units for effective logging.
Turns ``Activity`` objects into their keys."""
data = []
for key, amount in dct.items():
if isinstance(key, int):
data.append({"id": key, "amount": amount})
else:
try:
... | 9c86b5c6c4f360e86f39e2bc59ce4a34804cd7fa | 32,490 |
import os
def load_dataset_class(name):
"""dynamically load a class object from a dataset file.
Return: dataset class object
"""
base_dir = os.path.join("lmnet", "datasets")
dataset_class = _load_class_from_name(name, base_dir)
return dataset_class | ce7aa8fe551ddc2b1b2071ea6d744f5759806dbd | 32,491 |
def full_fuel_requirement(mass: int) -> int:
"""Complete fuel requirements for a single module."""
base_fuel = fuel_requirement(mass)
return base_fuel + sum(additional_fuel_requirements(base_fuel)) | 62c9d7e11afd0805d476216bdd113081285b10c4 | 32,492 |
def is_private(name):
"""Check whether a Python object is private based on its name."""
return name.startswith("_") | d04dfd84884bbc8c8be179c6bc5fc1371f426a78 | 32,493 |
import warnings
def get_suitable_output_file_name_for_current_output_format(output_file, output_format):
""" renames the name given for the output_file if the results for current_output format are returned compressed by default
and the name selected by the user does not contain the correct extension.
out... | 6925d721f06e52c8177c5e4f6404629043642cc4 | 32,494 |
def efficientnet_b1(
num_classes: int = 1000,
class_type: str = "single",
dropout: float = 0.2,
se_mod: bool = False,
) -> EfficientNet:
"""
EfficientNet B1 implementation; expected input shape is (B, 3, 240, 240)
:param num_classes: the number of classes to classify
:param class_type: ... | e713946ec937d0beb2069f7a273a311cad4b3305 | 32,495 |
def mark_user_authenticated(user, login):
"""
Modify a User so it knows it is logged in - checked via user.is_authenticated()
"""
setattr(user, ACTIVATED_LOGIN_KEY, login)
return user | dcd706204747c526c2128a49fcf24c7ef8e075bd | 32,496 |
def assignments(bmat, order=1, ntry=10):
"""Make assignments between rows and columns.
The objective is to have assigments following the following conditions:
- all association are allowed in bmat,
- each row is associated with a unique column,
- each column is associated with a unique row,
... | 5d183df6b538b13f53cf4a9ec18527525b5d0383 | 32,497 |
from operator import inv
def _tracemin_fiedler(L, X, normalized, tol, method):
"""Compute the Fiedler vector of L using the TraceMIN-Fiedler algorithm.
"""
n = X.shape[0]
if normalized:
# Form the normalized Laplacian matrix and determine the eigenvector of
# its nullspace.
e ... | 9b14aa1a8973134846bcf31dabe8bb27d70d36fd | 32,498 |
def default_char_class_join_with():
""" default join for char_class and combine types """
return '' | 9d8f15413f56202472f2e1257382babbaa444edc | 32,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.