content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def update_t_new_docker_image_names(main, file):
""" Updates the names of the docker images from lasote to conanio
"""
docker_mappings = {
"lasote/conangcc49": "conanio/gcc49",
"lasote/conangcc5": "conanio/gcc5",
"lasote/conangcc6": "conanio/gcc6",
"lasote/conangcc7": "conan... | 6d1a1dd0f254252cf73d7a89c926dc2476fc89e8 | 2,200 |
def fit(kern, audio, file_name, max_par, fs):
"""Fit kernel to data """
# time vector for kernel
n = kern.size
xkern = np.linspace(0., (n - 1.) / fs, n).reshape(-1, 1)
# initialize parameters
if0 = gpitch.find_ideal_f0([file_name])[0]
init_f, init_v = gpitch.init_cparam(y=audio, fs=fs, max... | e4b6519f1d9439e3d8ea20c545664cf152ce6a89 | 2,201 |
def find_next_open_date(location_pid, date):
"""Finds the next day where this location is open."""
location = current_app_ils.location_record_cls.get_record_by_pid(
location_pid
)
_infinite_loop_guard = date + timedelta(days=365)
while date < _infinite_loop_guard:
if _is_open_on(loca... | 74a38c39d2e03a2857fa6bbc7e18dc45c0f4e48a | 2,202 |
import functools
def check_dimension(units_in=None, units_out=None):
"""Check dimensions of inputs and ouputs of function.
Will check that all inputs and outputs have the same dimension
than the passed units/quantities. Dimensions for inputs and
outputs expects a tuple.
Parameters
... | 68fb2bf7e0858824e5a1e3bdcef69834b08142ac | 2,203 |
def _rowcorr(a, b):
"""Correlations between corresponding matrix rows"""
cs = np.zeros((a.shape[0]))
for idx in range(a.shape[0]):
cs[idx] = np.corrcoef(a[idx], b[idx])[0, 1]
return cs | 21df87b6f3bba58285cac0242b7c9e72b534f762 | 2,204 |
def gff_to_dict(f_gff, feat_type, idattr, txattr, attributes, input_type):
"""
It reads only exonic features because not all GFF files contain gene and trascript features. From the exonic
features it extracts gene names, biotypes, start and end positions. If any of these attributes do not exit
then they... | f1574cabb40f09f4f7a3b6a4f0e1b0a11d5c585d | 2,205 |
def _subtract_the_mean(point_cloud):
"""
Subtract the mean in point cloud and return its zero-mean version.
Args:
point_cloud (numpy.ndarray of size [N,3]): point cloud
Returns:
(numpy.ndarray of size [N,3]): point cloud with zero-mean
"""
point_cloud = point_cloud - np.mean(poin... | 94866087a31b8268b06250d052fd12983222a066 | 2,206 |
from .load import url_load_list
def ncnr_load(filelist=None, check_timestamps=True):
"""
Load a list of nexus files from the NCNR data server.
**Inputs**
filelist (fileinfo[]): List of files to open.
check_timestamps (bool): verify that timestamps on file match request
**Returns**
out... | 97452707da94c356c93d18618f8b43bc8459a63b | 2,207 |
def load_source_dataframe(method, sourcename, source_dict,
download_FBA_if_missing, fbsconfigpath=None):
"""
Load the source dataframe. Data can be a FlowbyActivity or
FlowBySector parquet stored in flowsa, or a FlowBySector
formatted dataframe from another package.
:param ... | 9a928441d790bb35acd0d32efeea105eeb3082c8 | 2,208 |
import json
def unpack_nwchem_basis_block(data):
"""Unserialize a NWChem basis data block and extract components
@param data: a JSON of basis set data, perhaps containing many types
@type data : str
@return: unpacked data
@rtype : dict
"""
unpacked = json.loads(data)
return unpacked | dfa920f80ae8f0caf15441c354802410c8add690 | 2,209 |
def starify(name):
"""
Replace any ints in a dotted key with stars. Used when applying defaults and widgets to fields
"""
newname = []
for key in name.split('.'):
if is_int(key):
newname.append('*')
else:
newname.append(key)
name = '.'.join(newname)
re... | f7c8baf602ecc4cd12088d4ba70524b2a316875e | 2,210 |
import os
def render(states, actions, instantaneous_reward_log, cumulative_reward_log, critic_distributions, target_critic_distributions, projected_target_distribution, bins, loss_log, episode_number, filename, save_directory, time_log, SPOTNet_sees_target_log):
"""
TOTAL_STATE = [relative_x, relative_y, rela... | 5f41390e2ab0f92d648e80cd28e369d3eb06af10 | 2,211 |
def hydrogens(atom: Atom) -> int:
"""Total number of hydrogen atoms (int).
"""
return atom.GetTotalNumHs() | f36e04d2c67eaf81b031651f78bb64db3a1c614c | 2,212 |
def to_field(field_tuple):
"""Create a dataframe_field from a tuple"""
return dataframe_field(*field_tuple) | 6863cc33b8eea458223b9f4b1d4432104784d245 | 2,213 |
def compute_subjobs_for_build(build_id, job_config, project_type):
"""
Calculate subjobs for a build.
:type build_id: int
:type job_config: JobConfig
:param project_type: the project_type that the build is running in
:type project_type: project_type.project_type.ProjectType
:rtype: list[Subj... | caa16899755fbb19530c27004db3515e3eeab9d6 | 2,214 |
def pymodbus_mocked(mocker):
"""Patch pymodbus to deliver results."""
class ResponseContent:
"""Fake a response."""
registers = [0]
class WriteStatus:
"""Mock a successful response."""
@staticmethod
def isError():
# pylint: disable=invalid-name,missing... | fdee663d9a8a80496ab6678aacb0b820251c83e1 | 2,215 |
def user_can_view_assessments(user, **kwargs):
""" Return True iff given user is allowed to view the assessments """
return not appConfig.settings.LOGIN_REQUIRED or user.is_authenticated | 1ef3f41ee311a6504d6e0cff0f5cad68135e0527 | 2,216 |
from typing import List
def get_hashes(root_hash: str) -> List[str]:
""" Return a list with the commits since `root_hash` """
cmd = f"git rev-list --ancestry-path {root_hash}..HEAD"
proc = run(cmd)
return proc.stdout.splitlines() | c0fdb996cf43066b87040b6647b75f42e8f7360f | 2,217 |
import zipfile
def unzip_file(zip_src, dst_dir):
"""
解压zip文件
:param zip_src: zip文件的全路径
:param dst_dir: 要解压到的目的文件夹
:return:
"""
r = zipfile.is_zipfile(zip_src)
if r:
fz = zipfile.ZipFile(zip_src, "r")
for file in fz.namelist():
fz.extract(file, dst_dir)
e... | 8b89f41f38cc688f6e0473a77215ae72b163654a | 2,218 |
def abort_multipart_upload(resource, bucket_name, object_name, upload_id):
"""Abort in-progress multipart upload"""
mpupload = resource.MultipartUpload(bucket_name, object_name, upload_id)
return mpupload.abort() | 93535c2404db98e30bd29b2abbda1444ae4d0e8a | 2,219 |
import os
def read_data(input_path):
"""Read pre-stored data
"""
train = pd.read_parquet(os.path.join(input_path, 'train.parquet'))
tournament = pd.read_parquet(os.path.join(input_path, 'tournament.parquet'))
return train, tournament | d55b7b645089af0af2b7b27ec13e0581bf76e21a | 2,220 |
def double(n):
"""
Takes a number n and doubles it
"""
return n * 2 | 8efeee1aa09c27d679fa8c5cca18d4849ca7e205 | 2,221 |
import torch
def Normalize(tensor, mean, std, inplace=False):
"""Normalize a float tensor image with mean and standard deviation.
This transform does not support PIL Image.
.. note::
This transform acts out of place by default, i.e., it does not mutates the input tensor.
See :class:`~torchvi... | 1312955d0db28ae66f6dadd9c29f3034aa21e648 | 2,222 |
from rfpipe import candidates, util
def reproduce_candcollection(cc, data=None, wisdom=None, spec_std=None,
sig_ts=[], kalman_coeffs=[]):
""" Uses candcollection to make new candcollection with required info.
Will look for cluster label and filter only for peak snr, if available.
... | 6bd57054262bcc0ea5fe05dbe0b2a8f93cf9c7dc | 2,223 |
import scipy
def hilbert(signal, padding='nextpow'):
"""
Apply a Hilbert transform to a `neo.AnalogSignal` object in order to
obtain its (complex) analytic signal.
The time series of the instantaneous angle and amplitude can be obtained
as the angle (`np.angle` function) and absolute value (`np.a... | cf07ae43c928d9c8fdb323d40530d0353bc861ee | 2,224 |
def _tagged_mosc_id(kubeconfig, version, arch, private) -> str:
"""determine what the most recently tagged machine-os-content is in given imagestream"""
base_name = rgp.default_imagestream_base_name(version)
base_namespace = rgp.default_imagestream_namespace_base_name()
name, namespace = rgp.payload_ima... | 1fa4ebf736b763fb97d644c0d55aa3923020107d | 2,225 |
def load_household_size_by_municipality():
"""Return dataframe, index 'Gemeente', column 'HHsize'."""
dfhh = pd.read_csv('data/huishoudens_samenstelling_gemeentes.csv', comment='#')
dfhh.sort_values('Gemeente', inplace=True)
dfhh.set_index('Gemeente', inplace=True)
# remove rows for nonexistent mu... | 9e78345a00209135ec4185a806a70deeb10d5bea | 2,226 |
from typing import Dict
from typing import Any
from typing import List
def gcp_iam_service_account_delete_command(client: Client, args: Dict[str, Any]) -> CommandResults:
"""
Delete service account key.
Args:
client (Client): GCP API client.
args (dict): Command arguments from XSOAR.
... | eeea44d6cc96b430c63168346849ac30a1247cad | 2,227 |
from typing import Union
from typing import Tuple
def couple_to_string(couple: Union[Span, Tuple[int, int]]) -> str:
"""Return a deduplicated string representation of the given couple or span.
Examples:
>>> couple_to_string((12, 15))
"12-15"
>>> couple_to_string((12, 12))
"12"... | 8aaa0e2b7dfbdd58e4f9765a56f9057dd2b612f3 | 2,228 |
def create_study(X, y,
storage=None, # type: Union[None, str, storages.BaseStorage]
sample_method=None,
metrics=None,
study_name=None, # type: Optional[str]
direction='maximize', # type: str
load_cache=False, # typ... | bf8ea9c5280c06c4468e9ba015e62401e65ad870 | 2,229 |
import os
import json
import logging
def setup_logging(path='log.config', key=None):
"""Setup logging configuration"""
if os.path.exists(path):
with open(path, 'rt') as f:
config = json.load(f)
logging.config.dictConfig(config)
else:
logging.basicConfig(level=logging.DE... | be4a4e94370f25ea232d5fc36b7d185bae2c5a1f | 2,230 |
import inspect
def test_no_access_to_class_property(db):
"""Ensure the implementation doesn't access class properties or declared
attrs while inspecting the unmapped model.
"""
class class_property:
def __init__(self, f):
self.f = f
def __get__(self, instance, owner):
... | ab24f6405675cba44af570282afa60bd1e600dcf | 2,231 |
import re
def get_gb_version(backbone_top_cmake_path):
"""
Find the game backbone version number by searching the top level CMake file
"""
with open(backbone_top_cmake_path, 'r') as file:
cmake_text = file.read()
regex_result = re.search(gb_version_regex, cmake_text)
return reg... | a4855c5fd82579b5b1f4f777ee0c040227432947 | 2,232 |
from typing import Optional
from typing import List
async def get_processes(name: Optional[str] = None) -> List[Process]:
"""
Get all processes.
Args:
name (Optional[str], optional): Filter by process name. Defaults to None.
Returns:
List[Process]: A list of processes.
"""
if... | 5133a81dcda079e6b5ed649443f9befed72be953 | 2,233 |
def plot_day_of_activation(df, plotname):
"""
Plots Aggregate of Day of Activation.
"""
# todo sort order in logical day order
dotw = {0: 'Monday',
1: 'Tuesday',
2: 'Wednesday',
3: 'Thursday',
4: 'Friday',
5: 'Saturday',
6: 'S... | 3c50196d1cd63972c3263bb695967f3552739fd1 | 2,234 |
def get_rucio_redirect_url(lfn, scope):
"""
get_rucio_redirect_url: assemble Rucio redirect URL
@params: lfn ... one filename
e.g. user.gangarbt.62544955._2108356106.log.tgz
scope ... scope of the file with lfn
e.g. user.gangarbt, or... | 26547c18d9699d0ab3d6d963382bf14c067b982f | 2,235 |
async def _getRequest(websession, url):
"""Send a GET request."""
async with websession.get(url, headers=HEADER) as response:
if response.status == 200:
data = await response.json(content_type=None)
else:
raise Exception('Bad response status code: {}'.format(response.stat... | 6511926b2ce753f5233778c702a11142e6cad5a3 | 2,236 |
def interval_seconds():
"""returns the time interval in seconds
Returns:
int
"""
return int(interval_to_milliseconds(interval())/1000) | 831c24cb113dab2b39fc068c397c41c3cc1131b5 | 2,237 |
import subprocess
def get_current_git_branch():
"""Get current git branch name.
Returns:
str: Branch name
"""
branch_name = "unknown"
try:
branch_name = subprocess.check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD']).decode('ascii').strip()
except subprocess.CalledProce... | 6d677d0f4e15532c20774e479b49a23093dad09a | 2,238 |
from typing import Optional
from typing import Sequence
def get_autonomous_db_versions(compartment_id: Optional[str] = None,
db_workload: Optional[str] = None,
filters: Optional[Sequence[pulumi.InputType['GetAutonomousDbVersionsFilterArgs']]] = None,
... | e10770e9db891079dda251578f851bdb7a0ade8e | 2,239 |
def azimuthal_average(image, center=None, stddev=True, binsize=0.5, interpnan=False):
"""
Calculate the azimuthally averaged radial profile.
Modified based on https://github.com/keflavich/image_tools/blob/master/image_tools/radialprofile.py
Parameters:
imgae (numpy 2-D array): image array.
... | f5b5e5b4b21af71c50f0a0a9947d3a5cc203bdf0 | 2,240 |
from typing import OrderedDict
def get_setindices(header, setnames):
"""From header like ---ID, coverage, set1_q-value set2_q-value---
this returns indices for different sets {'q-value': {'set1': 2, 'set2: 3}}
"""
setindices = OrderedDict()
for index, field in enumerate(header):
for setnam... | 1bdbda0528098a55438b4cb24ca22358fae7e682 | 2,241 |
def _base_and_stride(freqstr):
"""
Return base freq and stride info from string representation
Example
-------
_freq_and_stride('5Min') -> 'Min', 5
"""
groups = opattern.match(freqstr)
if groups.lastindex != 2:
raise ValueError("Could not evaluate %s" % freqstr)
stride = g... | a562b0a49f2e5a1d4f49119a424dbfd1588d9c97 | 2,242 |
def generate_label(input_x,threshold):
"""
generate label with input
:param input_x: shape of [batch_size, sequence_length]
:return: y:[batch_size]
"""
batch_size,sequence_length=input_x.shape
y=np.zeros((batch_size,2))
for i in range(batch_size):
input_single=input_x[i]
... | 0091fb0d4c92884af1cf07d8afd248e2afeb92b2 | 2,243 |
import io
def sf_imread(
img_path,
plot=True,
):
"""
Thin wrapper around `skimage.io.imread` that rotates the image if it is
to be used for plotting, but does not if it is to be used for measurements.
Parameters
----------
img_path : str
Path to image
plot : bool
D... | 3eb17fcb5bee144f7c822cfa23d5057c5fecc109 | 2,244 |
def test_plugin_ws_url_attributes(spf, path, query, expected_url):
"""Note, this doesn't _really_ test websocket functionality very well."""
app = spf._app
test_plugin = TestPlugin()
async def handler(request):
return text('OK')
test_plugin.websocket(path)(handler)
spf.register_plugin(... | f6e1f28f1df1e712ab399db48c8a4e0058d11d11 | 2,245 |
def less_than(x, y, force_cpu=None, cond=None, name=None):
"""
${comment}
Args:
x(Tensor): ${x_comment}.
y(Tensor): ${y_comment}.
force_cpu(${force_cpu_type}): ${force_cpu_comment}.
cond(Tensor, optional): Optional output which can be any created Tensor
that mee... | 676cdc38b83c2155bbf166f01f50554c1751585e | 2,246 |
import re
def get_page_namespace(url_response):
"""
:type element: Tag
:rtype: int
"""
keyword = '"wgNamespaceNumber"'
text = url_response
if keyword in text:
beginning = text[text.find(keyword) + len(keyword):]
ending = beginning[:beginning.find(',')]
ints = re.findall('\d+', ending)
if len(ints) > 0:... | f4e61d4a927401995f2435a94170ca691ff9119e | 2,247 |
def batch_to_seq(h, nbatch, nsteps, flat=False):
"""
Assumes Time major data!!
x.shape = [nsteps, nbatch, *obs_shape]
h = x.reshape([-1, *x.shape[2:]]))
"""
if flat:
h = tf.reshape(h, [nsteps, nbatch])
else:
h = tf.reshape(h, [nsteps, nbatch, -1])
return [tf.squeeze(v, [0... | a39bf967110b802063a37260147c98ecdf8925bb | 2,248 |
def get_site_camera_data(site_no):
"""An orchestration method that fetches camera data and returns the site dictionary"""
json_raw = get_json_camera_data()
camera = json_raw_to_dictionary(json_raw)
return find_site_in_cameras(site_no, camera) | c9d9febebe8c80dd9de18ece8085853224140d3b | 2,249 |
import argparse
def get_args():
"""
Get arguments to the tool with argparse
:return: The arguments
"""
parser = argparse.ArgumentParser()
parser.add_argument("filename", action='store',
help='.xyz file(s) with optimised geometries from which to make .top and .gro files'... | 0085922ad21776521bda2b2ce204983dd7181b89 | 2,250 |
def find_contam(df, contaminant_prevalence=0.5, use_mad_filter=False):
"""Flag taxa that occur in too many samples."""
taxa_counts = {}
for taxa in df['taxa_name']:
taxa_counts[taxa] = 1 + taxa_counts.get(taxa, 0)
thresh = max(2, contaminant_prevalence * len(set(df['sample_name'])))
contami... | 6f5976d97d7585d0dff60b90b2d6e5d6e22b6353 | 2,251 |
def has_level_or_node(level: int, *auth_nodes: str) -> Rule:
"""
:param level: 需要群组权限等级
:param auth_nodes: 需要的权限节点
:return: 群组权限等级大于要求等级或者具备权限节点, 权限节点为deny则拒绝
"""
async def _has_level_or_node(bot: Bot, event: Event, state: T_State) -> bool:
auth_node = '.'.join(auth_nodes)
detail... | a755b959eeb93caf113c157aa3551c45c1644216 | 2,252 |
import time
import random
import copy
def solve_problem(problem, max_iter_num=MAX_ITER_NUM, max_iter_num_without_adding=MAX_ITER_NUM_WITHOUT_ADDITIONS, iter_num_to_revert_removal=ITER_NUM_TO_REVERT_REMOVAL, remove_prob=ITEM_REMOVAL_PROBABILITY, consec_remove_prob=CONSECUTIVE_ITEM_REMOVAL_PROBABILITY, ignore_removed_i... | b240e0129e35c4066ec46d9dde68b012a821e319 | 2,253 |
import PIL
def _pil_apply_edit_steps_mask(image, mask, edit_steps, inplace=False):
"""
Apply edit steps from unmasking method on a PIL image.
Args:
image (PIL.Image): The input image.
mask (Union[int, tuple[int, int, int], PIL.Image]): The mask to apply on the image, could be a single gre... | c2bf05c282039ab5ff7eebefd8d9b3b635e9f74c | 2,254 |
def do_let_form(expressions, env):
"""Evaluate a let form."""
check_form(expressions, 2)
let_env = make_let_frame(expressions.first, env)
return eval_all(expressions.second, let_env) | e291880a21c99fcc05d8203dfd73dccc9084a72b | 2,255 |
def bubble(n_categories=5,n=10,prefix='category',mode=None):
"""
Returns a DataFrame with the required format for
a bubble plot
Parameters:
-----------
n_categories : int
Number of categories
n : int
Number of points for each category
prefix : string
Name for each category
mode : string
Form... | 77ba74f9bf6c09c49db8c4faa5934bd502995a5b | 2,256 |
def get_coherence(model, token_lists, measure='c_v'):
"""
Get model coherence from gensim.models.coherencemodel
:param model: Topic_Model object
:param token_lists: token lists of docs
:param topics: topics as top words
:param measure: coherence metrics
:return: coherence score
"""
i... | 1e8632eb901fc5219a4070d8e0b8e390612f7338 | 2,257 |
def run_vscode_command(
command_id: str,
*args: str,
wait_for_finish: bool = False,
return_command_output: bool = False,
):
"""Runs a VSCode command, using command server if available
Args:
command_id (str): The ID of the VSCode command to run
wait_for_finish (bool, optional): W... | 0bf1cfed5d2e02cf618ba8c7c9347d0408ef0ee3 | 2,258 |
import os
def clc_prepare(reference, outdir, source):
"""
create a CLC subset resampled to a reference image.
Parameters
----------
reference: str
the reference file with the target CRS and extent
outdir: str
the directory to write the new file to;
new files are na... | 0ebf57a5c11684e1575fb0eb3b69bde62d807431 | 2,259 |
from imucal.management import find_calibration_info_for_sensor # noqa: F401
from typing import Optional
from typing import Callable
from typing import List
from pathlib import Path
def find_calibrations_for_sensor(
sensor_id: str,
folder: Optional[path_t] = None,
recursive: bool = True,
filter_cal_ty... | b28a6deb1348fd86c93ae6fd0b292626a99c2149 | 2,260 |
def reward_displacement(navenv):
""" Reward = distance to previous position"""
r = dist(navenv.current_pos, navenv.old_pos)
return r | f2d9f5bf78a93967c6e74a4fba0e25109fa1fb3b | 2,261 |
import uuid
def MakeLinuxFirmware(save=True, **kwargs):
"""Create and return a LinuxFirmware for test."""
defaults = {
'manufacturer': 'Lonovo',
'serial': 'blah',
'password': '123456789',
'machine_uuid': str(uuid.uuid4()).upper(),
'owner': 'someone',
'asset_tags': ['12345'],
... | 2b4381035ae55ffc5996d06e5a9455c7ca148a85 | 2,262 |
def get_unity_filesystem_parameters():
"""This method provide parameters required for the ansible filesystem
module on Unity"""
return dict(
filesystem_name=dict(required=False, type='str'),
filesystem_id=dict(required=False, type='str'),
nas_server_name=dict(required=False, type=... | 2cbbe284a8345341abf80948d659c2f2625b6e8f | 2,263 |
def get_time_difference(row, start_col, end_col, start_format, end_format, unit='days'):
"""
Returns a Series object of days
Unit can be D for Days, or Y for Years
"""
start_date = row[start_col]
end_date = row[end_col]
if pd.isnull(start_date) or pd.isnull(end_date):
return np.nan
else:
... | a73fea6bebc777ec8ff4ff89118e940f8dfdfcf1 | 2,264 |
def get_account(account_name, password):
"""Displays account data from the wallet.
--- Definitions ---
{"name": "account_name", "prompt": "Alias of account", "default": "Myaccount"}
{"name": "password", "prompt": "Password to decrypt private key", "default": "Mypassword"}
"""
db = get_wallet_d... | 09791696c4a6c3ddfc0ceae20e50abf7f15893f5 | 2,265 |
def invert(img):
"""
Function to invert colors of an image
"""
r, g, b, a = colorsys_getRGBA(img) # Get r, g, b, a
r, g, b = 255 - r, 255 - g, 255 - b # Invert all colors
img_arr = np.dstack((r, g, b, a))
return img_arr | 013d708fb434b450404879346f25ad0d7088e3cf | 2,266 |
def spearman_kendall_test(df, item, alpha=0.05, increasing=True,
rank_in='Rank',
category_in='category',
dataset_in='dataset',
userid_in='userid'
):
"""
Do spearman's and kendall's t... | d8c85f20866a68a7070be89c57cdb18d2b33c828 | 2,267 |
def array2string(array, _depth=0):
"""
Recursively create a initializer list style string from an iterable with
multiple dimensions.
Args:
array (iterable): input iterable which is expected to have elements that
can be converted to strings with `str()`.
_depth ... | 948bfe9e63f16c588001707125afe8d2867ff6b6 | 2,268 |
def rail_help_wrapper(prog):
""" So formatter_class's max_help_position can be changed. """
return RailHelpFormatter(prog, max_help_position=40) | aa821f68ea1587a051be59f52187dbf9b1dd2d91 | 2,269 |
def project_dashboard(request):
"""
The function calling Project Dashboard page.
:param request:
:return:
"""
global all_vuln, \
total_web, \
all_high, \
total_network, \
all_medium, \
all_low, \
all_web_high, \
all_web_medium, \
al... | 0459776f846a8f089fefd528605d2e850aeced5c | 2,270 |
def getSelfRole(store):
"""
Retrieve the Role which corresponds to the user to whom the given store
belongs.
"""
return getAccountRole(store, userbase.getAccountNames(store)) | d548ba6406ec92df7777498574f86cf44737ba8b | 2,271 |
def forwardCOMDQ(robot, m = 0, symbolic = False):
"""
Using Dual Quaternions, this function computes forward kinematics to m - th center of mass, given joints positions in radians. Robot's kinematic parameters have to be set before using this function
robot: object (robot.jointsPositions, robot.linksLe... | e197839d98cdbb8b15449d33c8677adc5f9d3e8a | 2,272 |
def gen_mode():
"""获取玩家想要考试的模式"""
while True:
mode = input("如何考试?\n输入1顺序考试\n输入2乱序考试\n>>")
if mode in ("1", "2"):
return mode
else:
print()
print("非法输入,请输入\"1\"或\"2\"")
print("你不需要输入双引号")
print("--------------------------------") | eb3ff4a0812fe088f3acb1302730f5f48c6fbcda | 2,273 |
def find_movers(threshold, timeframe: Timeframe, increasing=True, decreasing=False, max_price=None):
"""
Return a dataframe with row index set to ASX ticker symbols and the only column set to
the sum over all desired dates for percentage change in the stock price. A negative sum
implies a decrease, pos... | ff1524d74dfe76630fb45b24119f57c3289ba355 | 2,274 |
from bigdl.nano.deps.automl.hpo_api import create_optuna_pl_pruning_callback
def create_pl_pruning_callback(*args, **kwargs):
"""Create PyTorchLightning Pruning Callback. Optuna Only."""
return create_optuna_pl_pruning_callback(*args, **kwargs) | 0698e800ed110d430422b7a3fcc72e100ed87658 | 2,275 |
import requests
def get_all_token_volume_by_direction(chain:str, direction:str):
"""
chain: Allowed: ethereum ┃ avalanche ┃ bsc ┃ polygon ┃ arbitrum ┃ fantom ┃ harmony ┃ boba ┃ optimism ┃ moonriver ┃ aurora
direction: Allowed: in ┃ out
"""
chain = chain.lower()
direction = direction.lower()... | be3285e4e4ac65075a98aeb853e68b1b5f6658cb | 2,276 |
def _interactively_fix_missing_variables(project, result):
"""Return True if we need to re-prepare."""
if project.problems:
return False
if not console_utils.stdin_is_interactive():
return False
# We don't ask the user to manually enter CONDA_PREFIX
# (CondaEnvRequirement) because ... | 73393e453043132fc340be10411cb83569becf8c | 2,277 |
def build_node_descr(levels, switch=False):
"""
Produces a node description of the above binary trees
"""
num_parents = sum([2**i for i in range(levels-1)])
parents, children = tee(character_iterator(switch))
next(children)
node_descr = []
for parent_ident in islice(parents, num_parents)... | c682cf5e5946b614563dda31ace76f259df02d47 | 2,278 |
import random
def random_sources(xSize, ySize, zSize, number):
""" returns a list of random positions in the grid where the sources of nutrients (blood vessels) will be """
src = []
for _ in range(number):
x = random.randint(0, xSize-1)
y = random.randint(0, ySize-1)
z = random.ran... | 17dab43ea2468a11e3720ff0f7eb33b605371496 | 2,279 |
import numpy
def sqeuclidean(
x_mat: 'Tensor', y_mat: 'Tensor', device: str = 'cpu'
) -> 'numpy.ndarray':
"""Squared euclidean distance between each row in x_mat and each row in y_mat.
:param x_mat: tensorflow array with ndim=2
:param y_mat: tensorflow array with ndim=2
:param device: the compu... | 3265a062d5a0eece85a3c83e99ad2f9ab27c62cb | 2,280 |
from typing import Optional
def get(*, db_session, tag_id: int) -> Optional[Tag]:
"""Gets a tag by its id."""
return db_session.query(Tag).filter(Tag.id == tag_id).one_or_none() | 752da542eef22ebd977b27c922341690bac2f5ab | 2,281 |
def plot_lines(axes, xdata, ydata, yerrors=None, cdata=None, cmap=None, line_spec='-o', *args, **kwargs):
"""
Plot lines on given matplotlib axes subplot
Uses matplotlib.plot or matplotlib.errorbar if yerrors is not None
:param axes: matplotlib figure or subplot axes, None uses current axes
:param x... | 5c618745ba503a206d594bbac9cbe831d1124625 | 2,282 |
import math
def conv_binary_prevent_overflow(array, structure):
"""
Make sure structure array has great enough positive bitdepth
to be convolved with binary primary array.
Parameters
----------
array : ndarray of bool or int, 2D
Primary integer array to convolve.
Must be a bin... | dd82382c1109e2ce9d15bf0abd563f32b8e8b585 | 2,283 |
def filter_freq_and_csq(mt: hl.MatrixTable, data_type: str, max_freq: float, least_consequence: str):
"""
Filters MatrixTable to include variants that:
1. Have a global AF <= `max_freq`
2. Have a consequence at least as severe as `least_consequence` (based on ordering from CSQ_ORDER)
:param MatrixT... | a20796ccb6fc4db1f93c91f07f5756f390099bee | 2,284 |
def get_regular_intervals(
pre_sfes: list,
post_sfes: list,
pre_keep_flag: bool,
post_keep_flag: bool,
) -> list:
"""
Calculates the intervals for the "regular" egg laying epoch. If pre_keep_flag,
the "regular" epoch is the pre-breakpoint region. If post_keep_flag, the
"regular" epoch is... | 7d92006fc286e3b8c2977c023070388581f192fa | 2,285 |
async def async_setup(hass, config):
"""Platform setup, do nothing."""
if DOMAIN not in config:
return True
hass.async_create_task(
hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_IMPORT}, data=dict(config[DOMAIN])
)
)
return True | be7c81bc7c91251c1c02696d8daa7eaac1f1d326 | 2,286 |
def get_new_bucket(target=None, name=None, headers=None):
"""
Get a bucket that exists and is empty.
Always recreates a bucket from scratch. This is useful to also
reset ACLs and such.
"""
if target is None:
target = targets.main.default
connection = target.connection
if name is... | d46156ee36304b6a13ebd2d467373c7873b8b075 | 2,287 |
def angle_rms(ang, axis=None, period=2*np.pi):
"""returns the rms of angles, uses the property that rms(x)**2 = mean(x)**2 + std(x)**2"""
#rms(x)**2 = mean(x)**2 + std(x)**2
#sqrt(E[X**2]) = E[X]**2 + sqrt(E[(X - E[X])**2])
m,s = angle_mean_std(ang,axis,period)
return np.hypot(m, s) | 5b2c8fc865762b7856fc6a8c68e901dbf367690d | 2,288 |
import functools
def check_units(*units_by_pos, **units_by_name):
"""Create a decorator to check units of function arguments."""
def dec(func):
# Match the signature of the function to the arguments given to the decorator
sig = signature(func)
bound_units = sig.bind_partial(*units_by_p... | b7bd0c78d1339032a442c4e3a354cc1fa9e804b2 | 2,289 |
def check_nifti_dim(fname, data, dim=4):
"""
Remove extra dimensions.
Parameters
----------
fname : str
The name of the file representing `data`
data : np.ndarray
The data which dimensionality needs to be checked
dim : int, optional
The amount of dimensions expected/... | 0f814cc3eaca7242bf3393a1e749df5ebe7b128a | 2,290 |
def bar_chart(x_data=None, y_data=None, title="Chart Title", x_label=None, y_label=None,
color="blue", figsize=(10,5)):
"""
This function requires two Pandas data series for x and y data.
Optionally: the x label, y label, color, title, and size may be set.
This function returns a bar ch... | 23b8d0c1a50ec4909d8b46c29ac75a483b2e221c | 2,291 |
def get_qtobject_for_uipath(pathstr):
""" Returns the QtObject for a Maya UI path.
Ensure that the path starts from the Maya main window and that there are no \
empty elements in it as this will fail.
"""
split_pathstr = pathstr.split("|")
return _find_qobject(get_maya_main_window(), split_paths... | fc39ffe792a25af33663c7843a934045df4a91b0 | 2,292 |
def parse_study_with_run(soup):
"""Given a BeautifulSoup object representing a study, parse out relevant
information.
:param soup: a BeautifulSoup object representing a study
:type soup: bs4.BeautifulSoup
:return: a dictionary containing study information and run information
:rtype: dict
"... | 44405ed14b67c03a44fef876d3d9ed5afc703489 | 2,293 |
def create_embed(**kwargs) -> Embed:
"""Creates a discord embed object."""
embed_type = kwargs.get('type', Embed.Empty)
title = kwargs.get('title', Embed.Empty)
description = kwargs.get('description', Embed.Empty)
color = kwargs.get('color', get_default_color())
timestamp = kwargs.get('timestamp... | 4396d03eab15ccc05ceff7cc8cfcd1b93e85894a | 2,294 |
from typing import List
import time
import os
import pkgutil
import importlib
def validate_commit(commit: Commit, out_errors: List[str] = None, ignore_validators: List[str] = None) -> bool:
"""Validates a commit against all validators
:param commit: The commit to validate
:param out_errors: if not None, ... | 6d02bef635b7100b66ba74cf7bc2b62d71d6607c | 2,295 |
from typing import Any
from typing import List
from typing import Dict
def _safe_types(
*, test_data: Any, cached_data: Any, key_rules: List[KeyRule],
) -> Dict:
"""Convert data and key_rules to safe data types for diffing.
Args:
test_data: data to compare
cached_data: data to compare
... | bf44aa091fcc751247fbc4ae92e826746c226cfc | 2,296 |
def _flatten_output(attr_dict, skip: list=[]):
"""
flaten output dict node
node_collection is a list to accumulate the nodes that not unfolded
:param skip: is a list of keys (format with parent_key.key) of Dict name that
will not collected into the json file.
For output nodes not being ex... | 75e2f41440b819ba939eb1e12c36a9ff6d894708 | 2,297 |
def get_tpu_estimator(
working_dir,
model_fn,
iterations_per_loop=320,
keep_checkpoint_max=20,
use_tpu=False,
train_batch_size=64):
"""Obtain an TPU estimator from a directory.
Args:
working_dir: the directory for holding checkpoints.
model_fn: an estimator model function.
iter... | 33f78f97aba4011fd8f637ff71a64e8716d5713a | 2,298 |
def rho_err(coeffs, rho, z, density_func):
"""
Returns the difference between the estimated and actual data
"""
soln = density_func(z, coeffs)
return rho - soln | 4a2d7c7243cad062d8568ab72599b4d8be26f874 | 2,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.