content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def download_image(url):
"""Downloads ipg, jpeg fils from given URL"""
response = request.urlopen(url)
return ContentFile(response.read()) | 6a96efe321dcbd84134400dce34de5484d7aa53f | 3,613,900 |
from typing import Tuple
def _evaluate(dataset: tf.data.Dataset, model: tf.keras.Model,
loss_fn: tf.keras.losses.Loss) -> Tuple[float, float]:
"""Evaluates the given model for the whole dataset once."""
loss_sum = 0
correct_item_count = 0
item_count = 0
for (x, y) in dataset:
... | ba950cea2b5bee509d0b4392f762bbb0f9a3ab1f | 3,613,901 |
def tab(column) -> str:
"""Emulates the TAB command in BASIC. Returns a string with ASCII
codes for setting the cursor to the specified column."""
return f"\r\33[{column}C" | d57e0d6840c9f446b2832bbe725bc986aaabf13e | 3,613,902 |
def _make_laplace_numba_2d(grid: CartesianGrid) -> OperatorType:
"""make a 2d laplace operator using numba compilation
Args:
grid (:class:`~pde.grids.cartesian.CartesianGrid`):
The grid for which the operator is created
Returns:
A function that can be applied to an array of val... | 5e34b9fadcd9a8f8304409f00e744e49645cc89a | 3,613,903 |
def preview(slug):
"""Show the preview of a newly created or edited post.
Parameters
----------
slug : str
The slug is the part of the URL which identifies a particular post
on our blog in an easy to read form.
"""
post = session['post']
# When I put the post object for the ... | d2116c426ec7bf657e5fb596cbb257c690f411b4 | 3,613,904 |
def get_longest_streak_of_all_habits(session):
"""
:return: the value of the largest value in the streak column.
"""
try:
longest_streak_for_all_habits = (max(session.query(HabitHistory.streak)
.all()))
except ValueError:
raise NoHabitsInHisto... | 3be2a0b2e458663e90a810c49cd41f3fda6a98ad | 3,613,905 |
import sys
def nonbond_pairs(pos, rcut_half, neigh_list, nonBondExcls,
rcut_ovlp,
znums=None):
"""
"""
unitcell_min = pos.min(axis=0)
unitcell_max = pos.max(axis=0)
box = unitcell_max - unitcell_min + 1.0
# Cell Linked List
ndim = np.array(box//rcut_ha... | ac3ed7cbe5889e6095cb6cc55f7d773b50e59350 | 3,613,906 |
import tokenize
def eye(N, chunks="auto", M=None, k=0, dtype=float):
"""
Return a 2-D Array with ones on the diagonal and zeros elsewhere.
Parameters
----------
N : int
Number of rows in the output.
chunks : int, str
How to chunk the array. Must be one of the following forms:
... | 0882c19f3abd5d9c6936fb704664b129c2b16d0e | 3,613,907 |
def calc_num_walls(side_length, room_positions, ap_positions):
"""
Calculate the number of walls between each room to each AP.
This is used to calculated the wall losses as well as the indoor
pathloss.
Parameters
----------
side_length : float
The side length of the square room.
... | cc1fc51189e614b353810b2f76421aa6951fa84e | 3,613,908 |
import codecs
import os
import ast
def get_version():
"""
Get version without importing from elasticapm. This avoids any side effects
from importing while installing and/or building the module
Once Python 3.8 is the lowest supported version, we could consider hardcoding
the version in setup.cfg i... | c0ed312698377e705cfb547c39b69f1858fc490d | 3,613,909 |
import binascii
def x(h):
"""Convert a hex string to bytes"""
return binascii.unhexlify(h.encode('utf8')) | 0cbba146b22419f9e67f0a2ea46851a47826d4f8 | 3,613,910 |
def get_new_goal(current_pos, current_dest, home_pos, rally_point, batt_level,
blocking_time=10, speed=5, energy_consumption=1):
"""
Function for deciding the new goal
All the input coordinates are in the format [LAT, LON] (deg).
returns a [int, int] list with [X, Y] coordinates of n... | da8a22da63d518935a1d1cd2b9aa9515abc301e5 | 3,613,911 |
def is_cuda_consistent(*args):
"""
See if the cuda states are consistent among variables (of type either
tensors or torch.autograd.Variable). For example,
import torch
from torch.autograd import Variable
import torch.nn as nn
net = nn.Linear(512, 10)
tensor = torch.... | 6554bd61956ae08080cf3d4564387cddc7ad0cb7 | 3,613,912 |
import sys
def get_policy_arn(
iam: boto3.client,
rights_msg: str,
prefix: str = '/cluster.dev/',
policy_name: str = 'cluster.dev-policy',
) -> str:
"""Get policy ARN if exist.
Required "iam:ListPolicies".
Args:
iam: (boto3.client.IAM) A low-level client representing AWS IAM.
... | 376040996a7fb6ab057d3dbe4e9930ed2b2f1fd8 | 3,613,913 |
def create_nginx_config(server, port):
"""Create NGINX config in sites-enabled directory"""
if config_count() >= config_limit:
abort(400)
ip = request.remote_addr
nginx_config = nginx_sites_enabled + '/' + server
temp = sys.stdout
sys.stdout = open(nginx_config, 'w')
print template... | b998c0dcd27f8578da76ba6fa24cd11c4ed76940 | 3,613,914 |
def elbo_batch_loss(model, X, y, inds, samples):
"""Compute an estimate of the negative ELBO loss from a single batch.
Args:
X ([N, input_dim] numpy array): Train inputs.
y ([N, output_dim] numpy array): Train outputs.
inds ([batch_size] torch tensor): Indices for the batch.
samp... | 8fc4fa1447607ab7d2190d226df606637b6d98e5 | 3,613,915 |
def calculate_similarity_bert(entity_1: str, entity_2: str) -> float:
"""
@param entity_1:
@param entity_2:
@return: similarity between two entities (in the sense of whether they refer to the same thing
TODO make this better than just embeddings?
"""
embedded_1 = embed_concept_sentence(enti... | e7ed47fd0e942bc6986e8cd9466d8c68b5058dbf | 3,613,916 |
def to_epoch(str_time):
"""Take in string time(yyyy-mm-dd) and convert to epoch time."""
return int(dt.datetime.strptime(str_time, "%Y-%m-%d").timestamp()) | c085f379399ad7257cf2a1d190ff3360bccda821 | 3,613,917 |
def _rpn_loss_regr(y_true, y_pred):
"""
smooth L1 loss
y_ture [1][HXWX10][3] (class,regr)
y_pred [1][HXWX10][2] (reger)
"""
sigma = 9.0
cls = y_true[0, :, 0]
regr = y_true[0, :, 1:3]
regr_keep = tf.where(K.equal(cls, 1))[:, 0]
regr_true = tf.gather(regr, regr_keep)
regr_pr... | 52cdfc439af2a91a3d638bff5ba46925c90c2063 | 3,613,918 |
def create_markdown_file_from_filename(markdown_filename:str) -> SuccessErrors:
"""Creates a markdown file based on incoming filename suggestion
If already exists, returns false,
If other os.file issue, returns false,
If successful, returns true
Args:
markdown_filename (str),
... | c02f1de1d0f749e60268a56537b10ff4e15544ad | 3,613,919 |
def fit_msm(trajectory, prefix=None, save_path=None):
"""Function to fit the msm to a given trajectory and save the vizualization
Args:
trajectory ([type]): Time series to be discretized
prefix ([type], optional): Name to save a file.
save_path ([type], optional): Wheree to save a fil... | 2f7454f597a9cc3b0daa54c71c7a1e0dba455af5 | 3,613,920 |
def dataclass(
_cls = None,
*arg,
init = True,
repr = True,
eq = True,
order = False,
unsafe_hash = False,
):
"""
Modification of dataclasses.dataclass that adds the following methods:
1. dataclass.from_tuple(data_tuple: Tuple[Any])
2. data... | 5c5315d089496d27554e72f87f67bad85ec45ba1 | 3,613,921 |
def get_quiz_info(random_words):
"""
get examples and random answers for each test word in random_words
:param random_words: a list of random test words
:return: a list of quiz information
"""
db_session = DB_Session()
allrows = db_session.query(TestWords)
quiz_info = []
for word in ... | 3a3d994dc7ba77d6a2a1f1ed36ef0c94244f4baa | 3,613,922 |
def parse_dependencies(file_names):
"""Program logic: read files, verify dependencies.
For each input file, read lines and create dependencies. Verify each dependency.
:param file_names: files to read dependencies from.
:return: The list of dependencies, each verified.
"""
# type: (List[Text])... | 2b34060b79e673b84b5c29114407a7d0e876463d | 3,613,923 |
def load_model_from_link(name, **overrides):
"""Load a model from a shortcut link, or directory in spaCy data path."""
path = get_data_path() / name / '__init__.py'
try:
cls = import_file(name, path)
except AttributeError:
raise IOError(Errors.E051.format(name=name))
return cls.load(... | 9b640bcb621874fcc37bf64853d37dd57add4fe0 | 3,613,924 |
import requests
def tencent_resolve(url_like):
"""根据输入的url_like,查询其腾讯安全接口查询结果
:url_like: 可能有几种形式:url: http://www.baidu.com,domain: www.baidu.com,ip: 14.15.15.17,甚至可能是:http://14.15.16.17:80
:returns: {url_like: tencent}
"""
url = TENCENT_URL
payload = {
'dname': url_like
}
hea... | 89f5f4eb20dfa3a503312eace80bd900acff6146 | 3,613,925 |
def host_create(context, values):
"""Create a host.
:param context: context to query under
:param values: dictionary of host attributes to create
:returns: dictionary-like object containing created host
"""
return IMPL.host_create(context, values) | d7285795b42b4eca9c9bc19f72d18cad8e36d464 | 3,613,926 |
def __dispatch_remove_command(arguments: list) -> str:
"""
Dispatches command to remove file/folder
Returns command that was run
"""
command = ""
if arguments["file"]:
command = "remove-file"
library.remove_file(arguments["file"])
elif arguments["folder"]:
command = "... | fd94f3fcd929b9aa220f99684282b439023b728b | 3,613,927 |
import click
from datetime import datetime
import time
def _wait_for_job(T, job, hide_progress=False):
"""
Wait for the compliance job to complete
"""
if (
job is not None
and "status" in job
and (job["status"] == "failed" or job["status"] == "expired")
):
click.ec... | 626bc582427f1e5621c5059f72dd07f937d67ad8 | 3,613,928 |
def adjust_learning_rate(lr, gamma, epoch, step_index, iteration, epoch_size):
"""Sets the learning rate
# Adapted from PyTorch Imagenet example:
# https://github.com/pytorch/examples/blob/master/imagenet/main.py
"""
if epoch < 6:
lr = 1e-6 + (lr - 1e-6) * iteration / (epoch_size * 5)
el... | 0d691893b0ebb234507940df5bc340b4855fcdd6 | 3,613,929 |
def assign_material(obj, materialname):
"""This function assigns a material to an objects mesh.
:param obj: The object to assign the material to.
:type obj: bpy.types.Object
:param materialname: The materials name.
:type materialname: str
"""
if materialname not in bpy.data.materials:
... | cd937cb0df8eaf9ed17034191acbd400a0993908 | 3,613,930 |
def make_fcc(nx=1, ny=1, nz=1, scale=1.0, noise=0.0):
"""Make a FCC crystal for testing
Args:
nx: Number of repeats in the x direction, default is 1
ny: Number of repeats in the y direction, default is 1
nz: Number of repeats in the z direction, default is 1
scale: Amount to sca... | bfd18b0858657877165995cc50d5f8cae382501d | 3,613,931 |
import os
import sys
def getfname(chapelfile, output, prefix):
"""Compute filename for output"""
if output == 'rst':
filename = os.path.split(chapelfile)[1]
basename, _ = os.path.splitext(filename)
rstname = ''.join([basename, '.rst'])
rstfile = os.path.join(prefix, rstname)
... | 15d48044546718055979a0bb2548e9267b8fb134 | 3,613,932 |
import pickle
def load_pickle(pickle_path: str) -> object:
"""Avoid boilerplate pickle loading.
Args:
pickle_path (str): Path of pickle file
Returns:
object: Python object unpickled
"""
assert_file_exists(pickle_path)
with open(pickle_path, "rb") as pf:
return pickle... | 81615e6671a660fc61a1192525ea02abdb5079fc | 3,613,933 |
def add_to_list(str_to_add, groups):
"""
This will add a string to the groups array if it does not exist.
It will then return the index of the string within the Array
"""
if str_to_add.replace(".", REPLACE_CHAR) not in groups:
groups.append(str_to_add.replace(".", REPLACE_CHAR))
return g... | cbd1598ad0eb4d7691f57c4df5436ad4a4df69eb | 3,613,934 |
import time
import os
def analyze_channel(blobfiles=None, channel=None,
start=1, end=0,
print_msg=True,
server="http://localhost:5279"):
"""Obtain usage information from a channel by analyzing its blobs.
If the channel is not specified, it will anal... | 34ab04b6ec57b41c0a7d9e18f4a61144bd219c89 | 3,613,935 |
def get_centroid(coords):
"""
Function: get centroids of given coordinates.
Input:
- coords: numpy array. mx2xn. m = number of centroids; n = number of points per centroid.
Output:
- new_coords: numpy array (mx2). centroids.
"""
new_coords = np.zeros((coords.shape[0], coords.shape[1]))
for i in range(coords.sh... | 484ad4ebbf4bbc9517ce28a98e06d95acc02e3f0 | 3,613,936 |
from typing import List
def towers_of_hanoi(n: int) -> List[Move]:
"""This is a classic CS problem that's often used as an introduction to
recursion.
"""
return towers_helper(n, 1, 3, 2) | 1fe931fdf74cecc3784b71f66e43caa5d89e98c3 | 3,613,937 |
def update_Sx(S_old, n_old, d_old, d_new, d_min):
"""
Update on the sum of log degrees S_d and n based on degree distribution resulting from inserting or deleting
a single edge.
Parameters
----------
S_old: float
Sum of log degrees in the distribution that are larger than or equal to d... | 4803aa41cd9b807212ba0c90bde618b97f2b0b1b | 3,613,938 |
import typing
def cumprod(mod: int, a: typing.List[int]) -> typing.List[int]:
"""Compute cummulative product over Modular."""
a = a.copy()
for i in range(len(a) - 1):
a[i + 1] = a[i + 1] * a[i] % mod
return a | 62a99a916c5e09187f05b9a31096037b3c53eb85 | 3,613,939 |
def is_skin_cluster(skin_cluster):
"""
Checks if the given node is a valid skinCluster
:param skin_cluster: str, name of the node to be checked
:return: bool, True if the given node is a skin cluster node
"""
if not maya.cmds.objExists(skin_cluster):
logger.error('SkinCluster "{}" does... | 429533a6b0cfa909ad2851b28046812d9fd61a80 | 3,613,940 |
def opp_move(player: Player) -> (bool, bool):
"""
Utility function to simulate opponent's moves on your board.
:param player: Player object
:return: (Bool, Bool) : change_turn and game_on booleans indicating whether to
reverse the turn and whether the game is not over.
""... | af18374964c67bec407a7c03fe4c65ca9b604250 | 3,613,941 |
def get_v50(line,epoch,velocity,evelocity):
"""
Eg:
In [1]: from epm.velocity import get_v50,vHbetatovFeII,vph50tovFe
In [2]: v50_hbeta,ev50_hbeta=get_v50("Hbeta",18.,10350,500)
In [3]: vFeII50,evFeII50=vHbetatovFeII(v50_hbeta,ev50_hbeta)
In [4]: vFeII50,evFeII50
Out[4]: (4853.111318324523,... | 71dfd8f29063b2d695a82b53b53c0e7230bd2b2b | 3,613,942 |
def is_retfp(*args):
"""
is_retfp(ea) -> bool
"""
return _ida_nalt.is_retfp(*args) | e6958d9ccdff4b8ad11d78d6c635388a059a430e | 3,613,943 |
def outbound():
"""Returns a function that generates a matrix out of bounds a given
range"""
def _outbound(low, high, size, tol=1000, nums=100):
"""Generates a matrix that is out of bounds"""
low_end = -np.random.uniform(tol, low, (nums,))
high_end = np.random.uniform(tol, high, (nu... | f291d38fa4151f54d9cb97819b648a5989488b41 | 3,613,944 |
def trans_in_lang(string, lang):
"""
Translate a string into a specific language (which can be different
than the set language).
Usage:
{{ var|trans_in_lang:"fr" }}
"""
if check_for_language(lang):
return translation(lang).ugettext(string)
return string | 97428deac0f1aa78cc0c9bbff3556d2a0355cf9d | 3,613,945 |
from typing import Union
from typing import Optional
from typing import Tuple
async def async_set_config_parameter(
node: Node,
new_value: Union[int, str],
property_or_property_name: Union[int, str],
property_key: Optional[Union[int, str]] = None,
) -> Tuple[ConfigurationValue, CommandStatus]:
"""... | 24ec40965cdb6a54518945a3fe4323ff6e408cbf | 3,613,946 |
from operator import matmul
from operator import concat
def black_out(x, t, W, samples, reduce='mean'):
"""BlackOut loss function.
BlackOut loss function is defined as
.. math::
-\\log(p(t)) - \\sum_{s \\in S} \\log(1 - p(s)),
where :math:`t` is the correct label, :math:`S` is a set of negat... | c352426a648ecea86c3254718bf5c8f1d8b2f43f | 3,613,947 |
def has_instance(cls, typeclass):
"""Test whether a class is a member of a particular type-class.
:param cls: The class or type to test for membership.
:param typeclass: The typeclass to check. Must be a subclass of
`Typeclass`:class:.
:returns: True if cls is a member of typeclass, and F... | 548264ca54407b8451f55553eab020148f33343e | 3,613,948 |
def two_fermion(emat, lb, rb):
"""
Build matrix form of a two-fermionic operator in the given Fock basis,
.. math::
<F_{l}|\sum_{ij}E_{ij}\hat{f}_{i}^{\dagger}\hat{f}_{j}|F_{r}>
Parameters
----------
emat : 2d complex array
The impurity matrix.
lb : list or array
... | 5ee4a625b92ef0d894a2db095042bdc080b99cda | 3,613,949 |
def leakyRelu(X):
"""
Apply Leaky Rectified Linear Unit on X Vector.
PARAMETERS
==========
X: ndarray(dtype=float, ndim=1)
Array containing Input Values.
RETURNS
=======
ndarray(dtype=float,ndim=1)
Output Vector after Vectorised Operation.
"""
return np.maximu... | 2ce205eb4df832106ab8460a8b59a2cd1f8e73b1 | 3,613,950 |
def box_read(path_out, sim_id):
"""Read in ChemEvol instance from box<sim_id>.pck file.
Args:
path_out (str): directory of pickle file.
sim_id (str): simulation ID number.
Returns:
object: instance of ChemEvol class ('box' object).
"""
fname = _make_sim_path(path_out, sim_i... | fc89b4c43aff8a90d071e75a47c7128668362ae5 | 3,613,951 |
def second(str_number):
"""
:param str_number: str
:return int
"""
list_number = list(str_number)
total = list_number.__len__()
half = total/2
result = 0
for key, x in enumerate(list_number):
index_y = int((key + half) % total)
if x == list_number[index_y]:
... | 92ffd31c72f4c0f5bc09c244b2e03acaea2d45e3 | 3,613,952 |
def get_active_psupport():
""" Returns all active prod support tests """
results = []
experiences = get_experiences()
for exp in experiences:
if len(exp["splits"]) == 1:
exp_name = exp["experience_name"]
external_link = create_external_link(exp_name, exp["id"])
... | 4cdc41a325908f8f9f976f73a58e59a46c9c0fc8 | 3,613,953 |
import ipaddress
def is_valid_ipv4(address):
"""Check an IPv4 address for validity"""
try:
ip = ipaddress.ip_address(address)
except ValueError:
return False
if not isinstance(ip, ipaddress.IPv4Address):
return False
warning = None
if ip.is_loopback:
warning = "... | fd095d8903cd0a44bfd6a7eb02fa95217a60077a | 3,613,954 |
def two_pts_to_line(pt1, pt2):
"""
Create a line from two points in form of
a1(x) + a2(y) = b
"""
pt1 = [float(p) for p in pt1]
pt2 = [float(p) for p in pt2]
try:
slp = (pt2[1] - pt1[1]) / (pt2[0] - pt1[0])
except ZeroDivisionError:
slp = 1e5 * (pt2[1] - pt1[1])
a1 =... | d607008c41eaa052c0988a7ac66588b464aab8e0 | 3,613,955 |
def unstandardize_set(var_list, sample_array):
"""
Inputs: var_list- list of variables
sample_array- array with one sample corresponding to each variable
Takes an array of standardized values, unstandardizes them, and returns the
array of unstandardized values.
"""
var_count, i... | 3378609a7451819a998531be8da5d5fa6d1a9bab | 3,613,956 |
import json
def get_policy(request, log, tenantId, groupId, policyId):
"""
Get a scaling policy which describes an id, name, type, adjustment, and
cooldown, and links. This data is returned in the body of the response in
JSON format.
Example response::
{
"policy": {
... | f275a751026bbca5b6b12650aa0b686a372839f5 | 3,613,957 |
def loss(*, target_sfs, events, n, key, nreps=20):
"""
Mean squared error between ``target_sfs`` and simulated sfs
when simulating with the given ``events``, averaged over ``nreps``
replicate simulations.
"""
avg_sfs = jnp.zeros(n + 1)
for key in jax.random.split(key, nreps):
pi, tau... | 46ec73c249fb1271e63231e81ea744b466fdf7ab | 3,613,958 |
from typing import Callable
def profile(func: Callable) -> Callable:
"""
A decorator that uses cProfile.Profile class to profile a function.
:param func: function
:return: function
"""
def inner(*args, **kwargs):
pr = Profile()
pr.enable()
result = func(*args, **kwargs... | b3c3cdce4aa1650a803039facc6e8a8468a0abec | 3,613,959 |
import numpy as np
def yield_function(E,species='W'):
"""
use: Y = yield_function(E,species='W')
This method implements the modified Bohdansky formula for physical sputtering
with incidence angle 0. See for example
Y. Marandet et. al. PPCF 58 (2016) 114001
input:
E: Energy of incoming... | 71c562fa24960838ae58c9d7ed6ba37c3744e13c | 3,613,960 |
from datetime import date
def get_current_day():
"""
return the current day number value from (1-7).
"""
return date.today().isocalendar()[2] | 52558cf9c1cab283abe496845ce778eac4802980 | 3,613,961 |
def _load_with_pydub(file, audio_format=None):
"""
Open compressed audio or video file using pydub. If a video file
is passed, its audio track(s) are extracted and loaded.
Parameters
----------
file : str
path to audio file.
audio_format : str, default: None
string, audio/vi... | 8d06a6b743f0c4ef03e0b9ceecc9afb55d57f49e | 3,613,962 |
import re
def findpath(name):
"""Resolves absolute path of module"""
path = import_module(name).__file__
# adjust file extension
path = re.sub('.pyc$', '.py', path)
# strip trailing "__init__.py"
path = re.sub('__init__.py$', '', path)
return path | 4864eaa2a85d8faf10c56a2a32bd48b4dc015fb3 | 3,613,963 |
def sets_k_fold_pattern(rdms, pattern_descriptor='index', k=5, random=False):
""" generates training and test set combinations by splitting into k
similar sized groups. This version splits in the given order or
randomizes the order. For k=1 training and test_set are whole dataset,
i.e. no crossvalidatio... | ec95136844cfd9ebf5e7b8217621e46436b08db9 | 3,613,964 |
import json
def lambda_handler(event, context):
"""This is a sample Annotation Consolidation Lambda for custom labeling jobs. It takes all worker responses for the
item to be labeled, and output a consolidated annotation.
Parameters
----------
event: dict, required
Content of an example ... | 1c2e3a2bc5f70e22be5768dbcbce2db56166a19b | 3,613,965 |
from typing import Iterable
def convert_dtypes(df: DataFrame, keys: Iterable[str]) -> DataFrame:
"""
Wrapper around df.astype(), cast DataFrame columns to the appropriate type for each key.
Use mapping from TX_KEY_DTYPES global.
"""
return df.astype({key: TX_KEY_DTYPES[key] for key in keys}, copy=... | 77e8d5ad98932d72c06ba3c06ccdd4ad885f6586 | 3,613,966 |
from qcodes.dataset.data_set import load_by_id
def diff_param_values_by_id(left_id: RunId, right_id: RunId) -> ParameterDiff:
"""
Given the IDs of two datasets, returns the differences between
parameter values in each of their snapshots.
"""
# Local import to reduce load time and
# avoid circu... | 1fa84900b59ab2003a096b071e9c5893593f9b00 | 3,613,967 |
from typing import OrderedDict
import requests
def query(client: Client,
service_code: str,
header: dict = HEADER,
check_query: bool = True,
check_response: bool = True,
**params) -> OrderedDict:
"""Query Elexon API.
Parameters
----------
client : ... | c3f361e944d02222012a2a674244c13ac2e336ae | 3,613,968 |
def get_band_num(color, satellite):
"""Get the image band # from the color and satellite
Parameters
----------
color: string
color band name i.e. red, green, nir1
satellite: string
code for satellite (supports quickbird, geoeye 1 and worldview 2/3)
Returns
-------
int
... | e23fafccccf99d2cf5dee12295e233aa1ab614fd | 3,613,969 |
def ResNet50(parameters, num_channel=3, num_classes=10, att=False, mean=False):
"""
Function that creates a ResNet 50 model
:param parameters (list or tuple): List of parameters for the model
:param num_channel (int): Number of channels in input specimens
:param num_classes (int): Number of classes... | 54c509970d500984bda98c4c3aabf005a0e50f79 | 3,613,970 |
from typing import List
def read_file_list(path: str) -> List[str]:
"""读取文件列表(包含\\n字符)"""
with open(path, 'r', encoding='utf-8') as f:
content = f.readlines() # 包含\n字符
return content | 5dbb082f9d228cd2ef227d51603a232508ee74dd | 3,613,971 |
import torch
def letterbox_resize_tensor(src, dst_h, dst_w):
# https://stackoverflow.com/a/66539730
# It seems GPU is not helpful in this case
"""Resize with same aspect ratio as source image.
Args:
src: `torch.tensor`, source image which has a size of (N, C, H, W).
dst_h: `int`, heig... | f615c22cbbab4735f390e5469932e11da71e5094 | 3,613,972 |
def get_target(words, idx, window_size=5):
"""
Get a list of words in a window around an index
Input:
* words: the dictionary of words
* idx: the index for the word of interest
* window_size: (Optional) the number of words to include
Output:
* returns the words of interest that fall into the window
""... | 01d0e052bd6adfb1a8f32a3104c801ee68211801 | 3,613,973 |
def define_inputs():
"""
In this function, the user must define all the inputs that are required to run a simulation.
Returns:
"""
# Define the required inputs.
req_inputs = {'B': 0.0467,
'Lambda': 1.,
'E0': 0.99,
'C_R': 1e3,
... | 04db80abb9751d0b39dbdd053220295c18398c79 | 3,613,974 |
import six
def FSeek(params, ctxt, scope, stream, coord):
"""Returns 0 if successful or -1 if the address is out of range
"""
if len(params) != 1:
raise errors.InvalidArguments(
coord,
"{} args".format(len(params)),
"FSeek accepts only one argument",
)
... | 2b3aec837ed2436c911b100aea9af76863d6f9a7 | 3,613,975 |
def processFocusNVDAEvent(obj,force=False):
"""Processes a focus NVDA event.
If the focus event is valid, it is queued.
@param obj: the NVDAObject the focus event is for
@type obj: L{NVDAObjects.NVDAObject}
@param force: If True, the shouldAllowIAccessibleFocusEvent property of the object is ignored.
@type force:... | d4fdd05bdaa0d73955e35d99b41bc0db79537e9d | 3,613,976 |
def filter_results(TAP_df, print_targets=True):
"""
Add a few new useful columns to the pandas.DataFrame with the query results from the PyVO TAP service and
return the full query DataFrame and optionally a summary of the results.
Parameters
----------
TAP_df : pandas.DataFrame
This is... | 9b2fb713e0b01c0cc08a5e883fe18446f065a71e | 3,613,977 |
def node_list(request):
"""Retrieve a list of nodes.
:param request: HTTP request.
:return: A list of nodes.
http://docs.openstack.org/developer/python-ironicclient/api/ironicclient.v1.node.html#ironicclient.v1.node.NodeManager.list
"""
node_manager = ironicclient(request).node
return node... | 7e24434304c92a498ae62b6baa2bf6fda6baf365 | 3,613,978 |
import torch
def random_input(in_features: int) -> ByteTensor:
"""Return a random bit tensor of length 'in_features.'"""
state = np.random.randint(0, 2, (in_features, )).astype(np.int32)
return torch.from_numpy(state).byte() | 7a371db6628c1a178a1f0749857bdd9ed9d78546 | 3,613,979 |
def semi_split(s):
""" Split 's' on semicolons.
"""
return map(lambda x: x.strip(), s.split(';')) | f81eff42e170c7b760a75d86d5d0d9326365ca8e | 3,613,980 |
from typing import Optional
def get_implementation() -> Optional[PythonImplementation]:
"""Determine the current Python implementation.
:return: The appropriate :class:`~PythonImplementation` instance if found
:rtype: Optional[PythonImplementation]
"""
try:
return PythonImplementation(py... | 7b7298f3c8fd7f27585c42f5f4ef1db60af44ee7 | 3,613,981 |
def sample_passwds():
"""Pre-generates password hashes for `sample_users`. This drastically speeds up any tests
relying on sample users, as bcrypt is intentionally very slow."""
pwds = dict(
admin='a',
mod='b',
arch='c',
user='d',
)
for k, pwd in pwds.items():
... | 39f42be8b4a3a58de9410490cea81e4a3a2dc4ec | 3,613,982 |
def well_formed(expr):
"""Check that each Var is only bound once (well formed).
Parameters
----------
expr : tvm.relay.Expr
The input expression
Returns
-------
well_form : bool
Whether the input expression is well formed
"""
return _ffi_api.well_formed(expr) | c826792e6477f62dfa8cea0200c7b758424dfee9 | 3,613,983 |
def call_function(ctx,
node,
func_var,
args,
fallback_to_unsolvable=True,
allow_noreturn=False):
"""Call a function.
Args:
ctx: The abstract context.
node: The current CFG node.
func_var: A variable of the possibl... | da7f614bd70bb6695f7d8f0f94a25db05c9d28e0 | 3,613,984 |
def login():
"""Log user in."""
# forget any user_id
session.clear()
# if user reached route via POST (as by submitting a form via POST)
if request.method == "POST":
# ensure username was submitted
if not request.form.get("username"):
return apology("Must provide usern... | 5d6fa63efaf3ef14529328b5a3fd47d94f940b53 | 3,613,985 |
from operator import inv
def _system_mat3d(fmatin, cmat, fmatout):
"""Computes a system matrix from a characteristic matrix Fin-1.C.Fout"""
fmatini = inv(fmatin)
out = bdotdm(fmatini,cmat)
return bdotmd(out,fmatout) | 0e792ddc6b5dc636bc51ad0fe25696bd6ce990f1 | 3,613,986 |
def grad(phit):
"""Returns the spatial derivatives of a Fourier transformed variable.
Returns (∂/∂x[F[φ]], ∂/∂y[F[φ]]) i.e. (ik F[φ], il F[φ])"""
global ik, il
phixt = ik*phit # d/dx F[φ] = ik F[φ]
phiyt = il*phit # d/dy F[φ] = il F[φ]
return (phixt, phiyt) | d70f93018fbf630dd9380ef31cf70788c309e9dc | 3,613,987 |
import csv
import numpy as np
import logging
def csv_reader(data_file):
"""returns np.array(time), np.array(voltage)
This function reads in csv files.
The for loop reads each row of the time and voltage lists and
converts them from strings to floats. If a string can't be
converted, a ValueError ... | 93540368516ba13e1a7c7e9deee1d068218dcb3a | 3,613,988 |
def KS_bucket(score, target, bucket = 10, method = 'quantile', **kwargs):
"""calculate ks value by bucket
Args:
score (array-like): list of score or probability that the model predict
target (array-like): list of real target
bucket (int): n groups that will bin into
method (str)... | b3d0312055c7b7b49a1fbd11b0eaa76ae85bd0b4 | 3,613,989 |
def create_input_data():
"""Utility function for creating input data."""
position = Coordinate2d(3.0, 4.0)
speed = Coordinate2d(2.0, 5.0)
sample_time = 0.1
return {'position': position,
'speed': speed,
'sample_time': sample_time} | aad272f153662949b81f328dab0e3f962a65f08a | 3,613,990 |
def get_metadata(**kwargs):
"""
Metadata
Account metadata
Reference: https://iexcloud.io/docs/api/#metadata
Data Weighting: ``Free``
"""
return Metadata(**kwargs).fetch() | 94b33368170b7dc2b47e68a97169d2c02646016f | 3,613,991 |
from scipy.misc import comb
def polyConvMatrix(n, trans=(0, 1)):
"""
Return the upper triangular matrix (i,k) * b**k * a**(i-k), that
converts polynomial coeffs for x~:=a+b*x (P~ = a0~ + a1~*x~ +
a2~*x~**2 + ...) in polynomial coeffs for x (P = a0 + a1*x +
a2*x**2 + ...). Therefore, (a,b)=(0,1) gi... | 27bd03dc47af7f947d273f3d6d26a32d2b5c239c | 3,613,992 |
from typing import cast
import pandas
def get_user_activity(session):
"""Create a plot showing the inline usage statistics."""
def running_window(session, subquery):
# Create a running window which sums all users up to this point for the current millennium ;P
users = (
session.que... | 862dca86cdefe0ff512fe905de4e36568ed54c87 | 3,613,993 |
import os
def git_version(file, version=None):
"""
Fetch from Git: {tag} {distance-from-tag} {current commit hash}
Return as semantic version string compliant with PEP440
"""
root = os.path.dirname(os.path.realpath(file))
try:
tag, distance, commit = g.gitDescribe(root)
# 5... | aa81074ecf76efabefd78560316cf8fab577f81e | 3,613,994 |
def get_log_from_policy(policy: Policy, policy_id: PolicyID) -> dict:
"""
Gets the to_log var from a policy and rename its keys,
adding the policy_id as a suffix.
"""
to_log = {}
if hasattr(policy, "to_log"):
for k, v in policy.to_log.items():
to_log[f"{k}/{policy_id}"] = v
... | 056ea2e519e1160cf828c19625ca7e869e4da51a | 3,613,995 |
def show_ridge_plot(df: pd.DataFrame, name="naked") -> sns.FacetGrid:
"""Shows the distribution of the data for different categories.
Using the output from `generate_df_for_theo_correlation_comparison`
we group the data per quantile and display it in several different
distribution plots.
Taken alm... | 4796ac0b49b43da0aeadd39e2f990f7406b52f78 | 3,613,996 |
def f2n( fig ):
"""
@brief Convert a Matplotlib figure to a 4D numpy array with RGBA channels and return it
@param fig a matplotlib figure
@return a numpy 3D array of RGBA values
"""
# draw the renderer
fig.canvas.draw()
data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uin... | ccf3b16e27e52de21b8ef39e4dad09b2c9296d37 | 3,613,997 |
def windows_details(request):
"""Get available connection details for windows hosts"""
return connection_details_for(request.param) | dda2a5b0c9ea2257bc798cf31962aa5bfded0402 | 3,613,998 |
def exclude_jobs(jobs, project, tag) -> list:
"""Returns list of jobs filtered by exclude map variables.
Args:
jobs: List of jobs
project: A project name string
tag: A tag string
Returns:
List of of jobs after being filtered with the exclude maps
"""
included_jobs =... | 6905430b83f61721208c0dbd855c845736b264a6 | 3,613,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.