content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import numpy
def calc_min(arr, idx, win_size):
"""Recalculate the window min based on data, index and window size."""
start = max(0, idx - win_size + 1)
nfinite = 0
result = numpy.nan
for i in range(start, idx + 1):
value = arr[i]
nfinite, result = put_min(value, nfinite, result)
... | b0ca52a5e13d696047faae7b1490ae8d01be9320 | 3,618,000 |
def rotation_3d_matrix(theta: float, axis: np.ndarray) -> np.ndarray:
"""Creates a rotation matrix: Slow method.
Inputs are rotation angle theta and rotation axis axis.
The rotation matrix correspond to a rotation of angle theta
with respect to axis axis."""
axis = axis / np.sqrt(np.dot(axis, axis)... | 60c1362518fe572e43d3fe149d6af8e4ab934ec0 | 3,618,001 |
def get_pipeline(xml_node: XmlNode) -> RenderingPipeline:
"""Resolves pipeline by namespace and name or by namespace"""
key = f'{xml_node.namespace}.{xml_node.name}'
try:
return resolve(RenderingPipeline, key)
except DependencyError:
try:
return resolve(RenderingPipeline, xml... | 6474f8247f2b783ffa389ebc21ef4ef10d36cdea | 3,618,002 |
from pathlib import Path
import tempfile
import os
def plotTempature(xi, yi, zi, save_dir='.'):
"""
功能:
绘制温度等值线
输入:
xi: 插值格点后的经向numpy array
yi: 插值格点后的纬向numpy array
zi: 经过matplotlib.mlab.griddata插值后的二维numpy array
输出:
save_dir/tempf... | dee24fedfdf9c9dba9e44052a8beae3a2206324a | 3,618,003 |
import os
def genomics_core_testdata(filename):
"""Gets the path to a testdata named filename in util/testdata.
Args:
filename: The name of a testdata file in the core genomics testdata
directory. For example, if you have a test file in
"third_party/nucleus/util/testdata/foo.txt", filename should... | 784dc7f9ad99c05e34783b5ba04d438f3477acda | 3,618,004 |
def get_authorization(client):
"""
Define authorization arguments for rsync command
:param client: String
:return: String
"""
_ssh_key = None
if not client:
return ''
if 'ssh_key' in system.config[client]:
_ssh_key = system.config[mode.Client.ORIGIN]['ssh_key']
_ssh... | 31eff8f16b2e9aeb550d2a15144c1d8f663706dc | 3,618,005 |
import click
def _get_help_record(opt):
"""Re-implementation of click.Opt.get_help_record.
The variant of 'get_help_record' found in Click makes uses of slashes to
separate multiple opts, and formats option arguments using upper case. This
is not compatible with Sphinx's 'option' directive, which expe... | fb8e3f79e46cd046737de4d001357eafb9a1ef5c | 3,618,006 |
import torch
def select_topk(args, logits, force_no_eos_id=None):
"""
Applies topk sampling decoding.
"""
if force_no_eos_id is not None:
logits[:, force_no_eos_id] = float('-inf')
indices_to_remove = logits < \
torch.topk(logits, args.top_k, axis=-1)[0][
..., ... | 7bf5c142be0dca30bcfc0845ec12c272cfa02292 | 3,618,007 |
def from_file(input, output_path=None, options=None):
"""
Convert HTML file or files to PDF document
:param input: path to HTML file or list with paths or file-like object
:param output_path: (optional) path to output PDF file. If not provided, PDF will be returned as string
:param options: (option... | 998f4b8ae2e39bbf65780a49cc34e951fea0e7d9 | 3,618,008 |
from datetime import datetime
def get_date(fmt='%Y%m%d', delta_day=0):
""" 获取日期字符串,包含 年 + 月 + 日
@param fmt 返回的日期格式
"""
day = datetime.datetime.today()
if delta_day:
day += datetime.timedelta(days=delta_day)
str_d = day.strftime(fmt)
return str_d | 1a5146c3ad0e8410af02935470ba4f2576be877e | 3,618,009 |
def init(input_mgr, user_data, logger):
"""Initialize the example source tool."""
# Get the selected value from the GUI and save it for later use in the user_data
user_data.val = float(input_mgr.workflow_config["Value"])
# Display info on the selected value
logger.display_info_msg(f"The value selec... | dd922eea66b61e152675f9a27f6732cb8bd56209 | 3,618,010 |
from typing import List
def assert_single_whitespace_after_second_semicolon(docstring: List[str]) -> List[str]:
"""
Find the lines conaining prefixes = [":param", ":return", ":raises"].
For those lines make sure that there is only one whitespace after the second semicolon.
:param docstring: list of l... | 8e3f1a2f67782774e52b424e025e5a2cea1ebfca | 3,618,011 |
from typing import Dict
def is_graph_equal(lhs_workbench: Dict, rhs_workbench: Dict) -> bool:
"""Checks whether both workbench contain the same graph
Two graphs are the same when the same topology (i.e. nodes and edges)
and the ports at each node have same values/connections
"""
try:
if n... | 02c327cfb364e01f206458a87d6c4561985b42d6 | 3,618,012 |
def _undrift_from_picked_coordinate_light(
picked_locs, coordinate, info
):
"""Should be identical to _undrift_from_picked_coordinate but with lower
memory usage."""
n_picks = len(picked_locs)
n_frames = info[0]["Frames"]
# Drift per pick per frame
#drift = _np.empty((n_picks, n_frames))
... | db46b018e486e276209ac2e40234b8b223c78b79 | 3,618,013 |
def get_model(**kwargs):
"""
Returns the model.
"""
model = MobileNetV2(**kwargs)
return model | c1511837b9ac66d9ed55b85ef4956f9187cd2a12 | 3,618,014 |
import copy
def combine(to_merge, extend_by):
"""Merge nested dictionaries."""
def _combine(to_merge, extend_by):
for key, value in extend_by.items():
if key in to_merge:
if isinstance(to_merge[key], dict):
_combine(to_merge[key], value)
... | 69a5713e65bace724370c722155a2677cd50c317 | 3,618,015 |
from datetime import datetime
def timestamp(t=None,sep="_"):
""" Creates a timestamp that can easily be included in a filename. """
if t is None:
t = datetime.datetime.now()
#sargs = (t.year,t.month,t.day,t.hour,t.minute,t.second)
#sbase = "".join(["%04d",sep,"%02d",sep,"%02d",sep,"%02d",sep,"... | 9e384faf8902f3791e35a44498865ab8ae77f525 | 3,618,016 |
import torch
def triangle_loss(verts, edge2verts):
"""
Encourages dihedral angle to be 180 degrees.
Args:
verts: B X N X 3
edge2verts: B X E X 4
Returns:
loss : scalar
"""
indices_repeat = torch.stack([edge2verts, edge2verts, edge2verts], dim=2) # B X E X 3 X 4
v... | 8b84e538bfdc1de1317d0eceef2bcf47e1a30636 | 3,618,017 |
def randint(lower: int, upper: int):
"""Sample an integer value uniformly between ``lower`` and ``upper``.
``lower`` is inclusive, ``upper`` is exclusive.
Sampling from ``tune.randint(10)`` is equivalent to sampling from
``np.random.randint(10)``
"""
return Integer(lower, upper).uniform() | 032ae1d194b3aa6161182d30b8f8dcb25ca51611 | 3,618,018 |
def _remove_non_numeric_characters(gtin: str) -> str:
"""
Strip non-numeric characters from a string
"""
return _NON_NUMERIC_CHARACTERS_PATTERN.sub("", gtin) | 822ddaced4063a641e1835b0e0019efcd4f6333f | 3,618,019 |
from datetime import datetime
def increment_timeperiod(time_qualifier, timeperiod, delta=1):
""" method performs simple increment/decrement of the timeperiods
For instance: 2010010119 with delta=1 -> 2010010120
Or 2010010000 with delta=-1 -> 2009120000, etc"""
pattern = define_pattern(timeperiod)
... | 08151995fa1d334d71fdc50d015aac3dc2484cd3 | 3,618,020 |
def get_kernel_prefix_and_full_hash(build_id):
"""Download repo.prop and return the full hash and prefix."""
android_kernel_repo_data = _get_repo_prop_data(build_id,
constants.LKL_BUILD_TARGET)
if android_kernel_repo_data:
for line in android_kernel_repo_data.s... | 14f3bc1e3c5cd625226d91ca8e10efa5fa0e0fc7 | 3,618,021 |
def get_global_cfg_path():
""" Get path to global config file. """
return qisys.sh.get_config_path("qi", "qibuild.xml") | db7d16efd5cee33cda56a61777303e31fe42bd4f | 3,618,022 |
def infrastructure_member_delete(context, data_dict):
"""
Remove a user from an infrastructure.
You must be authorized to edit the infrastructure.
:param id: the id or name of the infrastructure
:type id: string
:param username: name or id of the user
:type username: string
"""
log... | 260facbd1960fa26eac456a540bd5013c07d9a07 | 3,618,023 |
def chr22XY(c):
"""Reformats chromosome to be of the form Chr1, ..., Chr22, ChrX, ChrY, etc.
Args:
c (str or int): A chromosome.
Returns:
str: The reformatted chromosome.
Examples:
>>> chr22XY('1')
'chr1'
>>> chr22XY(1)
'chr1'
>>> c... | 13677f728ce8221e9a6966951353deba703f3294 | 3,618,024 |
def url_to_image(url, flag=cv2.IMREAD_COLOR):
""" download the image, convert it to a NumPy array, and then read
it into OpenCV format """
resp = urlopen(url)
image = np.asarray(bytearray(resp.read()), dtype="uint8")
image = cv2.imdecode(image, flag)
return image | 11f7fed7a6db6909fc7a3f5aa64c29968c145df5 | 3,618,025 |
import os
def write_mapping_file(sum_inputs_df, target_dir, is_fm_summary=False):
"""
Writes a summary map file, used to build summarycalc xref files.
:param summary_mapping: dataframe return from get_summary_mapping
:type summary_mapping: pandas.DataFrame
:param sum_mapping_fp: Summary map file... | b6b61ed1d7d77de53c6fb849c57e5af6ae8a1409 | 3,618,026 |
def arr2str(a: np.ndarray, format_='e', ndigits=2) -> str:
"""convert ndarray of floats to a string expression.
:param a:
:param format_:
:param ndigits:
:return:
"""
return np.array2string(
a,
formatter=dict(
float_kind=(lambda x: f'{x:.{ndigits}{format_}}' if x... | 73d3e02017ff7c71159ab77cf910cb3863b0519d | 3,618,027 |
import re
def searchLiteral(a_string, patterns):
"""assumes a_string is a string, being searched in
assumes patterns is a list of strings, to be search for in a_string
returns a re span object, representing the found literal if it exists,
else None"""
results = []
for pattern in patterns:
... | fcbbbdb61474e441b5fe0a0d207b0c2c7a0b7da5 | 3,618,028 |
def TStrHashF_OldGLib_GetSecHashCd(*args):
"""
GetSecHashCd(char const * p) -> int
Parameters:
p: char const *
TStrHashF_OldGLib_GetSecHashCd(TStr s) -> int
Parameters:
s: TStr const &
"""
return _snap.TStrHashF_OldGLib_GetSecHashCd(*args) | 4b3bb61237b742c2c33af5944c8b79fd721e82c2 | 3,618,029 |
def t_n_rect(discharge, strickler_roughness, inclination, width, start=1):
"""Calculates the normal depth of a rectangular channel."""
A = lambda w, h: w * h
U = lambda w, h: w + 2 * h
R = lambda w, h: A(w, h) / U(w, h)
return fsolve(
lambda h: strickler_roughness
* inclination ** ... | 9f644c6f230eca34587c78a8485b83ee37412a3d | 3,618,030 |
def validate_choice(value, choices):
"""Check that ``value`` is in ``choices``."""
choices = validate_list(choices)
if value not in choices:
raise ValidationError(
value,
INVALID_CHOICE,
{
'choices': ', '.join(map(str, choices)),
},
... | 97b56f25c581e797745ab34e33573d659a9be801 | 3,618,031 |
def tensor_power(a, n:int):
"""
kron(a, kron(a, ...))
"""
if n == 1:
return csr_matrix(a)
else:
tmp = a
for i in range(n-1):
tmp = kron(tmp, a)
return tmp | 7f12a188a00698676100c53e75661714299334cb | 3,618,032 |
import unicodedata
def _is_punctuation(char):
"""Checks whether `char` is a punctuation character."""
cp = ord(char)
# We treat all non-letter/number ASCII as punctuation.
# Characters such as "^", "$", and "`" are not in the Unicode
# Punctuation class but we treat them as punctuation anyways, fo... | 0d380deffd9554dc398eb0eae846b12d868da273 | 3,618,033 |
from typing import List
from typing import cast
def validate(parser:Parser):
"""
Validate the program's tokens against the grammar tree, and then return the
abstract syntax tree.
"""
def error_handler(hint:str, token:Token, ErrorType=GrammarError):
message = parser.message(hint, *token.po... | 3f9ec203dba4bafd3d69c23c85d4cc98d8a2468b | 3,618,034 |
import operator
def get_chart_data(physical_events, spell_events, timestamps):
"""Compiles data for the DPS chart"""
total_dps = {}
total_dps = aggregate_dps(spell_events, aggregate_dps(physical_events, total_dps))
# for ts in timestamps:
# if ts not in total_dps.keys():
# total_d... | e7bb45420e128da4eec4254af13675227022d07b | 3,618,035 |
import torch
def knn_indices_func_cpu(rep_pts : FloatTensor, # (N, pts, dim)
pts : FloatTensor, # (N, x, dim)
K : int, D : int
) -> LongTensor: # (N, pts, K)
"""
EXAMPLE FUNCTION. Imports not included for this.
CPU-ba... | 07c620ed5175b9e9996e32bf8848d686fcbe641e | 3,618,036 |
def detect_language(html) :
"""
Detect the language of the text content of a page.
"""
h = html2text.HTML2Text()
return langdetect.detect(h.handle(html)) | df6f4b8fdcadf06aaadfb6f9092cdca92de06f7c | 3,618,037 |
def calc_P_ref_evp(Theta_ref_evp):
"""蒸発圧力 (12)
Args:
Theta_ref_evp(float): ヒートポンプサイクルの蒸発温度 (℃)
Returns:
float: 蒸発圧力 (MPa)
"""
return get_f_p_sgas(Theta=Theta_ref_evp) | be3de36271f994ccd5fe9150aa41b5d3a1dd68d4 | 3,618,038 |
import PIL
def red_filter(
img: PIL.Image.Image, red_thresh: int, green_thresh: int, blue_thresh: int
) -> np.ndarray:
"""Mask reddish colors in an RGB image.
Create a mask to filter out reddish colors, where the mask is based on a pixel
being above a red channel threshold value, below a green channe... | a6733ddc6bb0fcca3fd62ba750e1e4690e68a0f5 | 3,618,039 |
def reorder(operator, order_function, num_modes=None, reverse=False):
"""Changes the fermionic order of the Hamiltonian based on the provided
order_function per mode index
Args:
operator (SymbolicOperator): the operator that will be reordered. must
be a SymbolicOperator or any type of o... | e0cb7a39d1b08093d44b8e958dc9ffd78733995f | 3,618,040 |
from typing import Any
def create_item(
*,
item_in: schemas.ItemCreate,
) -> Any:
"""
Create new item.
"""
next_item_id = items[-1].id + 1 # pylint: disable=no-member
item = schemas.Item(
id=next_item_id,
title=item_in.title,
description=item_in.description,
... | 2b4cfc33a6771b119318df6555f2852789e26dd4 | 3,618,041 |
import pickle
def get_worker_from_file( fileName:str ) -> Worker.Worker:
"""
Returns a Worker Object
from the given fileName
"""
if not exists(fileName):
print("The FileName given does not exist")
return None
with open( fileName+".pkl", "rb") as file:
return pickle.load... | 31af9fbfaf571c66f20c6e96bc0746f741f0122e | 3,618,042 |
import logging
def NeedANewWaterfallTryJob(master_name,
builder_name,
build_number,
force_try_job,
build_completed=True):
"""Preliminary check if a new try job is needed.
Don't need try job if build no... | 6acc753ae066c9fc685e0c4c891284fe4ab99501 | 3,618,043 |
from typing import Dict
def build_tree_recursive(node: PropertyNode,
max_level,
cpvs: Dict[str, str] = {}):
""" Build a property node and its children recusively
until the maximum level."""
result = node.json_blob() # build the property node blobs
... | 86a85c3a92b8b70d9b0f34b45b3bf17863396485 | 3,618,044 |
def load_metrics():
"""
Load metrics from [hosts] section of RC file
"""
global config
if 'hosts' in config:
mets = config.hosts
else:
mets = {}
mets2 = {}
for tm in mets:
try:
mets2[tm.replace('.', '_')] = int(mets[tm])
except:
log... | ed3287a06331ceecc36569d55cd149df03243012 | 3,618,045 |
def handler_get_user_created_events_from_id(userID):
"""Get the events created by the user with the given ID.
.. :quickref: Users; Get the events created by the user with the given ID.
:param int userID: The ID of the user to retrieve the collection from
:status 200: The list was correctly retriev... | fa0e98ed13035e99f267626b5e5454a0250ed1d4 | 3,618,046 |
def convert_lookups(**query):
"""
Transform a query from Django-style format to Datasore format.
:return: An iterable of filters suitable to pass to :meth:`~gcloudoem.datastore.query.Query.add_filter`.
"""
filters = []
for key, value in sorted(query.items()):
parts = key.rsplit(LOOKUP_S... | 36e7d091894424c7f2521cbd0dae925b6c76b7cd | 3,618,047 |
def get_tourn_golfer_id(tourn_golfers_list, tourn_id, golfer_id):
"""
Helper function to get the tourn_golfer_id
based on the specified tourn_id and golfer_id
"""
for tourn_golfer in tourn_golfers_list:
if tourn_golfer.get_golfer_id() == golfer_id:
if tourn_golfer.get_tourn_id()... | ead84142f91289a8786aa57da6c64cc512309ff8 | 3,618,048 |
def get_jti(encoded_token):
"""
Returns the JTI given the JWT encoded token
:param encoded_token: The encoded JWT string
:return: The JTI of the token
"""
return decode_jwt(encoded_token, config.secret_key, config.algorithm, config.csrf_protect).get('jti') | 647a93077b570ce201c6ebb09e4f27cfd9dc87ac | 3,618,049 |
import re
def verify_raw_google_hash_header(google_hash: str) -> bool:
"""Verify the format of the raw value of the "x-goog-hash" header.
Note: For now this method is used for tests only.
:param str google_hash: the raw value of the "x-goog-hash" header
:rtype: bool
"""
return bool(re.match... | 187c903c23e0c860e983b2e9b70890a36823c63f | 3,618,050 |
def compare_ssdeep(payload1, payload2):
"""
Compare binary payloads with ssdeep to determine
:param bytes payload1: Binary content to compare
:param bytes payload2: Binary content to compare
:returns: Match score from 0 (no match) to 100
:type: int or None
"""
payload1_hash = get_ssd... | b167abf3fd1ccd8252430ca6d927fb19bcbceed2 | 3,618,051 |
import typing
import os
import socket
def _get_workstation() -> typing.Optional[str]:
"""Get the current workstation name.
This gets the current workstation name that respects `NETBIOS_COMPUTER_NAME`. The env var is used by the library
that gss-ntlmssp calls and makes sure that this Python implementation... | 29aabfb7f3d7be7a07ce3a66847e30817e959513 | 3,618,052 |
def stack_operations():
"""Solution to exercise R-6.1.
What values are returned during the following series of stack operations,
if executed upon an initially empty stack? push(5), push(3), pop(),
push(2), push(8), pop(), pop(), push(9), push(1), pop(), push(7), push(6),
pop(), pop(), push(4), pop(... | d3acdcdd38cf86cf2d94a9c35dec9994a649ef4e | 3,618,053 |
def configuration_to_safe_dict(method):
"""
This wrapper function calls the method with the configuration converted from a regular dict into a SafeDict
"""
@wraps(method)
def method_wrapper(self, project_and_group, configuration, dry_run):
return method(self, project_and_group, SafeDict(con... | 64660166d15e1748fda992bf1c8cec9a49d0c9a2 | 3,618,054 |
def get_initial_arg(pk):
"""
Builds the initial arg string for rerunning from wells
"""
if int(pk) != 0:
try:
report = models.Results.objects.get(pk=pk)
ret = report.get_report_dir()
return ret
except models.Results.DoesNotExist:
return ""
... | a480a48434150a3f0d5090d43f683339f130388b | 3,618,055 |
import hashlib
def get_SHA1(variant_rec):
"""Calculate the SHA1 digest from the ref, study, contig, start, ref, and alt attributes of the variant"""
h = hashlib.sha1()
keys = ['seq', 'study', 'contig', 'start', 'ref', 'alt']
h.update('_'.join([str(variant_rec[key]) for key in keys]).encode())
retu... | 45e1aca002dc2ae972ee0e61c11441c11714c793 | 3,618,056 |
def get_labels(data, centroids):
"""
Find nearest centroid to each data point. Returns ndarray of shape (n, d)
containing labels (nearest centroid) of each data point.
"""
# i-th row of the distances matrix represents distances from each data
# point to the i-th centroid.
distances = np.emp... | 96af5dfcb063592960436915e8cd7447023d3c38 | 3,618,057 |
def compare_metadata(context, metadata):
"""Compare a database schema to that given in a
:class:`~sqlalchemy.schema.MetaData` instance.
The database connection is presented in the context
of a :class:`.MigrationContext` object, which
provides database connectivity as well as optional
comparison... | bd905c9724a05107e841e9195a8b61be56535e6b | 3,618,058 |
def parse_address_or_network(value):
"""
Parse value as IPAddress or Network
"""
if isinstance(value, (IPAddress, Network)):
return value
try:
return IPAddress(value)
except (ValueError, AddrFormatError):
pass
try:
return Network(value)
except AddrFormatEr... | 3988f634a75bb05a3e34ae59db40bcd47d29664b | 3,618,059 |
def render_flag_completion_func(command_dict: dict, name: str) -> (str, str):
"""Renders function for flag completion of command and its subcommands."""
subcommands = get_subcommands(command_dict)
options = get_options(command_dict)
func_name = "__unikube_complete_flags_{name}".format(name=name)
i... | 28f3dacc5c1aa8f6aa73c26f44eff86aea05d8bd | 3,618,060 |
def compare_output(prev_solrrec, solrrec, chromo):
"""
process solr_compare_previous_year fields and return solrrec with
extra sum and change fields added
"""
out = dict(solrrec)
for f in chromo['fields']:
comp = f.get('solr_compare_previous_year')
if not comp:
conti... | 360890e51a10bcaa92d708bdf3e4fde76439a156 | 3,618,061 |
def build_docs():
""" Builds up a complete chunk-match structure, with a depth of 2 in both directions recursively. """
docs = []
for base_id in range(DOCUMENTS_PER_LEVEL):
d = jina_pb2.Document()
d.granularity = 0
d.adjacency = 0
d.id = base_id
docs.append(d)
... | da3a11ddf61a404a6170f2a9f8c6ae9bb27b43e2 | 3,618,062 |
import api.impl
def fetch(critic, token_id):
"""Fetch an AccessToken object with the given token id"""
assert isinstance(critic, api.critic.Critic)
return api.impl.accesstoken.fetch(critic, int(token_id)) | 57fafab8c03602d700aad6aaa56ca6325351c21d | 3,618,063 |
def verify_checksum(message, previous_csum=0):
"""Verify checksum for incoming message.
:param message: incoming message
:param previous_csum: accumulated checksum value
:return return True if message checksum type is None
or checksum is correct
"""
if message.message_type in CHECKSUM_MSG_... | eca4b2f2ee4a4d8623110798b55787ef8cca3e84 | 3,618,064 |
def group_required(*group_names):
"""
Requires user membership in at least one of the groups passed in.
"""
def wrap(view):
def wrapped_view(request, *args, **kwargs):
user = request.user
if user.is_authenticated:
check_groups = bool(user.groups.filter(nam... | 242076eedbf2c4a6519f819e878f868bec0551a5 | 3,618,065 |
from skyfield.positionlib import Angle
from skyfield.api import Star
def cirs_radec(body, date=None, deg=False, obs=chime):
"""Converts a Skyfield body in CIRS coordinates at a given epoch to
ICRS coordinates observed from CHIME
Parameters
----------
body : skyfield.api.Star
Skyfield Star... | 8cc0b870bdbafbea6149b8f378ffc09f315243eb | 3,618,066 |
def reconcile_S1(T):
"""
Prune the Fitch-Hartigan S1 arrays across T to respect only solutions that are guaranteed to
be sub-optimal in the subtree below any internal node and legal with respect to its parent's
set of potential states.
"""
source = [n for n in T if T.in_degree(n) == 0][0]
... | 12e646470d75f8a1c5c24d1acb36030fa691e70b | 3,618,067 |
import os
import json
def find_pgomgr(chrome_checkout_dir):
"""Find pgomgr.exe."""
win_toolchain_json_file = os.path.join(chrome_checkout_dir, 'build',
'win_toolchain.json')
if not os.path.exists(win_toolchain_json_file):
raise Exception('The toolchain JSON file is missing.')
with open(win_toolchain... | 618a23726fb5b02eaa7be2fbf4597dce3e1acd29 | 3,618,068 |
def state_filestub(st, is2005=False):
"""Given a 2-char abbreviation, return the state filestub (directory).
The Census standard is the full state name, camel case, spaces
removed. This generally is true for "United States" too, but in 2005
they put a "0" in front of the name, to make sure it's sorted ... | 3a7889062aeee89a4fc4d0137a1bb6ea03bd6805 | 3,618,069 |
def parse_experiments(data, symbols):
"""
For the experiment in the data structure that has data recorded in a table column,
the data type string and the list of table values is returned
Returns
-------
tuple
2 tuple of a list of data types/units and the list of elements each output cor... | 77bfb88db0112f569e7d557b111f15f111a0b75d | 3,618,070 |
def generate_urls(row):
"""Generate list of URLS from a given row"""
urls = []
for k in keys_url:
url = row.get(k, "")
if url.strip() != "":
name = get_url_type(url)
urls.append({"name": name, "url": encode_base64(url)})
return urls | add9e3bc7b969b7cad4069e5ff614ce35aa86780 | 3,618,071 |
def csr_polynomial_expansion(X, interaction_only, degree):
"""Apply polynomial expansion on CSR matrix
Parameters
----------
X : sparse CSR matrix
Input array
Returns
-------
New expansed matrix
"""
assert degree in (2, 3)
interaction_only = 1 if interaction_only else ... | d851723ba4f0a79b534267b0a7b3af6dd70c589a | 3,618,072 |
from typing import Union
from typing import List
from typing import Dict
def read_genbank(
file: str,
as_dict: bool = False) -> \
Union[List[Chromosome], Dict[str, Chromosome]]:
"""
Read a genbank file into Chromosome ojbects, i.e. annotated genome
Args:
file: path-like
... | 01c95594570c466e77e7879a4d707b2e9fb691ce | 3,618,073 |
def get_docs_and_trans():
"""
:return: docs (translated and not) and translator count
:structure: dict('code': string, 'document': dict('documents': int, 'translators': int, 'translated_documents': int)
"""
client = MongoClient()
db = client.highlight
acc = db.accounts
l_s = db.files_inf... | 5c0fae144cad73d1eb93e4195f1d50fe9d7f3503 | 3,618,074 |
from .model_store import get_model_file
import os
def get_hrnet(version,
model_name=None,
pretrained=False,
root=os.path.join("~", ".tensorflow", "models"),
**kwargs):
"""
Create HRNet model with specific parameters.
Parameters:
----------
v... | 91a6344616c95b6d2255450dcb1e0a68cd824111 | 3,618,075 |
def http_exception_error_handler(
exception):
"""
Handle HTTP exception
:param werkzeug.exceptions.HTTPException exception: Raised exception
A response is returned, as formatted by the :py:func:`response` function.
"""
assert issubclass(type(exception), HTTPException), type(exception)... | e26963d55700ebd24a3481c3232efc6ba1188b81 | 3,618,076 |
def reverse_list(head):
"""Fantasic code!"""
new_head = None # ptr on previous item
while head:
head.next, head, new_head = new_head, head.next, head # look Ma, no temp vars!
return new_head | a9a09f30083549aeaeaa4750f66efaf869fce44d | 3,618,077 |
def namespacesFromSelection():
"""this is get namespace string from current selectionList.
"""
namespaces = ['']
try:
namespaces = a
except NameError as error:
pm.warning('occured nameError. skip get namespace.')
namespaces = ['']
return namespaces | d58988fa664f8be887d256fad6b8f3902364ba59 | 3,618,078 |
from typing import Dict
def build_db_changes(change: TasksChange, current_tasks: Dict[str, DbTask]) -> DbTasksChange:
"""Evaluate all changes that must be performed on task to apply the requested changes"""
deleted_tasks_ids = (
{task_id for task_id in current_tasks.keys() if is_task_in_dag(task_id, c... | aa70d72feef5d954090d499c8f66efcc775924d8 | 3,618,079 |
import scipy
def eigprincomp(x, npcs=None, norm=False, weights=None):
"""Does principal components analysis on [x].
Returns coefficients (eigenvectors) and eigenvalues.
If given, only the [npcs] greatest eigenvectors/values will be returned.
If given, the covariance matrix will be computed using [weig... | c5c6ddecdadcd1766a9c86299d6201d9d39abc93 | 3,618,080 |
def nco_ocp_Ecker2015_function(sto):
"""
NCO OCP as a function of stochiometry [1, 2, 3].
References
----------
.. [1] Ecker, Madeleine, et al. "Parameterization of a physico-chemical model of
a lithium-ion battery i. determination of parameters." Journal of the
Electrochemical Society 162.... | 13043b6a9d48a63f0e740a62de948771b1269671 | 3,618,081 |
def calc_coord_distances(locations):
"""Calculate distances of all locations(latitude longitude).
Expects flat list, not pairs of points"""
n = len(locations)
coord_distances = np.empty((n, n))
for i in range(n - 1):
coord_distances[i, i] = 0.0
for j in range(i + 1, n):
d... | 4e8bd415772b216e40333c7a304d4d70be6aff65 | 3,618,082 |
import os
import urllib
def download_wallpaper(url, picture_dir, filename):
"""
Downloads URL passed, saves in specified location, cleans filename.
"""
filename = filename + "." + url.split(".")[-1]
outpath = os.path.join(picture_dir, filename)
try:
f = urllib.request.urlopen(url)
... | 258218947c7ae97d5831ee2bd74439ffd79fdf7b | 3,618,083 |
def game(game_id):
"""Details of a specific game."""
with session_scope() as session:
game = session.query(Game, Image, System, Company, User).filter(
Game.image_id == Image.id).filter(
Game.system_id == System.id).filter(
Game.publisher_id == Company.id).... | 519c4e9996028ffd4b6263ee77458342395d91db | 3,618,084 |
def mult_vector(vector, coeff):
""" multiplies a 2D vector by a coefficient """
return [coeff * element for element in vector] | 4f404b23ef4f11b162b352735275498811cc6821 | 3,618,085 |
def ratio_dananwpp2_at_houchiweir():
"""
Real Name: Ratio DaNanWPP2 At HouChiWeir
Original Eqn: Allocation DaNan WPP2/Total WPP Allocation At HouChiWeir
Units: m3/m3
Limits: (None, None)
Type: component
Subs: None
"""
return allocation_danan_wpp2() / total_wpp_allocation_at_houchiw... | 2ec9a29e53d6f31afaa394c9108445e967d2e1c7 | 3,618,086 |
def clean_data(self):
"""Make all the data arrays the same length, in case the log file
did not finish a full time step (e.g. you killed the job early or are
monitoring a job in progess. Furthermore, delete redundant time steps
corresponding to when MMUT restarts"""
def get_length(data):
... | 3a39d00804972bfe39d60732df7693ee504a0b1e | 3,618,087 |
def compute_beta_zero_node(alpha):
"""Compute beta values for ZERO node.
https://arxiv.org/pdf/1510.06495.pdf Section III.C.
"""
return np.ones(alpha.size, dtype=np.double) * INFINITY | a70c7109331470c8639e4b49504fa33f94b55cdd | 3,618,088 |
def get_ann_info(self, image_id=None, ann_id=None):
""" Retrieves the annotation informations given an image id or annotation id
if image_id provided, returns a list of annotation infos
if ann_id provided, returns a single annotation info
"""
if image_id is not None:
return deepcopy([self.a... | 2bc1afcb58332d7ce84fc13954b8910224a72d28 | 3,618,089 |
def _is_any_geom_pass_contype_conaffinity_check(model: mujoco.wrapper.MjModel,
body1_id: int, body2_id: int):
"""Returns true if any geom pair passes the contype/conaff check."""
body1_geomadr = model.body_geomadr[body1_id]
body2_geomadr = model.body_geomadr[body2_i... | 50cf63d42ff13d2892d61a56d8d1c019dc2891e5 | 3,618,090 |
def sample_sphere(n=100, center=(0, 0, 0), minr=0, maxr=1, mintheta=0, maxtheta=2*np.pi, minphi=0, maxphi=1):
"""Function to Sample points Between Two concentric Spheres using Inverse Transform Samples
Reference: https://github.com/girishdhegde/random.fun/tree/master/sampling
http://corysim... | 2aea223487a22eb5a76bb00964096efa6c48ff43 | 3,618,091 |
def extract_non_constant_subtree(expr, variables):
"""
Extract a non-constant sub-tree from an equation.
"""
last = expr
while True:
last = expr
# expr = remove_root_constant_terms(expr, variables, 'add')
expr = remove_root_constant_terms(expr, variables, "mul")
# exp... | 8f60b9c281231bcd0439f31b634e007cb8f36179 | 3,618,092 |
def get_date_whereclause(date_colname, startdate, enddate):
"""This is to change the date format function to use on the actual queries
sqlite and mysql use different methodnames to do their date arithmetic"""
ret = " %s > '%s' AND %s < '%s' " % (date_colname,startdate.strftime('%Y-%m-%d'),
... | f02d033f3f89eac5ac4d496d5995e87b6d9d0301 | 3,618,093 |
def map_label_colors(array, ignore_vals=[0]):
"""
Maps unique values in a mask to colors
Colors from 12-class paired
http://colorbrewer2.org/#type=qualitative&scheme=Paired&n=12
"""
colset = [(166, 206, 227),
(31, 120, 180),
(178, 223, 138),
(51, 160, 44... | e10b4d60cef26d0cb2311606ee562e1793620fc6 | 3,618,094 |
def LoadTraceFile(filename):
"""
Load a previously recorded binary trace file
@param filename: trace file
"""
return idaapi.load_trace_file(filename) | 42a99c96c4ce7f9343cf15caa8f4b73411139584 | 3,618,095 |
def makeImageAuto(inarray):
"""Combines float_uint8 and image2array operations
ie. scales a numeric array from -1:1 to 0:255 and
converts to PIL image format"""
return image2array(float_uint8(inarray)) | b23c38907375a5eaaee1b6c4664648cebca5c263 | 3,618,096 |
def get_effective_answer_words(answer_words, format_spec):
"""
If needed, modify answer_words using format spec to add padding chars
"""
if format_spec == model.ModelOutputFormat.sequence:
return answer_words + ["<stop>"]
else:
return answer_words | 99b5d30974ece35eb3437a93c5402b23015dc3ff | 3,618,097 |
import logging
def ami_copy(region):
"""
Define a fixture to manage the copy and deletion of AMI.
This AMI is used to test head node and compute node AMI update
"""
copy_ami_id = None
client = boto3.client("ec2", region_name=region)
def _copy_image(image_id, test_name):
nonlocal c... | 3398c9b5d84a6eb601fdcfbbd241351f23ec1701 | 3,618,098 |
def newton_rhapson(f, df, x0, epsilon=1e-5):
"""Găsește o soluție a funcției f cu derivata df, aplicând
metoda lui Newton, pornind din punctul x0.
"""
# Primul punct este cel primit ca parametru
prev_x = x0
# Aplicăm prima iterație
x = x0 - f(x0) / df(x0)
# Continuăm să calculăm până av... | 5cd4d3b201d5e0cfd441df494b4203b523f39171 | 3,618,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.