content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import yaml
def loadConfig(filename):
"""Load and parse .yaml configuration file
Args:
filename (str): Path to system configuration file
Returns:
dict: representing configuration information
Raises:
BdsError: if unable to get configuration information
"""
try:
... | 099d1892bf6f6798a77dcc59067afa59af770745 | 3,644,005 |
def scale_t50(t50_val = 1.0, zval = 1.0):
"""
Change a t50 value from lookback time in Gyr at a given redshift
to fraction of the age of the universe.
inputs: t50 [Gyr, lookback time], redshift
outputs: t50 [fraction of the age of the universe, cosmic time]
"""
return (1 - t50_val... | 43d7fa07a59c4b66c7db7caca3c138800ca8db4e | 3,644,006 |
def get_car_changing_properties(car):
"""
Gets cars properties that change during a trip
:param car: car info in original system JSON-dict format
:return: dict with keys mapped to common electric2go format
"""
result = {mapped_key: car.get(original_key, None)
for mapped_key, origi... | 540dbd0b6d08cc08a950946dda018c3296d8c51d | 3,644,007 |
def get_metadata(record):
"""
Calls DNZ's API to retrieve the metadata for a given record.
"""
id = record['id']
url = DNZ_URL + '{id}.json?api_key={key}'.format(id=id, key=DNZ_KEY)
try:
metadata = get(url).json()['record']
metadata['hash'] = record['hash']
except KeyError... | 522e2aed2f7d71bcf9d397036c764c90c67b6184 | 3,644,008 |
def _expand_one_dict(cfg, shared):
"""expand a piece of config
Parameters
----------
cfg : dict
Configuration
shared : dict
A dict of shared objects
Returns
-------
dict, list
Expanded configuration
"""
if shared['default_config_key'] is not None:
... | d8d00bfede1bdca504f3d643836947363d8914ac | 3,644,009 |
import six
def _api_decrypt():
"""
Return the response dictionary from the KMS decrypt API call.
"""
kms = _kms()
data_key = _cfg_data_key()
try:
return kms.decrypt(CiphertextBlob=data_key)
except botocore.exceptions.ClientError as orig_exc:
error_code = orig_exc.response.g... | b0b01e9a71dfaf594dd9526072b77f2a5c6363c1 | 3,644,010 |
def hide_panel(panel_name, base_url=DEFAULT_BASE_URL):
"""Hide a panel in the UI of Cytoscape.
Other panels will expand into the space.
Args:
panel_name (str): Name of the panel. Multiple ways of referencing panels is supported:
(WEST == control panel, control, c), (SOUTH == table panel... | 5e8ead9f8ca51d4629c4c4dbd605ad2257cfa147 | 3,644,011 |
def user_tickets(raffle_prize, user):
"""return the allocate ticket for user"""
return raffle_prize.allocated_tickets(user) | a29c578713664018f639088539f2404fc7a63171 | 3,644,012 |
def init_container(self, **kwargs):
"""Initialise a container with a dictionary of inputs
"""
for k, v in kwargs.iteritems():
try:
setattr(self, k, v)
except Exception as e:
# Deal with the array -> list issue
if isinstance(getattr(self, k), list) and isin... | 888f5fc1cfc2b7718b8712360f86b5fd51fd25d2 | 3,644,013 |
def optimize(nn_last_layer, correct_label, learning_rate, num_classes):
"""
Build the TensorFLow loss and optimizer operations.
:param nn_last_layer: TF Tensor of the last layer in the neural network
:param correct_label: TF Placeholder for the correct label image
:param learning_rate: TF Placeholde... | 0c1f50c3148a87206fff9473f2ecd78793aef630 | 3,644,014 |
def setIamPolicy(asset_id, policy):
"""Sets ACL info for an asset.
Args:
asset_id: The asset to set the ACL policy on.
policy: The new Policy to apply to the asset. This replaces
the current Policy.
Returns:
The new ACL, as an IAM Policy.
"""
return _execute_cloud_call(
_get_cloud_ap... | 2501565aee420cd3b66eaf204ecd756d51e30b4f | 3,644,015 |
def get_corners(n):
"""Returns corner numbers of layer n"""
end = end = (2*n + 1) * (2*n + 1)
return [end-m*n for m in range(0,8,2)] | 8d78135f13675d01fc2b6736b7c1fb1e7cf3e5f5 | 3,644,016 |
def plot_single_hist(histvals, edges, legend=None, **kwds):
""" Bokeh-based plotting of a single histogram with legend and tooltips.
**Parameters**\n
histvals: 1D array
Histogram counts (e.g. vertical axis).
edges: 1D array
Histogram edge values (e.g. horizontal axis).
legend: str
... | 24a91ed6e3653dde35a27bba26530f47ec11bcd2 | 3,644,017 |
import torch
def resnet50(alpha, beta,**kwargs):
"""Constructs a ResNet-50 based model.
"""
model = ResNet(Bottleneck, [3, 4, 6, 3], alpha, beta, **kwargs)
checkpoint = torch.load(model_dirs['resnet50'])
layer_name = list(checkpoint.keys())
for ln in layer_name:
if 'conv' in ln or 'downsample.0.weight' in ln:... | 165f0bfd357af96004edcc5d73224d8efcb98943 | 3,644,018 |
from datetime import datetime
def datetime_to_timestamp(dt, epoch=datetime(1970,1,1)):
"""takes a python datetime object and converts it to a Unix timestamp.
This is a non-timezone-aware function.
:param dt: datetime to convert to timestamp
:param epoch: datetime, option specification of start of ep... | 2fbd5b3d6a56bc04066f7aaa8d4bef7c87a42632 | 3,644,019 |
def connectivity_dict_builder(edge_list, as_edges=False):
"""Builds connectivity dictionary for each vertex (node) - a list
of connected nodes for each node.
Args:
edge_list (list): a list describing the connectivity
e.g. [('E7', 'N3', 'N6'), ('E2', 'N9', 'N4'), ...]
as_edges (b... | 58f24c6465fa1aaccca92df4d06662b0ce1e1e77 | 3,644,020 |
def get_confusion_matrix(*, labels, logits, batch_mask):
"""Computes the confusion matrix that is necessary for global mIoU."""
if labels.ndim == logits.ndim: # One-hot targets.
y_true = jnp.argmax(labels, axis=-1)
else:
y_true = labels
# Set excluded pixels (label -1) to zero, because the confusion ... | 664f08446ea25000c77a78b133fc749fbb919376 | 3,644,021 |
import socket
def init_socket():
"""Returns a fresh socket"""
return socket.socket() | 429d790f3007a357d4a14d57066d890f14f42178 | 3,644,022 |
def semitone_frequencies(fmin, fmax, fref=A4):
"""
Returns frequencies separated by semitones.
Parameters
----------
fmin : float
Minimum frequency [Hz].
fmax : float
Maximum frequency [Hz].
fref : float, optional
Tuning frequency of A4 [Hz].
Returns
-------... | b4a29dcb0ae53f2876d01f4a084d577219db1e47 | 3,644,023 |
from typing import Mapping
from typing import Any
from typing import Sequence
def dict_get_value(dict: Mapping, name: str) -> Any:
"""Gets data from a dictionary using a dotted accessor-string
:param dict: source dictionary
:param name: dotted value name
"""
current_data = dict
for chunk in n... | c77c4fbfd8677fc53510a1dfe565e3496d57f8ef | 3,644,024 |
def get_files_from_split(split):
""" "
Get filenames for real and fake samples
Parameters
----------
split : pandas.DataFrame
DataFrame containing filenames
"""
files_1 = split[0].astype(str).str.cat(split[1].astype(str), sep="_")
files_2 = split[1].astype(str).str.cat(split[0].... | 951c8e73952017db2d29b6b1e4944ddf832516e3 | 3,644,025 |
def dedupBiblioReferences(doc):
"""
SpecRef has checks in its database preventing multiple references from having the same URL.
Shepherd, while it doesn't have an explicit check for this,
should also generally have unique URLs.
But these aren't uniqued against each other.
So, if you explicitly b... | 4fbbb6eb85b1136c5addc5421ff9be083cc3429d | 3,644,026 |
def check_percent(mask_arr, row, col, sz, percent):
"""
:param mask_arr: mask数组
:param row:
:param col:
:param sz:
:param percent: 有效百分比
:return:
"""
upper_bound = mask_arr.max()
area = np.sum(mask_arr[row:row + sz, col:col + sz]) / upper_bound
if area / (sz ** 2) > percent:... | 0d84e511d6895145dc4a7f8f150ae907a4884f90 | 3,644,027 |
def find_center_pc(proj1, proj2, tol=0.5, rotc_guess=None):
"""
Find rotation axis location by finding the offset between the first
projection and a mirrored projection 180 degrees apart using
phase correlation in Fourier space.
The ``register_translation`` function uses cross-correlation in Fourier... | 4bc9a25bb6bd041d9d5cb8ae46bfd91dfa7c97ff | 3,644,028 |
def emce_comparison(nus, n_reps=100):
"""Simulation comparing ECME algorithm with M-estimates.
We compare the estimates obtained by the ECME algorithm against two Huber
M-estimates with tuning parameters 1 and 4.
Args:
nus, iter: Iterator of values for the degrees of freedom.
n_reps, i... | 1d79ae528d8bffb694e1718f037d880f46d8c597 | 3,644,029 |
def seconds(seconds_since_epoch: int) -> date:
"""Converts a seconds offset from epoch to a date
Args:
seconds_since_epoch (int): The second offset from epoch
Returns:
date: The date the offset represents
"""
return EPOCH + timedelta(seconds=seconds_since_epoch) | 1dd1559e3f971922bad3d618ff4db8b1e0012c42 | 3,644,031 |
def check_presence(user):
"""
Gets user presence information from Slack ("active" or "away")
:param user: The identifier of the specified user
:return: True if user is currently active, False if user is away
"""
if not settings.SLACK_TOKEN:
return None
client = WebClient(token=set... | acdeae9b80613edcfbfb05ea594260d1f99473ff | 3,644,032 |
def adjust_position_to_boundaries(positions, bounds, tolerance=DEFAULT_TOLERANCE):
"""
Function to update boid position if crossing a boundary (toroid boundary condition)
:param positions: vector of (x,y) positions
:param bounds: (xmin,xmax,ymin,ymax) boundaries
:param tolerance: optional tolerance ... | 3354a0e19d085e0e02595866deac7a035b364e58 | 3,644,034 |
def residual_mlp_layer(x_flat, intermediate_size, initializer_range=0.02, hidden_dropout_prob=0.1):
"""
:param x_flat: The attention output. It should be [batch_size*seq_length, dim]
:param intermediate_size: the hidden projection. By default this is the input_dim * 4.
in the original GPT we would retu... | 03e04c074080b54c4a8bc71a0fbef9e6e025f71f | 3,644,035 |
def _delete_project_repo(repo_name):
"""Deletes the specified repo from AWS."""
client = boto3.client('codecommit')
response = client.delete_repository(repositoryName=repo_name)
return response | 8410302fc419cbe9c13b9f73ef6af63f588ede76 | 3,644,036 |
def score_items(X, U, mu,
scoremethod='lowhigh',
missingmethod='none',
feature_weights=[]):
"""score_items(X, U, scoremethod, missingmethod, feature_weights)
Calculate the score (reconstruction error) for every item in X,
with respect to the SVD model in U and ... | 9355665670ff7b3a49d0abeacc9cfbaab8d586b1 | 3,644,037 |
def get_output_specs(output):
""" Get the OpenAPI specifications of a SED output
Args:
output (:obj:`Output`): output
Returns:
:obj:`dict` with schema `SedOutput`
"""
if isinstance(output, Report):
specs = {
'_type': 'SedReport',
'id': output.id,
... | 26617aa635fd97408e9d27e2972bcd9d7bd4340a | 3,644,038 |
def logggnfw_exact(x, x0, y0, m1, m2, alpha):
"""
exact form, inspired by gNFW potential
OverFlow warning is easily raised by somewhat
large values of m1, m2, and base
"""
base = 1. + np.exp(alpha)
x = x - x0
return np.log((base ** x) ** m1 *
(1 + base ** x) ** (m2 - m1... | f6b1c5511b2bfe337402b2342484d1b642329f00 | 3,644,039 |
def is_lepton(pdgid):
"""Does this PDG ID correspond to a lepton?"""
if _extra_bits(pdgid) > 0:
return False
if _fundamental_id(pdgid) >= 11 and _fundamental_id(pdgid) <= 18:
return True
return False | 086d7cebee19cfb7a91d4fc09417f168c53942de | 3,644,041 |
def complex_fields_container(real_field, imaginary_field, server = None):
"""Create a fields container with two fields (real and imaginary) and only one time set.
Parameters
----------
real_fields : Field
Real :class:`ansys.dpf.core.Field` entity to add to the fields container.
imaginary_fi... | f20cee35cff2d86801446faca4e60777c3fab429 | 3,644,043 |
def get_time_slots(s : pd.Series, time_interval : str = 'daily'):
"""Convert timestamps to time slots"""
if time_interval.lower() not in (
'hourly', 'daily', 'weekly', 'monthly',
'quarterly', 'yearly'):
raise ValueError
return pd.to_datetime(s)\
.dt.to_period(time_interval[0]... | f67c076fc3f946e4b41df9d6d79dac6f19634ea5 | 3,644,044 |
def build_optimising_metaclass(
builtins=None, builtin_only=False, stoplist=(), constant_fold=True,
verbose=False
):
"""Return a automatically optimising metaclass for use as __metaclass__."""
class _OptimisingMetaclass(type):
def __init__(cls, name, bases, dict):
super(_Optimis... | 678454e3c45b0f4ccbaef77427776485ddb07815 | 3,644,045 |
def get_ensembl_id(hgnc_id):
"""Return the Ensembl ID corresponding to the given HGNC ID.
Parameters
----------
hgnc_id : str
The HGNC ID to be converted. Note that the HGNC ID is a number that is
passed as a string. It is not the same as the HGNC gene symbol.
Returns
-------
... | d815259b553c022f5400b34e5ae5f9ddaff6193e | 3,644,046 |
import torch
def predict(model, dataloader):
"""Returns: numpy arrays of true labels and predicted probabilities."""
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
model.eval()
labels = []
probs = []
for batch_idx, batch in enumerate(dataloader):
... | 1e4b6e1f72127174a8bdbc693665ace8cbe8e4af | 3,644,047 |
import re
def _ProcessMemoryAccess(instruction, operands):
"""Make sure that memory access is valid and return precondition required.
(only makes sense for 64-bit instructions)
Args:
instruction: Instruction tuple
operands: list of instruction operands as strings, for example
['%eax', '(... | 922489dca706ba5c88132f9676c7b99bfc966947 | 3,644,048 |
def minimizeMeshDimensions(obj, direction, step, epsilon):
"""
Args:
obj:
direction:
step:
epsilon:
Returns:
"""
stepsum = 0
while True:
before, after = compareOrientation(obj, direction * step)
if before < after:
# bpy.ops.transform.rot... | ba1f7e2cf66e6665042307b9fe50c7728d68157d | 3,644,049 |
from importlib import import_module
def gimme_dj(mystery_val: int, secret_val: int) -> str:
"""Play that funky music."""
# If youre worried about what this is doing, and NEED TO KNOW. Check this gist:
# https://gist.github.com/SalomonSmeke/2dfef1f714851ae8c6933c71dad701ba
# its nothing evil. just an i... | e14680d5a73e3ea3a3651bbeccd8af18a07a5907 | 3,644,050 |
def pluecker_from_verts(A,B):
"""
See Hartley & Zisserman (2003) p. 70
"""
if len(A)==3:
A = A[0], A[1], A[2], 1.0
if len(B)==3:
B = B[0], B[1], B[2], 1.0
A=nx.reshape(A,(4,1))
B=nx.reshape(B,(4,1))
L = nx.dot(A,nx.transpose(B)) - nx.dot(B,nx.transpose(A))
return Lmat... | 7af9f779e1c00ffeee035bc76a8333d36e2ed5be | 3,644,051 |
def MAP_score(source_id, target_labels, prediction):
""" Function to compute the Mean Average Precision score of a given ranking.
Args:
source_id (array): Array containing the source_id of our given queries.
target_labels (array): Array containing the target labels of our query-docu... | ad279df4b28bceff52af98d6f7e71f34b564db55 | 3,644,052 |
def get_model_config(model):
"""Returns hyper-parameters for given mode"""
if model == 'maml':
return 0.1, 0.5, 5
if model == 'fomaml':
return 0.1, 0.5, 100
return 0.1, 0.1, 100 | dcdfb3c00026a172b22611ad3203a7c32d8e59d7 | 3,644,053 |
def find_longest_substring(s: str, k: int) -> str:
"""
Speed: ~O(N)
Memory: ~O(1)
:param s:
:param k:
:return:
"""
# longest substring (found)
lss = ""
# current longest substring
c_lss = ""
# current list of characters for the current longest substring
c_c = []
... | 78936d140ea1e54945c6b4dd849b38f0c5604a36 | 3,644,055 |
def _fixTool2(scModel,gopLoader):
"""
:param scModel:
:param gopLoader:
:return:
@type scModel: ImageProjectModel
"""
def replace_tool(tool):
return 'jtui' if 'MaskGenUI' in tool else tool
modifier_tools = scModel.getGraph().getDataItem('modifier_tools')
if modifier_tools ... | 3eb3bf8a47514a28c2e699a2eeefb084f9f7923b | 3,644,056 |
from io import StringIO
def mol_view(request):
"""Function to view a 2D depiction of a molecule -> as PNG"""
my_choice = request.GET['choice'].split("_")[0]
try:
mol = Chem.MolFromSmiles(str(InternalIDLink.objects.filter(internal_id=my_choice)[0].mol_id.smiles))
except IndexError:
mol ... | 91f202b34fe63c8b89e1250bb54222120410f9c2 | 3,644,057 |
def rotation_matrix_about(axis, theta):
"""Return the rotation matrix associated with counterclockwise rotation about
the given axis by theta radians.
Taken from: https://stackoverflow.com/a/6802723
"""
if np.shape(axis) != (3,):
raise ValueError("Shape of `axis` must be (3,)!")
scala... | f65fdc6e40ad7712521fbb6db662827401f82aca | 3,644,058 |
def zc_rules():
"""catch issues with zero copy streaming"""
return (
case("SSTableReader"),
rule(
capture(
r"Could not recreate or deserialize existing bloom filter, continuing with a pass-through bloom filter but this will significantly impact reads performance"
... | e4847d95b0565d5cb9213cfca9e8e3f28657041c | 3,644,059 |
import re
def name_convert_to_camel(name: str) -> str:
"""下划线转驼峰"""
contents = re.findall('_[a-z]+', name)
for content in set(contents):
name = name.replace(content, content[1:].title())
return name | 109a1035a3efa98861b6a419206823b1114268e2 | 3,644,060 |
def triangle_as_polynomial(nodes, degree):
"""Convert ``nodes`` into a SymPy polynomial array :math:`B(s, t)`.
Args:
nodes (numpy.ndarray): Nodes defining a B |eacute| zier triangle.
degree (int): The degree of the triangle. This is assumed to
correctly correspond to the number of `... | 20c0bc7021673ac375018a387926ae25bdfda2e5 | 3,644,061 |
import decimal
def as_decimal(dct):
"""Decodes the Decimal datatype."""
if '__Decimal__' in dct:
return decimal.Decimal(dct['__Decimal__'])
return dct | d25b3ff73d7559a9018666d5f2cd189e6503a268 | 3,644,062 |
def input_layer(features,
feature_columns,
weight_collections=None,
trainable=True,
cols_to_vars=None,
cols_to_output_tensors=None):
"""Returns a dense `Tensor` as input layer based on given `feature_columns`.
Generally a single exampl... | 89fda325ec1afb98a772d7238386471bf4484141 | 3,644,063 |
def log_sum_exp(x):
"""Utility function for computing log_sum_exp while determining
This will be used to determine unaveraged confidence loss across
all examples in a batch.
Args:
x (Variable(tensor)): conf_preds from conf layers
"""
log_reduce_sum = P.ReduceSum()
log = P.Log()
e... | 72a39a81fa3959e73c096732a86e843b5330e27d | 3,644,064 |
def prepareRepoCharts(url, name, auths):
"""
NOTE: currently not support git
"""
charts_info, charts_info_hash = _prepareHelmRepoPath(url, name, auths)
return charts_info, charts_info_hash | 7d2a6af1cae019020cd0921155fcdc749585d32c | 3,644,066 |
def num_ini_spaces(s):
"""Return the number of initial spaces in a string.
Note that tabs are counted as a single space. For now, we do *not* support
mixing of tabs and spaces in the user's input.
Parameters
----------
s : string
Returns
-------
n : int
"""
ini_spaces = ... | 9870aa42020b56f765f0ed74f73edda21b1786b1 | 3,644,067 |
def make_filename_template(schema, **kwargs):
"""Create codeblocks containing example filename patterns for a given
datatype.
Parameters
----------
schema : dict
The schema object, which is a dictionary with nested dictionaries and
lists stored within it.
kwargs : dict
K... | bb1d8eb776d8e248ca7fb67167594639a02c92cb | 3,644,068 |
def getLanguageLevel() -> dict:
"""
Takes the user input and returns the found documents as dictionary.
:text: String
:language: String
:return: Dictionary
"""
text: str = request.params.get('text')
language: str = request.params.get('language')
# check API Key
if str(request.pa... | 967b4244f7406c82715bdfb112cd82c652c9c68e | 3,644,070 |
import oci.exceptions
def list_networks(**kwargs):
"""Lists all networks of the given compartment
Args:
**kwargs: Additional options
Keyword Args:
public_subnet (bool): Whether only public or private subnets should be
considered
compartment_id (str): OCID of the pare... | 32a816b595d45102a393be8a548f48414509f865 | 3,644,071 |
def ed_affine_to_extended(pt):
"""Map (x, y) to (x : y : x*y : 1)."""
new_curve = EllipticCurve(pt.curve, ED_EXT_HOM_PROJ, Edwards_ExtProj_Arithm)
return new_curve((pt.x, pt.y, pt.x * pt.y, new_curve.field(1))) | ee949c7c0487fb580d79764e3f0c10d2a2080943 | 3,644,072 |
import joblib
def do_setup(experiment_folder, path_to_additional_args):
""" Setup Shell Scripts for Experiment """
additional_args = joblib.load(path_to_additional_args)
# Setup Data
logger.info("Setting Up Data")
data_args = setup_train_test_data(experiment_folder, **additional_args)
# Setu... | 9489b5abab6335de4c5909d718b5ccb3bcc0f3c7 | 3,644,074 |
import requests
def getorgadmins(apikey, orgid, suppressprint=False):
"""
Args:
apikey: User's Meraki API Key
orgid: OrganizationId for operation to be performed against
suppressprint:
Returns:
"""
__hasorgaccess(apikey, orgid)
calltype = 'Organization'
geturl = '{... | 640ca97bf7213b2b0e24190b7f1b6658c53332b6 | 3,644,075 |
def calc_recall(TP, FN):
"""
Calculate recall from TP and FN
"""
if TP + FN != 0:
recall = TP / (TP + FN)
else:
recall = 0
return recall | 8f3513e11f8adad111eee32740c271aad31fbe28 | 3,644,076 |
def lookup_last_report_execution(job_type, work_ids=None):
"""Lookup in the database when the report/job chunk last executed
This is the expected table schema from the database (id and timestamp columns
are omitted),
---------------------------------------------------
| work_id | history ... | bcc7715d416820dcc9f065b952e0a751255c9929 | 3,644,077 |
def get_course_goal_options():
"""
Returns the valid options for goal keys, mapped to their translated
strings, as defined by theCourseGoal model.
"""
return {goal_key: goal_text for goal_key, goal_text in GOAL_KEY_CHOICES} | 6f8fc2bd812a216abcff6a82107cf28bfc2fcbf4 | 3,644,078 |
def to_dataframe(y):
"""
If the input is not a dataframe, convert it to a dataframe
:param y: The target variable
:return: A dataframe
"""
if not isinstance(y, pd.DataFrame):
return pd.DataFrame(y)
return y | 1fc302b1acb264bce5778c9c2349100f799da397 | 3,644,079 |
def url_equal(first, second, ignore_scheme=False, ignore_netloc=False, ignore_path=False, ignore_params=False,
ignore_query=False, ignore_fragment=False):
"""
Compare two URLs and return True if they are equal, some parts of the URLs can be ignored
:param first: URL
:param second: URL
... | caea2185db83c5938f48e8d2de432c5e74540014 | 3,644,080 |
def test_struct(n: cython.int, x: cython.double) -> MyStruct2:
"""
>>> test_struct(389, 1.64493)
(389, 1.64493)
>>> d = test_struct.__annotations__
>>> sorted(d)
['n', 'return', 'x']
"""
assert cython.typeof(n) == 'int', cython.typeof(n)
if is_compiled:
assert cython.typeof(x... | 1bf5e97719d80c8327c44bfea66f7ef26b3f7400 | 3,644,081 |
def is_oasis_db():
""" Is this likely an OASIS database? Look at the table names to see
if we have the more specific ones.
Return "yes", "no", or "empty"
"""
expect = ['qtvariations', 'users', 'examqtemplates', 'marklog', 'qtattach',
'questions', 'guesses', 'exams', 'qtemplate... | 330da79c63afe4905c9469e54d61d5de6a8fa575 | 3,644,084 |
def make_segment(segment, discontinuity=False):
"""Create a playlist response for a segment."""
response = []
if discontinuity:
response.append("#EXT-X-DISCONTINUITY")
response.extend(["#EXTINF:10.0000,", f"./segment/{segment}.m4s"]),
return "\n".join(response) | 8419b100409934f902c751734c396bc72d8a6917 | 3,644,085 |
def seq_aggregate_with_reducer(x, y):
"""
Sequencing function that works with the dataframe created by get_normal_frame
:param x:
:param y:
:return:
"""
res = []
for i in range(0, len(x)):
res.append((x[i][0], x[i][1], get_aggregation_func_by_name(x[i][0])(x[i][2], y[i][2])))
... | 6faed81fd925656c2984e9d78df3b88e98fcb035 | 3,644,086 |
from typing import Any
def from_dicts(key: str, *dicts, default: Any = None):
"""
Returns value of key in first matchning dict.
If not matching dict, default value is returned.
Return:
Any
"""
for d in dicts:
if key in d:
return d[key]
return ... | 508febc48fd22d3a23dc0500b0aa3824c99fdbc3 | 3,644,087 |
def time_in_words(h, m):
"""Hackerrank Problem: https://www.hackerrank.com/challenges/the-time-in-words/problem
Given the time in numerals we may convert it into words, as shown below:
----------------------------------------------
| 5:00 | -> | five o' clock |
| 5:01 | -> | one m... | 85f2247f01df36ef499105a9940be63eee189100 | 3,644,088 |
def majorityElement(nums):
"""超过三分之一的数,最多不超过两个数"""
num1, num2 = -1, -1
count1, count2 = 0, 0
for i in range(len(nums)):
curNum = nums[i]
if curNum == num1:
count1 += 1
elif curNum == num2:
count2 += 1
elif count1 == 0:
num1 = curNum
... | ef71fa445c3bc16bbaf79a1ab4e9548125e71b7b | 3,644,089 |
def calcDensHeight(T,p,z):
"""
Calculate the density scale height H_rho
Parameters
----------
T: vector (float)
temperature (K)
p: vector (float) of len(T)
pressure (pa)
z: vector (float) of len(T
height (m)
Returns
-------
Hb... | c45d47d4f3dffe0e1706f979a9a6eb5028c7b775 | 3,644,090 |
import re
def extract_push_target(push_target: str):
"""
Extract push target from the url configured
Workspace is optional
"""
if not push_target:
raise ValueError("Cannot extract push-target if push-target is not set.")
match_pattern = re.compile(
r"(?P<http_scheme>https|http)... | 3fe11ac218c0cfc7c6211cfe76fd11bd248c4588 | 3,644,093 |
def dish_gain(radius, freq):
"""
Dish radar gain.
Inputs:
- radius [float]: Dish radius (m)
- freq [float]: Transmit frequency (Hz)
Outputs:
- g: Gain
"""
return 4*pi**2*radius**2/wavelen(freq)**2 | a20d963f9acc839a811aefaa942aaeaedce0689c | 3,644,095 |
def center_img(img, size=None, fill_value=255):
"""
center img in a square background
"""
h, w = img.shape[:2]
if size is None:
size = max(h, w)
shape = (size, size) + img.shape[2:]
background = np.full(shape, fill_value, np.uint8)
center_x = (size - w) // 2
center_y = (size ... | 838d6185230fbb8184925a31e0f3334dc4bda627 | 3,644,097 |
def concat_files(*files):
"""
Concat some files together. Returns out and err to keep parity with shell commands.
Args:
*files: src1, src2, ..., srcN, dst.
Returns:
out: string
err: string
"""
out = ''
err = ''
dst_name = files[-1]
sources = [files[f] for f ... | 101c37e5b3955c153c8c2210e7575a62341c768a | 3,644,098 |
def getElementTypeToolTip(t):
"""Wrapper to prevent loading qtgui when this module is imported"""
if t == PoolControllerView.ControllerModule:
return "Controller module"
elif t == PoolControllerView.ControllerClass:
return "Controller class" | 6862b10bc940daec1c13ef97fafbf525c2683e9e | 3,644,102 |
def parse_dates(array):
"""Parse the valid dates in an array of strings.
"""
parsed_dates = []
for elem in array:
elem = parse_date(elem)
if elem is not None:
parsed_dates.append(elem)
return parsed_dates | 1ec89f084cdd68709a37ea05356ceeb1a21f98bd | 3,644,103 |
def app_factory(global_config, **local_config):
"""
定义一个 app 的 factory 方法,以便在运行时绑定具体的 app,而不是在配置文件中就绑定。
:param global_config:
:param local_config:
:return:
"""
return MyApp() | c4c29963f88253c272319bc2369d4801df284fbf | 3,644,104 |
import pytz
def str_to_datetime(dt_str):
""" Converts a string to a UTC datetime object.
@rtype: datetime
"""
try:
return dt.datetime.strptime(
dt_str, DATE_STR_FORMAT).replace(tzinfo=pytz.utc)
except ValueError: # If dt_str did not match our format
return None | a9ac073c11b13dca011cca46860080cdc638dcbe | 3,644,105 |
def quantize(img):
"""Quantize the output of model.
:param img: the input image
:type img: ndarray
:return: the image after quantize
:rtype: ndarray
"""
pixel_range = 255
return img.mul(pixel_range).clamp(0, 255).round().div(pixel_range) | 49abd32d8b2cf54c955e16765602bbff77a2a1b9 | 3,644,106 |
def is_normalized(M, x, eps):
"""Return True if (a Fuchsian) matrix M is normalized, that
is all the eigenvalues of it's residues in x lie in [-1/2, 1/2)
range (in limit eps->0). Return False otherwise.
Examples:
>>> x, e = var("x epsilon")
>>> is_normalized(matrix([[(1+e)/3/x, 0], [0, e/x]]), ... | 01715cd58cad25a805ffd260b78641701483ad86 | 3,644,107 |
def _get_dashboard_link(course_key):
""" Construct a URL to the external analytics dashboard """
analytics_dashboard_url = f'{settings.ANALYTICS_DASHBOARD_URL}/courses/{str(course_key)}'
link = HTML("<a href=\"{0}\" rel=\"noopener\" target=\"_blank\">{1}</a>").format(
analytics_dashboard_url, settin... | fa9fb656ff4e7cf70c3512755351a46302cec71b | 3,644,108 |
def figure1_control(data1, cols):
""" Creates a data set to plot figure 1, Panel B, D, F.
Args:
- data1 (pd.DataFrame): the original data set
- cols (list): a list of column names ["agus", "bct", "bcg"]
Returns:
- df_fig1_contr (pd.DataFrame): a data set for plotting panels with co... | 5eef05c567159a623fdaaafa5a5707c48c7fe7fa | 3,644,109 |
import ctypes
def GetEffectiveRightsFromAclW(acl, sid):
"""
Takes a SID instead of a trustee!
"""
_GetEffectiveRightsFromAclW = windll.advapi32.GetEffectiveRightsFromAclW
_GetEffectiveRightsFromAclW.argtypes = [PVOID, PTRUSTEE_W, PDWORD] #[HANDLE, SE_OBJECT_TYPE, DWORD, PSID, PSID, PACL, PACL, PSECURITY_DESCRIPT... | 3edb0080a98a7d9d0d040914435c76cd20f30e0a | 3,644,110 |
def store(mnemonic, opcode):
""" Create a store instruction """
ra = Operand("ra", Or1kRegister, read=True)
rb = Operand("rb", Or1kRegister, read=True)
imm = Operand("imm", int)
syntax = Syntax(["l", ".", mnemonic, " ", imm, "(", ra, ")", ",", " ", rb])
patterns = {"opcode": opcode, "ra": ra, "r... | c9d1d7376b5c73eed87b5c3a7438cc54ecab9ad2 | 3,644,111 |
import ctypes
def hlmlDeviceGetPowerUsage(device: hlml_t.HLML_DEVICE.TYPE) -> int:
""" Retrieves power usage for the device in mW
Parameters:
device (HLML_DEVICE.TYPE) - The handle for a habana device.
Returns:
power (int) - The given device's power usage in mW.
"""
... | ed2d64be06a8e319221b2c3e2017f07a6c16a028 | 3,644,112 |
def usgs_coef_parse(**kwargs):
"""
Combine, parse, and format the provided dataframes
:param kwargs: potential arguments include:
dataframe_list: list of dataframes to concat and format
args: dictionary, used to run flowbyactivity.py ('year' and 'source')
:return: d... | 9cfa29cc5390717fd4a36360dcdb373614ae7345 | 3,644,113 |
def success_poly_overlap(gt_poly, res_poly, n_frame):
"""
:param gt_poly: [Nx8]
:param result_bb:
:param n_frame:
:return:
"""
thresholds_overlap = np.arange(0, 1.05, 0.05)
success = np.zeros(len(thresholds_overlap))
iou_list = []
for i in range(gt_poly.shape[0]):
iou ... | 3de9e308fd8a29fb7e7ed4a7132ce5157b5794eb | 3,644,114 |
import io
def my_get_size_png(gg, height, width, dpi, limitsize):
"""
Get actual size of ggplot image saved (with bbox_inches="tight")
"""
buf = io.BytesIO()
gg.save(buf, format= "png", height = height, width = width,
dpi=dpi, units = "in", limitsize = limitsize,verbose=False,
... | fe6417f35480048b70f25bfab97978515fd7d7d1 | 3,644,115 |
def getRnnGenerator(vocab_size,hidden_dim,input_dim=512):
"""
"Apply" the RNN to the input x
For initializing the network, the vocab size needs to be known
Default of the hidden layer is set tot 512 like Karpathy
"""
generator = SequenceGenerator(
Readout(readout_dim = vocab_size,
... | b1c033da42a0079e8c539fd908b715b8e6cb076f | 3,644,116 |
def first_true(iterable, default=False, pred=None):
"""Returns the first true value in the iterable.
If no true value is found, returns *default*
If *pred* is not None, returns the first item
for which pred(item) is true.
"""
# first_true([a,b,c], x) --> a or b or c or x
# first_true([a,b... | 66c6b3e282cfdf60819d5df2d48cdea31484a4f1 | 3,644,117 |
def get_device_serial_no(instanceId, gwMgmtIp, fwApiKey):
"""
Retrieve the serial number from the FW.
@param gwMgmtIP: The IP address of the FW
@type: ```str```
@param fwApiKey: Api key of the FW
@type: ```str```
@return The serial number of the FW
@rtype: ```str```
"""
serial... | e13d90da032f4084b2c1cafcf4d3a77b189a5d58 | 3,644,120 |
from typing import Optional
import torch
def multilabel_cross_entropy(
x: Tensor,
target: Tensor,
weight: Optional[Tensor] = None,
ignore_index: int = -100,
reduction: str = 'mean'
) -> Tensor:
"""Implements the cross entropy loss for multi-label targets
Args:
x (torch.Tensor[N, K... | 12f1bdb41955fc6ba05b125956cdef40e42ca94c | 3,644,121 |
def dataset_string(dataset):
"""Generate string from dataset"""
data = dataset_data(dataset)
try:
# single value
return fn.VALUE_FORMAT % data
except TypeError:
# array
if dataset.size > 1:
return fn.data_string(data)
# probably a string
return fn.shor... | 25d82bc87ae83599857a6b8d83b671d25339df9f | 3,644,122 |
from typing import Type
from typing import Callable
def create_constant_value_validator(
constant_cls: Type, is_required: bool
) -> Callable[[str], bool]:
"""
Create a validator func that validates a value is one of the valid values.
Parameters
----------
constant_cls: Type
The consta... | d225c4a225a4e24c809ef8cc6d557cf989375542 | 3,644,123 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.