content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import OrderedDict
async def bulkget(ip, community, scalar_oids, repeating_oids, max_list_size=1,
port=161, timeout=DEFAULT_TIMEOUT):
# type: (str, str, List[str], List[str], int, int, int) -> BulkResult
"""
Delegates to :py:func:`~puresnmp.aio.api.raw.bulkget` but returns si... | 6795f7d9ff7ac1952406922395e2308346ff244d | 3,645,600 |
def repo_version_db_key() -> bytes:
"""The db formated key which version information can be accessed at
Returns
-------
bytes
db formatted key to use to get/set the repository software version.
"""
db_key = c.K_VERSION.encode()
return db_key | 090a70e59d1a2c7d4a3f4589b9f4a2ef975e2585 | 3,645,601 |
def retrieve_psd_cdf(path):
"""interact with hdf5 file format for marginal CDFs for a set of PSDs"""
with h5py.File(path, 'r') as obj:
group = obj['PSD_CDF']
Npsd = group.attrs['num_psds']
freqs = group['frequencies'][...]
data = group['CDFs'][...]
vals = data[:,0,:]
cdf... | f0ee184d972ddcbedeb94345f15fcab9d08e8458 | 3,645,602 |
def get(context: mgp.ProcCtx) -> mgp.Record(tracks=list):
"""Returns a list of track_ids of trendy songs.
Calculates recently popular tracks by comparing the
popularity of songs using the `followers`, `created_at`,
and proximity to other popular songs (pagerank).
Example usage:
CALL trendy_... | 182d8a3d26028f472f1cc64bd993b6a29635daf5 | 3,645,603 |
import ipaddress
def ip_only(value):
"""
Returns only the IP address string of the value provided. The value could be either an IP address,
and IP network or and IP interface as defined by the ipaddress module.
Parameters
----------
value : str
The value to use
Returns
-----... | 149b202969c0ccb4e0c5e55417ce0231f1b5fc11 | 3,645,604 |
import logging
def GetAuth1Token():
"""Returns an Auth1Token for use with server authentication."""
if AUTH1_TOKEN:
return AUTH1_TOKEN
if not OBJC_OK:
logging.error('Objective-C bindings not available.')
return None
pref_value = Foundation.CFPreferencesCopyAppValue(
'AdditionalHttpHeaders'... | 70134cb639e5bc1021fd04ee2524592681a5b04b | 3,645,605 |
import os
def TemplateInputFilename(context):
"""Build template file name from config."""
if args.templatedir:
filename = config_lib.CONFIG.Get("PyInstaller.template_filename",
context=context)
return os.path.join(args.templatedir, filename)
return None | 4a132a5a74d96414c63aa0b6113ebb07f3d46d4b | 3,645,606 |
from typing import Tuple
from datetime import datetime
from typing import Optional
def get_data_by_isin(isin: str, dates: Tuple[datetime.date], is_etf: bool) -> Tuple[Optional[np.ndarray], str]:
"""Retrieves stock/ETF prices in EUR by ISIN for the given dates. Cached to make sure this is only queried once for
... | d4d46b45f480488fb67d3a6116a3b2e90c736efc | 3,645,607 |
from typing import Dict
from typing import Any
def get_result_qiskit() -> Dict[str, Dict[str, Any]]:
"""Fixture for returning sample experiment result
Returns
-------
Dict[str, Dict[str, Any]]
A dictionary of results for physics simulation and perfect gates
A result dictionary... | 7dc44fe110687b92f5e8b23c24798b06dd19e71e | 3,645,608 |
def all_budgets_for_student(user_id):
"""Returns a queryset for all budgets that a student can view/edit
i.e. is the submitter, president, or treasurer for any of the organization's budgets"""
query = Q(budget__submitter=user_id) | Q(budget__president_crsid=user_id) | Q(budget__treasurer_crsid=user_id)
... | 2048f2b579c2e8903ca34c34990e9c2c5215f79c | 3,645,609 |
import subprocess
import sys
import errno
def exec_process(cmdline, silent=True, catch_enoent=True, input=None, **kwargs):
"""Execute a subprocess and returns the returncode, stdout buffer and stderr buffer.
Optionally prints stdout and stderr while running."""
try:
sub = subprocess.Popen(args=cmd... | 30d81dd2cac035902bdd800d1205bcadce4421b5 | 3,645,610 |
import torch
def uniform_weights(x, x_mask):
"""Return uniform weights over non-masked x (a sequence of vectors).
Args:
x: batch * len * hdim
x_mask: batch * len (1 for padding, 0 for true)
Output:
x_avg: batch * hdim
"""
alpha = Variable(torch.ones(x.size(0), x.size(1)))
... | a1b88fc88ac65886283159d077e9550dab95c8de | 3,645,611 |
from operator import inv
def mixed_estimator_2(T1, T2, verbose=False):
"""
Based on the Lavancier and Rochet (2016) article.
The method combines two series of estimates of the same quantity taking into account their correlations. The individual measureements are assumed independent. The current implement... | 8f9ee282b0756dd41ff98e9ae596e46ddf6947a3 | 3,645,612 |
def e_add_const(pub, a, n):
"""Add constant n to an encrypted integer"""
return a * modpow(pub.g, n, pub.n_sq) % pub.n_sq | 37be82c71da3114f94d8b2ebe08f54a0726ec655 | 3,645,613 |
def area_triangle(base, height):
"""
"""
return (base * height) / 2.0 | 474e1a090dc7af9d68eaab35e6b04e5e165b6777 | 3,645,614 |
def _getAtomInvariantsWithRadius(mol, radius):
""" Helper function to calculate the atom invariants for each atom
with a given radius
Arguments:
- mol: the molecule of interest
- radius: the radius for the Morgan fingerprint
Return: list of atom invariants
"""
inv = []
for i ... | 8b8565a62af7f94c79604342077918a5b4261410 | 3,645,615 |
import argparse
def build_argparser():
"""Construct an argument parser for the ``translate_header.py`` script.
Returns
-------
argparser : `argparse.ArgumentParser`
The argument parser that defines the ``translate_header.py``
command-line interface.
"""
parser = argparse.Argu... | ec054012455a7fc0f6559d01f69e5a3b71cb346c | 3,645,616 |
def radcool(temp, zmetal):
""" Cooling Function
This version redefines Lambda_sd
(rho/m_p)^2 Lambda(T,z) is the cooling in erg/cm^3 s
Args:
temp : temperature in the unit of K
zmetal: metallicity in the unit of solar metallicity
Return:
in the unit of erg*s*cm^3
"""
... | 720ed6625c9fe348ebe78aa80127c4bcc4e911a9 | 3,645,617 |
def L_model_forward(X, parameters):
"""
Implement forward propagation for the [LINEAR->RELU]*(L-1)->LINEAR->SIGMOID computation
Arguments:
X -- data, numpy array of shape (input size, number of examples)
parameters -- output of initialize_parameters_deep()
Returns:
AL -- last post-... | b086f172e1fc0d8dad2353af1b35a8f6bd3f13dc | 3,645,618 |
def linalg_multiply(a):
"""
Multiple all elements in vector or matrix
Parameters:
* a (array or matrix): The input to multiply
Return (number): The product of all elements
"""
return np.prod(a) | bac2457c61813cb5d662cef37fb2b48d8e65ba34 | 3,645,619 |
def lambda_handler(event, context):
"""
This method selects 10% of the input manifest as validation and creates an s3 file containing the validation objects.
"""
label_attribute_name = event['LabelAttributeName']
meta_data = event['meta_data']
s3_input_uri = meta_data['IntermediateManifestS3Uri'... | f6e0313155a47110e47567320e03e241bb6dde37 | 3,645,620 |
def get_table_6():
"""表 6 蓄熱の採用の可否
Args:
Returns:
list: 表 6 蓄熱の採用の可否
"""
table_6 = [
('不可', '不可', '可', '可', '可'),
('不可', '不可', '可', '可', '可'),
('不可', '不可', '可', '可', '可'),
('不可', '不可', '可', '可', '可'),
('不可', '不可', '可', '可', '可'),
('不可', '不可',... | 4ecd4526ed9ce67b7a5d22b67dd804059807e94d | 3,645,621 |
import random
def is_prime(number, num_trials=200):
"""Determines whether a number is prime.
Runs the Miller-Rabin probabilistic primality test many times on the given number.
Args:
number (int): Number to perform primality test on.
num_trials (int): Number of times to perform the Miller... | 78478437c08bcbd5e4c690466e4fe51bb4fad5ce | 3,645,622 |
def extract_labels(filenames):
"""
Extract class labels of the images from image path list.
# Arguments
filenames: List of paths to image file.
# Returns
List of image labels.
"""
return LabelEncoder().fit_transform([extract_label(filename) for filename in filenames]) | 53f708a0abb105d3ffce0202117b6eae812a9ede | 3,645,623 |
def reverseList(head):
"""
:type head: ListNode
:rtype: ListNode
"""
current = head;
# temp is first
counter = 0;
flag = 'Y';
while current is not None and flag != 'N':
# store the current element
# print(f"Current: {current... | 06f07ad9c5dbb13d2e288ea2ff14ef31febf87b9 | 3,645,624 |
def validate(data: BuildParams):
"""
Makes sure a valid combination of params have been provided.
"""
git_repo = bool(data.source.git_repo)
dockerfile = bool(data.source.dockerfile)
build_context = bool(data.source.build_context)
git_valid = git_repo and not dockerfile and not build_context
... | 708335092018339aa4f64b58d5ec8d2cb09751c3 | 3,645,625 |
import pickle
def load_model(filepath=FILEPATH) -> TrainingParams:
"""
Load
:param filepath:
:return:
"""
with open(filepath, "rb") as handler:
model = pickle.load(handler)
return model | f2a1ed631bdb7b1f7e6fd372ca604ef4ef6890f2 | 3,645,626 |
def is_symmetric(m):
"""Check if a sparse matrix is symmetric
https://mail.python.org/pipermail/scipy-dev/2014-October/020117.html
Parameters
----------
m : sparse matrix
Returns
-------
check : bool
"""
if m.shape[0] != m.shape[1]:
raise Valu... | 84523c1c4bf0120025d6e7a0bcc9cf2e489b1ae8 | 3,645,627 |
from pathlib import Path
from typing import List
import os
def get_proj_libdirs(proj_dir: Path) -> List[str]:
"""
This function finds the library directories
"""
proj_libdir = os.environ.get("PROJ_LIBDIR")
libdirs = []
if proj_libdir is None:
libdir_search_paths = (proj_dir / "lib", pr... | efeacd08940c1f8706cd86aa0c5da50b498608e6 | 3,645,628 |
def render_raster_map(bounds, scale, basemap_image, aoi_image, id, path, colors):
"""Render raster dataset map based on bounds. Merge this over basemap image
and under aoi_image.
Parameters
----------
bounds : list-like of [xmin, ymin, xmax, ymax]
bounds of map
scale : dict
map... | f24c3b48911c7c322d3c02e9808f0013354c567d | 3,645,629 |
def str2num(s):
"""Convert string to int or float number.
Parameters
----------
s : string
String representing a number.
Returns
-------
Number (int or float)
Raises
------
TypeError
If `s` is not a string.
ValueError
If the string does ... | 5dfaed567a66fc7d3ee46cbb70d9c408d38fcbfe | 3,645,630 |
import os
def get_html_templates_path():
"""
Return path to ABlog templates folder.
"""
pkgdir = os.path.abspath(os.path.dirname(__file__))
return os.path.join(pkgdir, "templates") | e72caf4a2558298ec909aff04bfde381abba256f | 3,645,631 |
def new_log(infile_history=None, extra_notes=None, git_repo=None):
"""Create a new command line log/history.
Kwargs:
infile_history (dict): keys are input file names and values are the logs for those files
extra_notes (list): List containing strings of extra information (output is one list item p... | f1bbf4b9c84442d7abf700fec98277eb9e2283ea | 3,645,632 |
from typing import OrderedDict
import inspect
def _get_new_args_dict(func, args, kwargs):
"""Build one dict from args, kwargs and function default args
The function signature is used to build one joint dict from args and kwargs and
additional from the default arguments found in the function signature. Th... | ad7553e7b778b8f7b499217c7ee4ad7328958809 | 3,645,633 |
def hellinger_funct(x,P,Q):
"""
P,Q should be numpy stats gkde objects
"""
return np.sqrt(P(x) * Q(x)) | 198f0cf72ef75cece3c59248d8cd1215fa4299a1 | 3,645,634 |
import os
def clean_collection(collection):
"""Iterates through the images in the Collection and remove those that don't exist
on disk anymore
"""
images = collection.images()
number_purged = 0
for image in images:
if not os.path.isfile(image.get_filepath()):
logger.info('R... | ce4162ef6fe4670b7666e6f84b4de9b9cb01e91b | 3,645,635 |
from datetime import datetime
def human_date(date):
""" Return a string containing a nice human readable date/time.
Miss out the year if it's this year
"""
today = datetime.datetime.today()
if today.year == date.year:
return date.strftime("%b %d, %I:%M%P")
return date.strftime("%... | 7088617b58c0d3b3193e11885fcd7b7ef075f627 | 3,645,636 |
def compute_thickness(wmP, kdTreegm, kdTreewm):
"""
This function..
:param wmP:
:param kdTreegm:
:param kdTreewm:
:return:
"""
# Find the closest point to the gray matter surface point
gmIndex = kdTreegm.FindClosestPoint(wmP)
gmP = kdTreegm.GetDataSet().GetPoint(gmIndex)
# c... | c2c13a8c17eb997843c9e5752c6ae05f0854a7e5 | 3,645,637 |
import sys
def sync(args):
"""Synchronize your local repository with the manifest and the real world.
This includes:
- ensures that all projects are cloned
- ensures that they have the correct remotes set up
- fetches from the remotes
- checks out the correct tracking branches
- if the local b... | c7cac9892d00b91f2f812c0ec20fc33fbe06308e | 3,645,638 |
def cytoband_interval():
"""Create test fixture for Cytoband Interval."""
return CytobandInterval(
start="q13.32", end="q13.32"
) | d052e2dcf7276dc24c680d0b1168ebea6f779eac | 3,645,639 |
def _get_proxy_class(request):
""" Return a class that is a subclass of the requests class. """
cls = request.__class__
if cls not in _proxy_classes:
class RequestProxy(cls):
def __init__(self, request):
self.__dict__ = request.__dict__
self.__request = re... | 72113c9d38bdf91650fa88d4297a25457f34b9f8 | 3,645,640 |
import csv
def rebuilt_emoji_dictionaries(filename):
"""
Rebuilds emoji dictionaries, given a csv file with labeled emoji's.
"""
emoji2unicode_name, emoji2sentiment = {}, {}
with open(filename) as csvin:
for emoji in csv.DictReader(csvin):
for key, value in emoji.items():
... | 69bf1438a524ea54bd7bef2d4537a0c61cd0bc3d | 3,645,641 |
def send_message(receiver, message):
"""
Send message to receivers using the Twilio account.
:param receiver: Number of Receivers
:param message: Message to be Sent
:return: Sends the Message
"""
message = client.messages.create(
from_="whatsapp:+14155238886", body=message, to=f"what... | 05022f40104d8b38ffe096ee01941ef04da5f076 | 3,645,642 |
def stem_list(tokens: list) -> list:
"""Stems all tokens in a given list
Arguments:
- tokens: List of tokens
Returns:
List of stemmed tokens
"""
stem = PorterStemmer().stem
return [stem(t) for t in tokens] | 6086bda0bce5ce042156a12617a2c09b4b8f9cc8 | 3,645,643 |
def unique(s):
"""Return a list of the elements in s, but without duplicates.
For example, unique([1,2,3,1,2,3]) is some permutation of [1,2,3],
unique("abcabc") some permutation of ["a", "b", "c"], and
unique(([1, 2], [2, 3], [1, 2])) some permutation of
[[2, 3], [1, 2]].
For best speed... | 055d2d6e748e1a4ee22057fcd3e73d4e8c8e8081 | 3,645,644 |
import subprocess
def execute(command: str, cwd: str = None, env: dict = None) -> str:
"""Executes a command and returns the stdout from it"""
result = subprocess.run(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=cwd,
env=env,
shell=True,
... | abda75f0e24f619ea35126ae3cdf8b8271e755f4 | 3,645,645 |
def get_ground_truth_assignments_for_zacharys_karate_club() -> jnp.ndarray:
"""Returns ground truth assignments for Zachary's karate club."""
return jnp.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1,
0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]) | fc2050072293d9857b50425a4f31137a0872096d | 3,645,646 |
import os
def read_frames_from_dir(_dir, _type='png'):
""" Read frames from the dir, and return list """
paths = os.listdir(_dir)
valid_paths = []
for path in paths:
if _type in path: valid_paths.append(path)
valid_paths = ns.natsorted(valid_paths)
frames = []
for path in valid_paths:
frames.append( np.arr... | e5e94498ec53b2099c9aa4645d34f410626d6044 | 3,645,647 |
from typing import List
from typing import Tuple
def sort_places_versus_distance_from_coordinates(
list_places: List[Place], gps_coord: Tuple[float, float]
) -> List[Place]:
"""Oder list of places according to the distance to a reference coordinates.
Note: this helper is compensating the bad results of t... | 3089503406bf0959dd1caac5746693f812eb449c | 3,645,648 |
from typing import List
from typing import Tuple
def solve_part2_coordinate_subdivision(boxes: List[Tuple[str, Box]]) -> int:
""" An alternative method to solve part 2 which uses coordinate subdivisions to make a new grid.
On the puzzle input, this is roughly a 800x800x800 grid, which actually takes some time... | 5a283b0de558755f7ec95ff9cde091ca95b245de | 3,645,649 |
def decodeSignal(y, t, fclk, nbits) :
"""
This file reads in digitized voltages outputted from the
QCM Antenna Master Controller Board and outputs time,logic code number
pairs.
The encoding scheme is as follows:
HEADER: 3 clock cycles HIGH, followed by 3 clock cycles LOW
SIGNAL: 1 clock cycle LOW, followed by 1... | 72b812267e172ee245cb5c7f59366105baad40dc | 3,645,650 |
def sqrt_price_to_tick(sqrt_price):
"""
TODO: finish documentation
See formula 6.8 in the white paper.
We use the change of base formula to compute the log as numpy doesn't have
a log function with an arbitrary base.
:param sqrt_price:
:return:
"""
base = np.sqrt(1.0001)
return... | 8c57f7918d656c982e8c34e3b6952f724ab2dc18 | 3,645,651 |
import logging
def getStateName(responseText: str) -> str:
"""Parse state name in title field.
Args:
responseText: response.text object from requests.
Returns: State string name.
"""
soup = Soup(responseText, "html.parser")
logging.debug("Ingesting soup: %s", soup.prettify())
if ... | 3e28c9a68cb116ad5faa36bf1b4b41e00284e477 | 3,645,652 |
def find_dead_blocks(func, cfg):
"""Find all immediate dead blocks"""
return [block for block in cfg if not cfg.predecessors(block)
if block != func.startblock] | 3f72e0a573b1ef617511f2b9ec3d2e30c7ba6554 | 3,645,653 |
def _mcse_sd(ary):
"""Compute the Markov Chain sd error."""
_numba_flag = Numba.numba_flag
ary = np.asarray(ary)
if _not_valid(ary, shape_kwargs=dict(min_draws=4, min_chains=1)):
return np.nan
ess = _ess_sd(ary)
if _numba_flag:
sd = np.float(_sqrt(svar(np.ravel(ary), ddof=1), np.... | 4fcf966b7ec98cad193418f7e623c96154646b5f | 3,645,654 |
def dfs_predecessors(G, source=None):
"""Return dictionary of predecessors in depth-first-search from source."""
return dict((t,s) for s,t in dfs_edges(G,source=source)) | 6929d25c981fec9b932c0f978b1ee45f37e0e565 | 3,645,655 |
def merge_all_sections(prnt_sctns, child_sctns, merge_within_sections=False):
""" Merge the doc-sections of the parent's and child's attribute into a single docstring.
Parameters
----------
prnt_sctns: OrderedDict[str, Union[None,str]]
child_sctns: OrderedDict[str, Union[None,str]]
Returns
... | c692d1b08db1a49545eb39e6385040fafc10e149 | 3,645,656 |
def input_fn(is_training, data_dir, batch_size, num_epochs=1):
"""Input_fn using the tf.data input pipeline for CIFAR-10 dataset.
Args:
is_training: A boolean denoting whether the input is for training.
data_dir: The directory containing the input data.
batch_size: The number of samples per batch.
... | 94875b205df2d67993dd658f33fbf3be917cf701 | 3,645,657 |
from typing import List
def _eye(sys: brax.System, qp: brax.QP) -> List[float]:
"""Determines the camera location for a Brax system."""
d = {}
for joint in sys.config.joints:
if joint.parent not in d:
d[joint.parent] = []
po, co = joint.parent_offset, joint.child_offset
off = onp.array([po.x, ... | 22eb7a1ffbd2aed810e19e842eaf9ab648a2b83b | 3,645,658 |
def num_list(to_parse):
"""
Creates list from its string representation
Arguments:
to_parse {string} -- String representation of list, can include 'None' or internal lists, represented by separation with '#'
Returns:
list[int] -- List represented in to_parse
"""
if len(... | b444554e37434b5ae42ebc913bcc0f9b99c65ce9 | 3,645,659 |
import torch
import os
def main():
"""Main."""
torch.manual_seed(args.seed)
# Experiment Information
print_experiment_info(args)
dataloaders, G, optimizer_g, writer = train_setup(args)
optimizer_g, lr = lr_scheduler_withoutDecay(optimizer_g, lr=args.lr)
# scheduler_g = optim.lr_scheduler... | aa042529b8903ac800824e82b1f06c7480da2107 | 3,645,660 |
def total_scatter_matrix(data):
"""
Total sum of square (TSS) : sum of squared distances of points around the baycentre
References : Clustering Indices, Bernard Desgraupes (April 2013)
"""
X = np.array(data.T.copy(), dtype=np.float64)
for feature_i in range(data.shape[1]):
X[feature_i] ... | 829bfdbf838d087517465e7173e480796e52cf8e | 3,645,661 |
def save_camera_zip(camera_id, year, month, file_path=None):
"""
Download a camera ZIP archive.
:param camera_id: int, camera ID
:param year: int, year
:param month: int, month
:param file_path: str, optional, path to save file
:return: bool, status of download
"""
# Setup file name... | 41e4ef0f5f412850266de2d136da719adae08e04 | 3,645,662 |
def read_user(str):
""" str -> dict """
pieces = str.split()
return {
'first': pieces[0],
'last': pieces[1],
'username': pieces[5],
'custID': pieces[3],
'password': pieces[7],
'rank': 0,
'total': 0
} | fcb24a2b791f0df8f40ea4080cdabe83d51fe068 | 3,645,663 |
import calendar
def lweekdate(weekday, year, month, nextDay=0):
"""
Usage
lastDate = lweekdate(weekday, year, month, nextDay)
Notes
Date of last occurrence of weekday in month
returns the serial date number for the last occurrence of Weekday in the given
year and month and in a week that also contains ... | 60367db7223f104260e2b7d757b367d6388d222b | 3,645,664 |
def multi_polygon_gdf(basic_polygon):
"""
A GeoDataFrame containing the basic polygon geometry.
Returns
-------
GeoDataFrame containing the basic_polygon polygon.
"""
poly_a = Polygon([(3, 5), (2, 3.25), (5.25, 6), (2.25, 2), (2, 2)])
gdf = gpd.GeoDataFrame(
[1, 2],
geome... | 9acfa76ca3a51603d96e1388dc7c7a1178ec3fa1 | 3,645,665 |
import traceback
def get_or_create_pull(github_repo, title, body, head, base, *, none_if_no_commit=False):
"""Try to create the PR. If the PR exists, try to find it instead. Raises otherwise.
You should always use the complete head syntax "org:branch", since the syntax is required
in case of listing.
... | 3968fc99c006c45e20eabce1329d95247ad855c8 | 3,645,666 |
import json
from typing import OrderedDict
def get_board_properties(board, board_path):
"""parses the board file returns the properties of the board specified"""
with open(helper.linux_path(board_path)) as f:
board_data = json.load(f, object_pairs_hook=OrderedDict)
return board_data[board] | e5fa5542c540c643ecf8b57314e227d14e193a56 | 3,645,667 |
import re
def parse_command(command):
"""
Parse the given one-line QF command analogously to parse_file().
"""
m = re.match(r'^\#?([bdpq]|build|dig|place|query)\s+(.+)', command)
if m is None:
raise ParametersError("Invalid command format '%s'." % command)
# set up details dict
d... | 05f0e12b413b3e26f2c73734e3d6e8f10d124c0d | 3,645,668 |
from typing import Union
from typing import List
import shlex
import subprocess
def _run(cmd: Union[str, List[str]]) -> List[str]:
"""Run a 'cmd', returning stdout as a list of strings."""
cmd_list = shlex.split(cmd) if type(cmd) == str else cmd
result = subprocess.run(cmd_list, capture_output=True)
... | 74fc47f531e8eef9f77b80798f0b5505b57968da | 3,645,669 |
def get_repository_username(repo_url):
"""
Returns the repository username
:return: (str) Repository owner username
"""
repo_path = _get_repo_path(repo_url)
return repo_path[0] | 008e67435c11e4fbb12ca19149e795dd50c12526 | 3,645,670 |
from IPython.config import Application
import logging
def get_logger():
"""Grab the global logger instance.
If a global IPython Application is instantiated, grab its logger.
Otherwise, grab the root logger.
"""
global _logger
if _logger is None:
if Application.initialized():
... | 717487ac1c94c09ab7831e405255283aea4570a5 | 3,645,671 |
def process_y(y_train: pd.Series, max_mult=20, large_sampsize=50000):
"""
Drop missing values, downsample the negative class
if sample size is large and there is significant class imbalance
"""
# Remove missing labels
ytr = y_train.dropna()
# The code below assumes the negative class is ove... | 2f36ba3bce93d47f944784f83fd731b9aa315acc | 3,645,672 |
def _distance(y1, y2):
"""1D distance calculator"""
inner = (y2 - y1) ** 2
d = np.sqrt(inner)
return d | 696c5ccbe720301d22d9b142e9a5d5f3c507b738 | 3,645,673 |
def create_container(context, values):
"""Create a new container.
:param context: The security context
:param values: A dict containing several items used to identify
and track the container, and several dicts which are
passed
into the Drivers when m... | b9047467a0a96c1b08bc92b4e74399e0a413ba45 | 3,645,674 |
from google.protobuf.json_format import MessageToDict
from typing import Callable
from typing import Dict
def build_model_from_pb(name: str, pb_model: Callable):
"""
Build model from protobuf message.
:param name: Name of the model.
:param pb_model: protobuf message.
:return: Model.
"""
... | a1de965b13b6cbbe33a08a52561f699042dd93f8 | 3,645,675 |
def create_proof_of_time_pietrzak(discriminant, x, iterations, int_size_bits):
"""
Returns a serialized proof blob.
"""
delta = 8
powers_to_calculate = proof_pietrzak.cache_indeces_for_count(iterations)
powers = iterate_squarings(x, powers_to_calculate)
y = powers[iterations]
proof = pr... | d31ac6eadcc3ce155d682e2cef4b392561a1412b | 3,645,676 |
def resample_dataset ( fname, x_factor, y_factor, method="mean", \
data_min=-1000, data_max=10000 ):
"""This function resamples a GDAL dataset (single band) by a factor of
(``x_factor``, ``y_factor``) in x and y. By default, the only method used
is to calculate the mean. The ``data_min`` and ``d... | f32465711d7dae3a8e7350676cb0e90f084bf5c5 | 3,645,677 |
def int2bytes(number, fill_size=None, chunk_size=None, overflow=False):
"""
Convert an unsigned integer to bytes (base-256 representation)::
Does not preserve leading zeros if you don't specify a chunk size or
fill size.
.. NOTE:
You must not specify both fill_size and chunk_size. Only one... | 091764ffeb9a15036b484380750f04496db36da1 | 3,645,678 |
def compFirstFivePowOf2(iset={0, 1, 2, 3, 4}):
"""
task 0.5.6
a comprehension over the given set whose value is the set consisting
of the first five powers of two, starting with 2**0
"""
return {2**x for x in iset} | a7b04ab6b127ef5ee7fdd3598b1569e171fd009e | 3,645,679 |
import types
import pandas
def sdc_pandas_dataframe_getitem(self, idx):
"""
Intel Scalable Dataframe Compiler User Guide
********************************************
Pandas API: pandas.DataFrame.getitem
Get data from a DataFrame by indexer.
Limitations
-----------
Supported ``key`` c... | 90b335db7327da883561665909a2b335437efc83 | 3,645,680 |
def display_finds_meta(r):
"""A list of urls in r is displayed as HTML"""
rows = ["<tr><td><img src='{row}'</td><td><a href = {meta} target='_'>{meta}</a></td></tr>".format(row=row, meta=row) for row in r]
return HTML("""<html><head></head>
<body>
<table>
{rows}
</table>
</body>
... | bd769bc4b0b6d4d55ec721e02c623f30d5eb5e1f | 3,645,681 |
def __pairwise__(iterable):
""" Converts a list of elements in a list of pairs like:
list -> (list[0], list[1]), (list[2], list[3]), (list[4], list[5]), ...
:param iterable: Input list.
:return: List of pairs of the given list elements.
"""
a = iter(iterable)
return zip(a, a) | 59eae23e0e6f9ccba528f9632caf77fe28698c5b | 3,645,682 |
def _generateTriangleSequence():
"""
Generates list of elements following sequence of triangle numbers.
Returns:
sequenceElements - List of elements following the sequence.
"""
sequenceElements = []
totalCharactersInNewSequence = 0
total = 1
currentAddend = 2
while totalCharac... | 453b5e672a4817281f5e4ba51ca3ea426fcdb3d2 | 3,645,683 |
import math
def normalize_neurons_range(neurons, standard_diagonal_line: int or float):
"""
:param neurons: should be refined.
:param standard_diagonal_line: pre-defined standard length of diagonal line of xoy plate
:return: neurons, width_scale, [width_span, height_span, z_span]
width_s... | 1709b68054aa10ccd9d065b04d809e2df4d3a8e2 | 3,645,684 |
def distort_image(image):
"""Perform random distortions to the given 4D image and return result"""
# Switch to 3D as that's what these operations require
slices = tf.unpack(image)
output = []
# Perform pixel-wise distortions
for image in slices:
image = tf.image.random_flip_left_right... | 70db49a2a3dfe31c0b511824342a95ad5da30430 | 3,645,685 |
from io import StringIO
def tablebyname(filehandle, header):
"""fast extraction of the table using the header to identify the table
This function reads only one table from the HTML file. This is in contrast to `results.readhtml.titletable` that will read all the tables into memory and allows you to interacti... | ba1c228843f631b0441fc69c66b0d9ae7acbf813 | 3,645,686 |
def BuildDataset():
"""Create the dataset"""
# Get the dataset keeping the first two features
iris = load_iris()
x = iris["data"][:,:2]
y = iris["target"]
# Standardize and keep only classes 0 and 1
x = (x - x.mean(axis=0)) / x.std(axis=0)
i0 = np.where(y == 0)[0]
i1 = np.where(y... | f6b3cc216262899880f048dd6d4823596d111c1a | 3,645,687 |
def read_tile(file, config):
"""Read a codex-specific 5D image tile"""
# When saving tiles in ImageJ compatible format, any unit length
# dimensions are lost so when reading them back out, it is simplest
# to conform to 5D convention by reshaping if necessary
slices = [None if dim == 1 else slice(No... | 3e0e61d8fa5ac497377c02c90a03bcbd176752ab | 3,645,688 |
def rmsd(V, W):
""" Calculate Root-mean-square deviation from two sets of vectors V and W. """
D = len(V[0])
N = len(V)
rmsd = 0.0
for v, w in zip(V, W):
rmsd += sum([(v[i] - w[i]) ** 2.0 for i in range(D)])
return np.sqrt(rmsd / N) | dc537f1cc742f7c4c5231af4c45d470e582be623 | 3,645,689 |
from re import L
def partition(f, xs):
"""
partition :: (a -> Bool) -> [a] -> ([a], [a])
The partition function takes a predicate a list and returns the pair of
lists of elements which do and do not satisfy the predicate.
"""
yes, no = [], []
for item in xs:
if f(item):
... | 7fde3557fa9d1e3bdf232885dda360a6695dabc0 | 3,645,690 |
from math import exp, pi, sin
def bvp2_check():
"""
Using scikits.bvp_solver to solve the bvp
y'' + y' + sin y = 0, y(0) = y(2*pi) = 0
y0 = y, y1 = y'
y0' = y1, y1' = y'' = -sin(y0) - y1
"""
lbc, rbc = .1, .1
def function1(x , y):
return np.array([y[1] , -sin(y[0]) -y[1] ])
def boundary_conditions(... | 6fe48b76945d3c322c21938049ab74099d022c7d | 3,645,691 |
import zarr
def get_zarr_store(file_path):
"""Get the storage type
"""
ZARR_STORE_MAP = {"lmdb": zarr.LMDBStore,
"zip": zarr.ZipStore,
"dbm": zarr.DBMStore,
"default": zarr.DirectoryStore}
suffix, subsuffix = get_subsuffix(file_path)
... | ecc17168d56bd9cc725a2db51914cddd098aa1af | 3,645,692 |
def convert_string(inpt):
"""Return string value from input lit_input
>>> convert_string(1)
'1'
"""
if PY2:
return str(inpt).decode()
else:
return str(inpt) | a88ee436726a6587e673fb71673c771851b83cea | 3,645,693 |
def get_ipc_kernel(imdark, tint, boxsize=5, nchans=4, bg_remove=True,
hotcut=[5000,50000], calc_ppc=False,
same_scan_direction=False, reverse_scan_direction=False):
""" Derive IPC/PPC Convolution Kernels
Find the IPC and PPC kernels used to convolve detector pixel data... | 4646ccc138d7f625941e9bc43382e1c5ef57e5c5 | 3,645,694 |
from datetime import datetime
def get_description():
""" Return a dict describing how to call this plotter """
desc = dict()
desc['data'] = True
desc['cache'] = 86400
desc['description'] = """This plot presents the trailing X number of days
temperature or precipitation departure from long term... | 04d19dde79c25bfc3cc606cd1a2b09ecd8a6408b | 3,645,695 |
def SpringH(z,m,k):
""" with shapes (bs,2nd)"""
D = z.shape[-1] # of ODE dims, 2*num_particles*space_dim
q = z[:,:D//2].reshape(*m.shape,-1)
p = z[:,D//2:].reshape(*m.shape,-1)
return EuclideanK(p,m) + SpringV(q,k) | 0895d44933a0390a65da42d596fcf1e822f0f93c | 3,645,696 |
def write_sushi_input_files(lhafile):
""" Add SusHi-related blocks to LHA file """
outfiles = {}
for higgsname, higgstype in {'H': 12, 'A': 21}.iteritems():
lha = LHA(lhafile)
sushi = Block('SUSHI', comment='SusHi specific')
sushi.add(Entry([1, 2], commen... | f2f88c79d19de05109748c5c839550bfab905581 | 3,645,697 |
import functools
def pytest_collection(session): # pylint: disable=unused-argument
"""Monkey patch lru_cache, before any module imports occur."""
# Gotta hold on to this before we patch it away
old_lru_cache = functools.lru_cache
@wraps(functools.lru_cache)
def lru_cache_wrapper(*args, **kwargs... | 56f218c06c1d8cc64d884e94f503ae51be135c7f | 3,645,698 |
def __graph_laplacian(mtx):
""" Compute the Laplacian of the matrix.
.. math::
"""
L = np.diag(np.sum(mtx, 0)) - mtx
return L | 54f7fd0a359863bcf31ca9800c30e9eadf32ba8f | 3,645,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.