content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Dict
def scatter_elements(node: NodeWrapper,
params: Dict[str, np.ndarray],
xmap: Dict[str, XLayer]):
""" ONNX ScatterElements to XLayer AnyOp conversion function """
logger.info("ONNX ScatterElements -> XLayer AnyOp")
assert len(node.get_outp... | a1a3dcc00520ed8a47223501c4f2e5458b4d241f | 3,606,200 |
def get_latest_jointarget_information():
"""
Retrieve recent JoinTarget Information from the database.
If recent information is not available in the db, use the WorldMap API and store
the new information in the db.
"""
# ---------------------------------
# (1) Is available JoinTarget info f... | 44d76ed571f81bdc0cf076631985d1a42c457db7 | 3,606,201 |
def folder_get_all_filenames_as_list(strFolderPath="",extension='all'):
"""
Get all the files of the given folder in a list.
Parameters:
strFolderPath (str) : Location of the folder.
extension (str) : extention of the file. by default all the files will be listed regarless of the exte... | f150a3f306219acebc5f8041fa55bc4dbc6b2e43 | 3,606,202 |
from vistrails.core.vistrail.pipeline import Pipeline
def get_workflow_diff(vt_pair_1, vt_pair_2):
"""get_workflow_diff( tuple(Vistrail, id), tuple(Vistrail, id) ) ->
Pipeline, Pipeline, [tuple(id, id)], [tuple(id, id)],
[id], [id], [tuple(id, id, list)]
Return a difference between t... | 4d7199e4caa015155b83102170f37811aab8f3e4 | 3,606,203 |
import argparse
def parse_arguments():
"""
Simple argument parsing using python's argparse
return: Python's argparse parser object
"""
parser = argparse.ArgumentParser()
parser.add_argument("--input", help="Single XML file or directory", action="store")
parser.add_argument("--log", help... | 0dcf19b43923c8e59af1444372421a07d6695534 | 3,606,204 |
import time
def mainLoop(config, batchSystem):
"""This is the main loop from which jobs are issued and processed.
"""
rescueJobsFrequency = float(config.attrib["rescue_jobs_frequency"])
maxJobDuration = float(config.attrib["max_job_duration"])
assert maxJobDuration >= 0
logger.info("Got parame... | 535d2aae802bae49ffa5a29bbbba10122939aebc | 3,606,205 |
import os
import io
def load_dataset(config, ext='png', flatten=False, split=False, fold=0, load=True):
""" Load dataset
returns: (X, Y)
"""
def srt(el):
return int(el.split('.')[-2].split('_')[-1])
Y = np.loadtxt(os.path.join(config.dataset_dir, config.labels_filename))
imgs = [i fo... | 1b5a64db89e97cd4073dfefccbda360ec6a7c036 | 3,606,206 |
def parse_repo_and_name(image) -> (str, str):
""" parse image to (repo, name)
:param image: one of
- k8s.gcr.io/pause
- gcr.io/ml-pipeline/api-server
- quay.io/metallb/controller
- gcr.io/knative-releases/knative.dev/eventing/cmd/webhook
:return (repo, name): one of
... | 4599f42748a50a19c1c3561b6e7f976038572e3d | 3,606,207 |
def in_roi(experiment=None, ex_id=None, bounds=None):
"""
Generate a dataframe with True/False for each blob ID if the bounding
box centroid lies within the ROI.
Must provide either experiment or (ex_id and bounds). Optionally
experiment and bounds dataframe can be provided to save some load time.
... | f0accea9ba9542f0e0d26f23cbd3ce7d92339064 | 3,606,208 |
from pprint import pprint
def check():
"""Prints app status"""
print("Extensions.")
pprint(app.extensions)
print("Modules.")
pprint(app.blueprints)
print("App.")
return app | 5769a0a79252d91a6ab2c17e499becea88dfac73 | 3,606,209 |
def url(feature):
"""
Get the URL for the given Enesmbl feature.
"""
return URL.format(transcript=transcript(feature)) | 810ad621cdd47b646f4df0763c34a1044c45fbec | 3,606,210 |
def _datacopied(arr, original):
"""
Strict check for `arr` not sharing any data with `original`,
under the assumption that arr = asarray(original)
"""
if arr is original:
return False
if not isinstance(original, np.ndarray) and hasattr(original, '__array__'):
return False
ret... | f2194bb116fca4fea2e56bb0ae213095e2419d9b | 3,606,211 |
def parse_vendor_ramdisk_args(args, args_list):
"""Parses vendor ramdisk specific arguments.
Args:
args: An argparse.Namespace object. Parsed results are stored into this
object.
args_list: A list of argument strings to be parsed.
Returns:
A list argument strings that a... | 1d986d367336906e3970d32dd3739f2402155b68 | 3,606,212 |
def parseXyzFile(xyzFile):
""" Extract geometry from xyz file into a unit cell
Args:
xyzFile: (str) Path to the .xyz file
Returns
outCell: (plato_pylib UnitCell object) This contains the cartesian co-ordinates in outCell.cartCoords. Also contains a unit-cell, which will be cubic
"""
fileAsList = _loa... | c6e718c1bbe85c9021da4a1109f88e6081738302 | 3,606,213 |
def draw_memmap(mapstr, lc=None, ax=None, **kwargs):
"""Draw memmap str using matplotlib
mapstr is like:
0x7f2a76000000, 2211840, 1, 256;0x7f2a7621c000, 8200192, 0, 1024;
"""
if ax is None:
_, ax = plt.subplots()
ax.set_xlim([0, 17179869184])
ax.set_ylim([-0.2, 0.2])
... | b8ba20ef2d090896a2b7a9d14823fb4be41d8360 | 3,606,214 |
import functools
def get_move_matrix3_n_move_vector_from_df_by_crystalID(crystalID):
"""
Input crystalRC later because multi systems to handle.
Usage:
get_move_matrix3_n_move_vector_from_df_by_crystalID(34)(crystalRC)
"""
def _get_move_matrix3_n_move_vector_from_df_by_crystalID(crystalID, cry... | e564e511b02631757a2a174d82f0bb062d37a3da | 3,606,215 |
def network_association_find_all(context, host_name=None, session=None):
"""API implementation using SQL-Alchemy; see API for design-level info."""
query = model_query(
context, pvc_adapter_dom.NetworkAssociation, session=session)
# If we don't have a session, make sure that the options for load
... | e43a76cdd9ab52d70f30d236344ed192d9a5d962 | 3,606,216 |
def get_all_round_info():
"""Returns a dictionary containing all the round information.
example: {"rounds": {"Round 1": {"start": start_date, "end": end_date,},},
"competition_start": start_date,
"competition_end": end_date}
"""
return settings.COMPETITION_ROUNDS | 3dbdc7bbffe038aba796071ad4b866f952548989 | 3,606,217 |
def find_sound_times(snd, sfreq, win_size):
"""Find groups of sound times by clustering in time.
Parameters
----------
snd : array (type bool)
A boolean array of sound timepoints, often
created with a cutoff
sfreq : int
The sampling frequency of snd
win_size : float
... | 16fa2e37bf307dfae7acdc435abe96b6ce8909b3 | 3,606,218 |
def get_topics_per_page(user):
"""
Gets the number of Topics which should be displayed per page, based
on the given User.
"""
if user.is_authenticated():
forum_profile = ForumProfile.objects.get_for_user(user)
return forum_profile.topics_per_page or \
app_settings.DEFA... | 053f9e7a31325e95a10e6b3230b60731dac0f29a | 3,606,219 |
import subprocess
def get_docker_version():
"""
Find the locally installed docker version, as captured from the output of
docker -v.
:returns: the raw string output of docker -v.
"""
try:
stdout = subprocess.check_output(('docker', '-v'))
except subprocess.CalledProcessError as ex... | 4e9f667191c3eeaaae05aa298a186d625533c731 | 3,606,220 |
def get_factors(n):
"""
Return a list of integer factors for a number.
Parameters
----------
n: int or float
Number to factor
Returns
-------
sorted: list
A list of sorted factors.
"""
factors = []
sqrt_n = int(round(np.sqrt(n) + 0.5))
i = 1
while i... | 2c1eee1b15c7f3f474ceb46a198256c162ad0236 | 3,606,221 |
def add(ui, repo, *pats, **opts):
"""add the specified files on the next commit
Schedule files to be version controlled and added to the
repository.
The files will be added to the repository at the next commit. To
undo an add before that, see :hg:`forget`.
If no names are given, add all files... | ad992ef49ae5836573482b704f1484010f16d25f | 3,606,222 |
from typing import Optional
def deepest_depth(tn: Optional[TreeNode], value: int) -> Optional[int]:
"""Returns the depth of the deepest node of a certain value."""
if tn is None:
return None
elif tn.value != value:
return opt_max(
opt_increment(deepest_depth(tn.left, value)),
... | aa09d7660c8d23e9f036dc051ff21563bafb9cdc | 3,606,223 |
import re
def get_doc(src) :
"""get comments from Python source code
Parameter
--------------
src@str - the source code
"""
pat = re.compile(r'((?:def|class)\s+[^\n]*\s*)"""(.*?)"""',re.MULTILINE|re.DOTALL)
return [gs for gs in pat.findall(src)] | bb9716a9f7b3c99d5ea3e468b7f69f893773feda | 3,606,224 |
def get_creation_operator(size):
"""
Construct the creation operator with the given matrix size.
Arguments:
size :: int - This is the size to truncate the operator at. This
value should be g.t.e. 1.
Returns:
creation_operator :: ndarray (size, size)
- The creation operator at l... | 7e8dd08d1753dbab6a8662e6c4a86a30dc314326 | 3,606,225 |
import numpy as np
import lib.operations as ops
import lib.test as test
def build_spectrum_limb_resolved(wl,fx_list,mu_list,wlmin,wlmax,x,y,vel_grid):
"""WRITE THIS.
Parameters
----------
"""
#I copy paste as much as possible from above. The roles of wlc and wlc_wide have
#changed bec... | 7d50600b7f61569c5eb8ff7f56257bf3c67341f3 | 3,606,226 |
def _GetBinaryName(client):
"""Gets the GRR binary name on the client."""
client_data = client.Get().data
return client_data.agent_info.client_binary_name | c363a4a42e81184ce2cb74bfdc9c2fd01a746cb1 | 3,606,227 |
def _searchsorted(a, v):
"""Returns where `v` can be inserted so that `a` remains sorted."""
def cond(state):
low_idx, high_idx = state
return low_idx < high_idx
def body(state):
low_idx, high_idx = state
mid_idx = (low_idx + high_idx) // 2
mid_v = a[mid_idx]
low_idx = np.where(v > mid_v... | f2682f732a5d149028229daea81edd59045917b6 | 3,606,228 |
def map_get_by_value_range(bin_name, value_start, value_end, return_type, inverted=False):
"""Creates a map_get_by_value_range operation to be used with operate or operate_ordered
The operation returns items, with values between value_start(inclusive) and
value_end(exclusive) from the map
Args:
... | e3dec52e5c591b307e38d2e882f586fbb6291f43 | 3,606,229 |
def _ifftshift(x):
""" Inverse FFT shifts of array contents, using CUDA if available.
Otherwise defaults to numpy.
Note, ifftshift and fftshift are identical for even-length x,
the functions differ by one sample for odd-length x. This function
implictly assumes that if using CUDA, the array size mus... | a2a7aacaf9a6fa214c29a053eda9c852f06e4aa8 | 3,606,230 |
def prepare_writer_info(slack_team_id, slack_user_id, jama_base_url, use_at_user):
"""
Using the requester's Slack email to find the Jama information of the requester. Then prepare
a piece of html code that we can post on Jama to reflect the requester.
Args:
slack_team_id (string): Slack team id... | 9fa6bdb87c73d9b5828afb428ecaec402a6a8b90 | 3,606,231 |
from pydantic import BaseModel # noqa: E0611
def field_getter(subject: object, field_name: str, default: any = None):
"""
Gets a field value from a dict or object
"""
value = None
if type(subject) is dict and field_name in subject:
value = subject.get(field_name, default)
if ha... | ebe9c4255fc063d95c0309b70e84b109b5b5d60c | 3,606,232 |
import statistics
def get_inhouse_results(date: str=get_inhouse_dates()[-1]) -> tuple:
""" Returns a tuple of a list of tuples sorted by average and a list of scrambles. """
return (sorted(list(map(\
lambda x: [statistics.ao(list(map(parse_time, [t if t != "DNF" else "" for t in x.split(NAME_DELIM)[1].spl... | 8b79d54b845fd043c1ad99361a4007c1bcc1e24e | 3,606,233 |
import os
import types
def custom_eval_shared_model(eval_saved_model_path, model_name, eval_config,
**kwargs) -> tfma.EvalSharedModel:
"""Returns a single custom EvalSharedModel."""
model_path = os.path.join(eval_saved_model_path, 'model.json')
return tfma.default_eval_shared_model(... | 2cf3ebb4678b6d1d9fd9f9256236de48b183ef17 | 3,606,234 |
def askForCommand(command):
"""Asks the user for a command to send to the gripper."""
currentCommand = 'Simple OnRobot RG Controller\n-----\nCurrent command:'
currentCommand += ' rGFR = ' + str(command.rGFR)
currentCommand += ', rGWD = ' + str(command.rGWD)
currentCommand += ', rCTR = ' + str(comma... | 8f678c084b10dbb75d75c47b65e76c7c2a5a41d7 | 3,606,235 |
def fill_with_gauss(df, w=12):
"""
Fill missing values in a time series data using gaussian
"""
return df.fillna(
df.rolling(window=w, win_type="gaussian", center=True, min_periods=1).mean(
std=2
)
) | fdfdedaf7968f617ff98df586b89c30053a6c886 | 3,606,236 |
def construct_azel_target(az, el):
"""Convenience function to create unnamed stationary target (*azel* body type).
The input parameters will also accept :class:`ephem.Angle` objects, as these
are floats in radians internally.
Parameters
----------
az, el : string or float
Azimuth / ele... | 1714ca59c22dd8db8dc3c99c84c5c2c9d5d79eda | 3,606,237 |
from typing import List
from typing import Optional
import torch
def conv_transpose(x: Tensor, kernel: Tensor, stride: List[int],
opad: List[int]) -> Tensor:
"""ND transposed convolution
x : (B, Ci, *inspatial) tensor
kernel : (Ci, Co, *kernel_size) tensor
stride : List{dim}[int]
... | 4ecc3769b8f3979120e673825676c9cc43cd62fb | 3,606,238 |
def gdisconnect():
""" Sign out from Google account. """
url = 'https://accounts.google.com/o/oauth2/revoke?token=%s' % \
session['access_token']
h = httplib2.Http()
result = h.request(url, 'GET')[0]
if result['status'] == '200':
return 'Successfully disconnected.'
else:
... | 132c01e33becfb7066cbb5f798f5720722574936 | 3,606,239 |
def opt(args=None, version=None, out=None, err=None):
"""runs opt"""
return mx.run([findLLVMProgram('opt', version)] + args, out=out, err=err) | 47f745c3c3c5c2686236ebcabd21a1003af68f0f | 3,606,240 |
from typing import Set
from typing import Tuple
def _calculate_mass_center(electrode: Set[Tuple[int, int, int]]):
"""Calculate the mass center of the electrode"""
return np.array(list(electrode)).mean(axis=0) | 32b4997e4a3de2be8517a4fefa75f7181f4589bf | 3,606,241 |
import functools
def decfunc(func):
"""" Decorator function to test _create_argument_value_pairs function """
@functools.wraps(func)
def wrapper(*args, **kwargs):
"""
Wrapper function that creates the argument dictionary and returns a
ret_func, which in turn just returns the argume... | dee0ce80bf35fbac6e1a92fcaead653afd376c70 | 3,606,242 |
import types
def _construct_many_to_many_relationship_property_artifacts():
"""Construct many-to-many relationship artifacts."""
return schemas_artifacts.types.ManyToManyRelationshipPropertyArtifacts(
type=types.PropertyType.RELATIONSHIP,
schema={}, # type: ignore
sub_type=types.Relat... | b6058a43fdef8979e30e464ea03260b8722df737 | 3,606,243 |
def directivity(guide_height, horn_width, horn_effective_length, frequency):
"""
Calculate the directivity for the H-plane horn.
:param guide_height: The height of the waveguide feed (m).
:param horn_width: The width of the horn (m).
:param horn_effective_length: The effective length of the horn (m)... | 5c02e4f8869bc91b36e4a24f8d00fa9bb3345f57 | 3,606,244 |
import os
def discover_evaluations(location):
"""
Return list of evaluations given the codebook location
"""
codebooks = []
for codebook_file in os.listdir(location):
if codebook_file.endswith('.npy'):
with open(os.path.join(location, codebook_file), 'rb+') as f:
... | cb3334323deb70d45cb01e0004c06207de402bb9 | 3,606,245 |
from typing import Iterable
from typing import Tuple
import numpy
def _create_contiguity(
p: DatasetAssembler,
product_list: Iterable[str],
resolution_yx: Tuple[float, float],
timedelta_product: str = "nbar",
timedelta_data: numpy.ndarray = None,
):
"""
Create the contiguity (all pixels va... | faeda18c85579e6b14fa296bc09da5aba6e6bd3a | 3,606,246 |
def oneway_chains(funcs, inits, times):
"""
Return result of chain.
funcs is a sequence of 2-tuple of functions.
i-th tuple's func[0] have 2*(i+1) arguments, and func[1] 2*(i+1)-1.
The funcs[1] is another function satisfying:
funcs[i+1][1](a_{i+1}, *p) == funcs[i+1][0](a_{i+1}, a_{i+1}, *p),
... | c944fe69298dc360a58148a3b22e7b500ef8c8e3 | 3,606,247 |
def swap(heights_list, index01, index02):
"""swap two positions in a list at given indexes
Args:
heights_list (list): iterable in which swapping occurs
index01 (int): index of first element
index02 (int): index of second element
Returns:
list: list with element positions s... | f7add4a06a79837766b5840840d17c3247b0bcae | 3,606,248 |
import requests
import logging
import json
def get_env_data(env_settings):
"""Fetches the environment data from the Arduino and Wio Terminal.
Returns the parsed JSON object or an empty dictionary on failure."""
# Read Arduino
try:
resp = requests.get(env_settings['arduino_url'])
except Con... | bbd7023a00e0f8cbe9b6186707ca0f551de660fc | 3,606,249 |
def wmd(doc1, doc2, matrice_plgt):
""" Soit doc_vec2 et doc_vec1 deux doc encodées à la one_hot sur un\
vocabulaire connu
code fortement inspiré et réécrit depuis la fonction wmdistance de gensim
Une Référence leurs reviennent de droits
"""
if len(doc2)*len(doc1) == 0:
logger.debug(
... | 0ad9b3681d68aeb1dcbbf40355703ac838d92caa | 3,606,250 |
def indexed_moving_average (s, n, central = False) :
"""Generator for indexed moving average of `n` data points over sequence `s`.
>>> def show (ma_s, fmt = "(%d, %.1f)") :
... print ("[" + ", ".join (fmt % (i, v) for i, v in ma_s) + "]")
>>> show (indexed_moving_average (range (10), 2))
[(1, ... | 7ad417dc6e1cc79551dd402513ed2775b7cce40d | 3,606,251 |
from . import persist
import os
import subprocess
def run_shell_cmd(cmd):
"""Run a shell command and return stdout."""
proc = popen(cmd, env=os.environ)
try:
timeout = persist.settings.get('shell_timeout', 10)
out, err = proc.communicate(timeout=timeout)
except subprocess.TimeoutExpir... | d7a680f3ca0ad210052a2d27bf8cafd6a02057e3 | 3,606,252 |
import csv
def ReadData(filename=FILENAME):
"""Reads a CSV file of data from HERI's CIRP survey.
Args:
filename: string filename
Returns:
list of (score, number) pairs
"""
fp = open(filename)
reader = csv.reader(fp)
res = []
for t in reader:
try:
year... | 854a6af3ff635cf96540c9f6e995a5cfbf4e9f89 | 3,606,253 |
def calibrate_seq(cigar_seq, sequence, md_seq, ref_positions):
"""
making cigar seq and seq as same length
with Deletions as '-'
"""
new_sequence = ''
new_pos = []
new_cigar = ''
new_md = ''
seq = iter(sequence)
pos = iter(ref_positions)
md = iter(md_seq)
current_positio... | b149587d8f61a4e7c82d4bde94e62512a5682346 | 3,606,254 |
def annotate_pfam(alignment):
""" Loop over sequences and fill in annotations using Pfam. """
for record in alignment:
if not record.id:
header = get_annotations_no_pfamid(
str(record.seq).replace("-", "")
)
record.id = header
else:
... | faf10185d27cb5bdcbf2c2873e131a9375604839 | 3,606,255 |
import struct
def read(fp: FileLike, format_str: str):
"""read data from `fp` specified by `format_str`"""
num_bytes = struct.calcsize(format_str)
byts = fp.read(num_bytes)
ans = struct.unpack(format_str, byts)
return ans if len(ans) > 1 else ans[0] | 74ee010aa609ad4d1b1111bd9b3284299e747cd3 | 3,606,256 |
import pkg_resources
def bcipy_version() -> str:
"""BciPy Version.
Gets the current bcipy version. If the current instance of bcipy is a
git repository, appends the current abbreviated sha hash.
"""
version = pkg_resources.get_distribution('bcipy').version
sha_hash = git_hash()
return f'... | 77960a393bffc9152c6eb3b41c021ceec815dbef | 3,606,257 |
def compute_separators_morph(binary, scale, max_blackseps=0, widen_blackseps=10):
"""Finds vertical black lines corresponding to column separators.
"""
d0 = int(max(5, scale/4))
d1 = int(max(5, scale))+widen_blackseps
thick = morph.r_dilation(binary, (d0, d1))
vert = morph.rb_opening(thick, (10*... | 16427ad8b5921f8abc9c8035b4a2c6d67f46fc08 | 3,606,258 |
def create_first_n_1_bits_mask(n, k):
""" Return a binary mask of first n bits of 1, k bits of 0s"""
if n < 0 or k < 0:
raise ValueError("n and k cannot be negative number")
if n == 0:
return 0
mask = (2 << n) - 1
return mask << k | 5a9b637a8973f004da2330c8ebb06ea63fd542c3 | 3,606,259 |
import yaml
import os
import io
def process_manifest(manifest_list_files):
"""
Parse the input manifest, generate the data base for genereated files
and generate manifest header files.
Parameters
----------
manifest_list_files:
The manifest lists to parse.
Returns
-------
... | e33a24a283ac78100fb53def354b7a6ceff1123c | 3,606,260 |
def prepare_data(seqs_x, chardict, n_chars=1000):
"""
Prepare the data for training - add masks and remove infrequent characters
"""
seqsX = []
for cc in seqs_x:
seqsX.append(
[
chardict[c] if c in chardict and chardict[c] <= n_chars else 0
for c i... | 6d85b799ca74ab3874b50280edbce2d13de1bf6d | 3,606,261 |
def chexdump(packet, dump=False, to_list=False):
"""
Return a chexdump base on packet
:param packet: String or Scapy object
:param dump: True if you want to dump instead of print
:param to_list: True if you want a list of hex instead of a string
:return: None or Str or List
"""
def _add... | 3a72503010be829feb854fdd6a6fb63b2abb5207 | 3,606,262 |
from typing import List
from typing import Tuple
def entity_confusion_matrix(
utterances: List[str],
entity_predictions: List[List[dict]],
y_trues: List[List[str]],
) -> Tuple[np.ndarray, List[str]]:
"""Confusion Matrix for Evaluating Entity Predictions
Preprocess a list of raw en... | 25173048f4478d7d71b33105e2c06cd75ccf5649 | 3,606,263 |
import numba
def read_boolean(position, block):
"""Read a single byte whose value is either 0 (false) or 1 (true).
Returns:
Tuple[int, numba.uint8]:
(new position, boolean)
"""
# We store bool as a bit array. Return 0xff so that we can bitwise AND with
# the mask that says wh... | 243f3f93e94310e57beb9551f7e609f407d0aedb | 3,606,264 |
def new_candidate():
"""Create a new candiate."""
form = NewCandidateForm()
if form.validate_on_submit():
demographic = Demographic(
race=form.demographic.race.data,
gender=form.demographic.gender.data,
age=form.demographic.age.data,
sexual_orientation... | 290b1c5978a892f6656f89f6a158b9369a0509fb | 3,606,265 |
from typing import Union
import copy
def merge_config(conf: Config, merge: Union[dict, Config]) -> Config:
"""
Merge config object with a dictionary, or a Config object,
same keys in the ``conf`` will be overwritten by keys
in ``merge``.
"""
new_conf = copy.deepcopy(conf)
if isinstance(mer... | 416f9e74707bdb897bcc79813b1bd8ddf3f9da46 | 3,606,266 |
from typing import Callable
from typing import Tuple
from typing import Any
def _wrap_run(func: Callable, step_type: StepType, step_id: "StepID",
catch_exceptions: bool, max_retries: int, *args,
**kwargs) -> Tuple[Any, Any]:
"""Wrap the function and execute it.
It returns two part... | 1c95c866c75f50cf726e4d9d5ab7712c497b5d3a | 3,606,267 |
def parse_args():
"""
Helper function parsing the command line options
@retval ArgumentParser
"""
parser = ArgumentParser(description="This is a script for launching PyTorch training and inference on Intel Xeon CPU "
"with optimal configurations. Now, single i... | 3c0444f18e9319d06a2610a4660d7c2a626023dc | 3,606,268 |
import re
def clean_str(string):
"""
Strip and replace some special characters.
"""
msg = str(string)
msg = msg.replace("\n", " ")
msg = re.sub(r"\s+", r" ", msg)
msg = re.sub(r"^\s", r"", msg)
msg = re.sub(r"\s$", r"", msg)
return msg | 50132d2c56498f4590fcba7837deb791500f3110 | 3,606,269 |
def watchlist(request, response_format='html'):
"""Displays all objects a User is subscribed to"""
profile = request.user.profile
watchlist = profile.subscriptions.all()
context = {'profile': profile, 'watchlist': watchlist}
return render_to_response('account/watchlist', context,
... | f9855bd4fe9d07b04049f3fb30933a603c9ddf43 | 3,606,270 |
from io import StringIO
import sys
import os
import shutil
def pip_install_package(source_name, pip_version=None, python_version=None,
mode=InstallMode.min_deps, release=False, prefix=None,
extra_args=None):
"""Install a pip-compatible python package as a rez packag... | 7d19054fcc6b4ced0074d1a9f4ddf1a96ba37bae | 3,606,271 |
def connect(database_name="tournament"):
"""Connect to the PostgreSQL database. Returns a database connection."""
try:
db = psycopg2.connect("dbname={}".format(database_name))
c = db.cursor()
return db, c
except TypeError:
print("Couldn't connect to DB") | 6d87933ce18d30cb4521a560c7a8fe9ddf7733e4 | 3,606,272 |
def filter_1031(osurl, splitos, device):
"""
Modify URLs to reflect changes in 10.3.1.
:param osurl: OS URL to modify.
:type osurl: str
:param splitos: OS version, split and cast to int: [10, 3, 2, 2876]
:type splitos: list(int)
:param device: Device to use.
:type device: int
"""
... | 472c8e852254806c18f0515c4647a57d645786ce | 3,606,273 |
def prepare_plane_to_curved_spherical_arbitrary(k, rs_support, num_pointss, z, xo, yo, roc_xo, roc_yo, rs_center=(0, 0),
qs_center=(0, 0), ro_centers=None, kz_mode='local_xy'):
"""Prepare spherical wavefront propagator from uniformly sampled plane to arbitrarily sampl... | 947a9ac6a2793c7a62660d5d45e81cd25b9758e8 | 3,606,274 |
def char_to_ix(chars):
"""
Make a dictionary that maps a character to an index
Arguments:
chars -- list of character set
Returns:
dictionary that maps a character to an index
"""
return {ch: i for i, ch in enumerate(chars)} | 8bfc5b99c7f5aef6d88276fe4b3ad005ce9a017e | 3,606,275 |
def define_G(input_nc, output_nc, ngf, netG, norm='batch', use_dropout=False,
init_type='normal', init_gain=0.02, gpu_ids=[]):
"""load a generator
Parameters:
input_nc (int) -- the number of channels in input images
output_nc (int) -- the number of channels in output images
... | 1ada180a82c56c42b21d434f1ec73c90a6a50a8b | 3,606,276 |
def get_genomiccoord2num_targeted(genes,
gene2transcript,
transcriptcodon2trinucleotides,
source_maf_id2target_intervals,
source_maf_id2center,
source... | a7536d89bf3acdde5fdc911f917f320c751ac308 | 3,606,277 |
def bool_tag(name, value):
"""Create a DMAP tag with boolean data."""
return name.encode('utf-8') + \
b'\x00\x00\x00\x01' + \
(b'\x01' if value else b'\x00') | dc914d262a20eed0732e477f75641daa4811fd9f | 3,606,278 |
import os
def file_exists(config, clients, deployment, param_name, mode=os.R_OK,
required=True):
"""Validator checks parameter is proper path to file with proper mode.
Ensure a file exists and can be accessed with the specified mode.
Note that path to file will be expanded before access c... | 5dbb1a227babe2fb899a6884a6099e7222b5314e | 3,606,279 |
def read_client_realtime(file_name):
"""读取实时探测主机信息"""
cf = ConfigParser.ConfigParser()
cf.read(file_name)
ip = cf.get("http_client_realtime", "ip")
port = cf.getint("http_client_realtime","port")
return ip, port | b9c69bb65e3ae3f2eac438ed9022ee276b370314 | 3,606,280 |
def _concat(*lists):
"""Concatenates the items in `lists`, ignoring `None` arguments."""
concatenated = []
for list in lists:
if list:
concatenated += list
return concatenated | a1eea1c074fe1eee1ca454899bf9dec2719a333e | 3,606,281 |
def rbf(x, y, sigma=100):
"""
Radial basis functions kernel
"""
return np.exp(-(np.sum((x-y)**2))/(sigma**2)) | 7b7c3de9d0a567de777ad240a21f986c2181b9a8 | 3,606,282 |
def fit_beta_prior(data):
"""
Fit the parameters of a beta prior given probability data.
Arguments:
data (numpy array):
Values ranging 0 to 1, representing the population level data.
Returns:
List of beta distribution parameters
"""
alpha, beta, _, _ = scs.beta.fit(d... | 27fde4b53cca63ee50f56a0e4ea5b07c3694f744 | 3,606,283 |
def _migrate1to2(previous: SettingsMap) -> SettingsMap:
"""
Migration to version 2 of the feature flags file. Adds the
disableLogAggregation config element.
"""
newmap = {k: v for k, v in previous.items()}
newmap["disableLogAggregation"] = None
return newmap | 690c6407c9ac7ec326f59c7d0c5977a0a17bc3ba | 3,606,284 |
def check_region(exon_exp_reg, act_reg, t_nums):
"""Check if exon found in the expected region."""
q_regions = [exon_exp_reg.get(n) for n in t_nums if exon_exp_reg.get(n)]
if not q_regions:
# target exons are not covered with chain
# expected region does not exist actually
return "EX... | 810ef3643fb537d85c14eecab990c2f0e3f00e0c | 3,606,285 |
def __has_punctuation(word):
"""Check punctuations"""
return any(char in punctuation for char in word) | 5dd05c9994a8622ca0f941f3e921dcd869b7e2fe | 3,606,286 |
def trA(p):
"""
Compute the partial trace of A of the composed matrix of two subsystems A and B
Arguments:
p -- square matrix of 4 x 4
Return:
pA -- square matrix of 2 x 2
"""
pA = np.matrix([[p[0,0]+p[2,2],p[0,1]+p[2,3]],[p[1,0]+p[3,2],p[1,1]+p[3,3]]])
return pA | 5f2c58f549db22e3604feb6b146d07f781a6fd0d | 3,606,287 |
import shelve
async def post_item_type(item: ItemTypeWithPrevious, tenant: str) -> ItemTypeUrlDetails:
"""
If 'previous' is set, we consider it an update on top of that.
If not, the internal database is checkd for a potentially existing version that is being used.
If not, a new item is created.
... | b43af6876c9984f733e381ee82fd3793ee18bc1b | 3,606,288 |
def logout_user():
""" logout a user and remove session data """
session.pop('username')
flash("Goodbye!", "info")
return redirect(url_for('home_page')) | dbade6ea1bd8e814982c84a215a742725768ac9c | 3,606,289 |
def get_least_squares_size(modelform, r, m=0, affines=None):
"""Calculate the number of columns in the operator matrix O in the Operator
Inference least-squares problem.
Parameters
---------
modelform : str containing 'c', 'A', 'H', 'G', and/or 'B'
The structure of the desired reduced-order... | 86cf6a0b3e4b256eaccb3f061d21f7de74dcc604 | 3,606,290 |
def nfvi_compute_initialize(config, pool):
"""
Initialize the NFVI compute package
"""
global _compute_plugin
if _compute_plugin is None:
_compute_plugin = NFVIComputePlugin(config['namespace'], pool)
if _compute_plugin.ready_to_initialize(config['config_file']):
_compute_plugin... | b84c292cc1b4d2d06f9862e63af87a17c02c2b46 | 3,606,291 |
import copy
def continuumTelluric(data, model=None):
"""
Return a continnum telluric standard data.
Default: return a telluric flux of mean 1.
Parameters
----------
data: spectrum object
The input telluric data to be continuum
corrected
model: (optional) model obje... | c299eae906cd87d352ec6cbc0e207c6a4cc9f942 | 3,606,292 |
def read(rows):
"""Reads the list of rows and returns the sudoku dict.
The sudoku dict maps an index to a known value. Unknown values are not written.
Indices go from 0 to 80.
"""
sudoku = {}
i = 0
for rn, row in enumerate(rows):
if rn in (3, 7):
continue
j = 0
... | 1f1a06a32d1be70f3d912bd42b9cca07f7d4879d | 3,606,293 |
import subprocess
def get_server_info():
"""
Returns server information
"""
container_name = subprocess.check_output("uname -n", shell=True).decode("ascii").strip()
ip_addr = subprocess.check_output("hostname -I", shell=True).decode("ascii").strip()
cores = subprocess.check_output("nproc", she... | 0bbe71a91bd6e183fd3980f49935b801dede9fbf | 3,606,294 |
from typing import Union
from re import T
from typing import Any
def _eval_decoder(obj: Union[str, T]) -> Union[Any, T]:
"""
Decoder function to help decoding string objects to objects using the Python interpeter.
If a non-string object is passed it will return the argument
"""
if isinstance(obj,... | 54170adeac71815eace9ec3ba8b90047431f396a | 3,606,295 |
def uniquify(iterable):
"""Remove duplicates in given iterable, preserving order."""
uniq = set()
return (x for x in iterable if x not in uniq and (uniq.add(x) or True)) | 563953cc6450a0136a4996d4a5f5a0057f6ad69b | 3,606,296 |
import logging
def model_fn(features, labels, mode, params):
"""The model, with loss, metrics and debug summaries"""
# YOLO parameters
grid_nn = params["grid_nn"] # each tile is divided into a grid_nn x grid_nn grid
cell_n = params["cell_n"] # each grid cell predicts cell_n bounding boxes.
info... | 18e9911bfd651ddc1e8619d11e1033177c291c6e | 3,606,297 |
def count_candidate_votes(candidate_dict: dict, csv_data: list) -> dict:
"""
Go through the candidate list and count the number of votes each time it appears.
:param candidate_dict:
:param csv_data:
:return:
"""
# Go through the csv and get the candidate's name
for row in csv_data:
... | b2ca61d78183c1b152e22bb413ebb89a8dff8b0a | 3,606,298 |
def model_resnet50_keras(
input_shape: tuple, classes: int,
include_top=True, weights='imagenet',) -> keras.Model:
"""
Keras Applicationsに用意されているResNet50を読み込む。
Deep Residual Learning for Image Recognition
Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun
https://arxiv.org/abs/1512.03385
... | e6ba286d3ac2fb93d4d985c67e7d270e627034f7 | 3,606,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.