content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import os
def fullpath(value):
"""
Standalone path string expander
e.g: Will expand '~' to the absolute path for the home directory of the user
"""
return os.path.abspath(os.path.expanduser(value)) | 744c4a35d66bfe3f5aeddb446f1c4caa9af7968b | 664,223 |
import subprocess
def run_shell_command_logging(args):
"""
Runs a shell command while logging both standard output and standard error.
An earlier version of this function that used Popen.stdout.readline()
was failing intermittently in CI, so now we're trying this version that
uses Popen.communica... | 4d1477c55779032032fe26612398095fcaeba104 | 664,224 |
import torch
def calc_confidence(
probs: torch.Tensor,
labels: torch.Tensor,
):
"""Confidence for filtering
Args:
probs: (Batch, Length, Vocab_size)
labels: (Batch, Length)
"""
bsz, tsz, _ = probs.size()
probs = probs.vi... | 74f6d2837bf940c508dc7613940e6f6d91234dec | 664,225 |
def runtime_sync_hook_is_client_running(client):
"""
Runtime sync hook to check whether a slash command should be registered and synced instantly when added or removed.
Parameters
----------
client : ``Client``
The respective client of the ``Slasher``.
"""
return client.running | 21b53074756dcb7f9c322b369b862f00f6cfc41c | 664,226 |
import math
def root_ttr(n_terms, n_words):
""" Root TTR (RTTR) computed as t/sqrt(w), where t is the number of unique terms/vocab,
and w is the total number of words.
Also known as Guiraud's R and Guiraud's index.
(Guiraud 1954, 1960)
"""
if n_words == 0:
return 0
retu... | bae5ed27e26e0f8751146717ff1a10192eed2ed1 | 664,227 |
import os
def get_imgs_path(root, postfix=None):
"""获取root目录下的所有文件路径,若postfix不为None,则只获取指定后缀的文件,如 “.jpg”
"""
imgs_path = []
for root, dirs, files in os.walk(root):
for file in files:
if not postfix:
imgs_path.append(os.path.join(root, file))
elif os.path... | aacc4527952ec7a45f3b857d42d7214bd30d98f8 | 664,228 |
def read_file(path):
""" reads lines of a file and joins them into a single string """
try:
with open(path, 'r') as text_file:
return "".join(text_file.readlines()).strip()
except IOError:
exit("Error: file '%s' is not readable!" % path) | c1a246c42874c11a7dc1f2e94f18c2a1f633d092 | 664,229 |
import re
import uuid
def _replace_re_pattern(code, pattern):
"""Replace the given re pattern with a unique id.
Return the replaced string and a list of replacement
tuples: (unique_id, original_substring)
"""
replacements = []
matches = re.findall(pattern, code)
code_ = code
for m in m... | 92f1d6a79e50c16d8175f75fc2fd4bac721e3393 | 664,230 |
def computeRank(R, T, key):
"""
Input: Root R (a node object) of a tree T (a tree object) and a key of a node in the tree (a number).
Output: Rank of the node with the key "key" in the tree - a number.
"""
left, right = R.getLeftChild(), R.getRightChild()
if left:
leftSize = left.getSize... | 4a3d42cc4cb8ddf6bb255b0d7cdcc8ba59454798 | 664,231 |
import torch
def cr_matrix_vector_product(m: torch.Tensor, x: torch.Tensor) -> torch.Tensor:
"""Returns the product of a complex matrix and a real vector.
:param m: Matrix as ``(*, m, n, 2)`` tensor.
:param x: Vector as ``(*, n)`` tensor.
:return: Result as ``(*, m, 2)`` tensor.
"""
xr = x.un... | cafc5f19441fc1c47eb9f82d0ae8992918a8df72 | 664,232 |
def invert_momenta(p):
""" fortran/C-python do not order table in the same order"""
new_p = []
for i in range(len(p[0])): new_p.append([0]*len(p))
for i, onep in enumerate(p):
for j, x in enumerate(onep):
new_p[j][i] = x
return new_p | bdbc47fcdc5cb46923ab6c827210052a8d8918c9 | 664,233 |
def _CheckNoInterfacesInBase(input_api, output_api):
"""Checks to make sure no files in libbase.a have |@interface|."""
pattern = input_api.re.compile(r'@interface')
files = []
for f in input_api.AffectedSourceFiles(input_api.FilterSourceFile):
if (f.LocalPath().find('base/') != -1 and
f.LocalPath()... | 12ea2309bdef26e6cb361b855ab1e97c0ac5c688 | 664,234 |
def _get_view_name(task_name: str, window_size: int) -> str:
"""Returns the view name for a given task name."""
return f"{task_name}_{window_size}_view" | fc247a0d486a12ec87ebc81de30d5d0729841b8b | 664,235 |
def is_prime(n):
""""pre-condition: n is a nonnegative integer
post-condition: return True if n is prime and False otherwise."""
if n < 2:
return False;
if n % 2 == 0:
return n == 2 # return False
k = 3
while k*k <= n:
if n % k == 0:
return ... | 9eee480d14c55f65446a6e683949e56ae77993a6 | 664,237 |
def white_space_fix(text):
"""fix whitespace"""
return ' '.join(text.split()) | c90058af88279135f551dc8b100408eb79b8d6a4 | 664,238 |
def subtract_one_from_each_index(sel_anch_index_list):
""" Subtract one from the selected anchors' index values. """
new_index_list = list()
# for i in range(len(sel_anch_index_list)):
# new_index = sel_anch_index_list[i] - 1
# new_index_list.append(new_index)
for item in sel_anch_ind... | e9fc920d5cd83edff28db91cafa24448c4d486c4 | 664,239 |
import os
import glob
import subprocess
def png_to_txt(pngpath,short_name,txtpath,file_data):
""" Extract the text from a set of png files (issued from the same pdf file).
The png files associated to a single pdf file are numbered according to the page,
they share the same short_name.
"""
png_in = os.path.join... | b8bd0b0134dcb16427f33a3bb3446ccd79d9176c | 664,240 |
def neurips2021_tex(*, family="serif"):
"""Fonts for Neurips 2021. LaTeX version."""
preamble = r"\renewcommand{\rmdefault}{ptm}\renewcommand{\sfdefault}{phv}"
if family == "serif":
return {
"text.usetex": True,
"font.family": "serif",
"text.latex.preamble": pream... | fdcb284d548dea8cc9f030b9ed11edf6a9c63445 | 664,241 |
def convertAbeBack(A):
"""
Convert A to numpy.array if it is abelieantensors
"""
if type(A).__module__.split(".")[0] == 'abeliantensors':
A = A.to_ndarray()
return A | f67bfe964269a880108161dd8b5b59c5e278e232 | 664,242 |
import re
def delete_bracket(text):
"""
删除括号以及括号里的内容,包括 <*>、(*)、(*)、【*】、[*]、{*}
"""
text = re.sub(r"<[^<>]*>", "", text)
text = re.sub(r"\([^()]*\)", "", text)
text = re.sub(r"\([^()]*\)", "", text)
text = re.sub(r"\【[^【】]*\】", "", text)
text = re.sub(r"\[[^\[\]]*\]", "", text)
tex... | 98c8b0938935a97312836041a74291197c0baca4 | 664,244 |
def make_extended_properties(extensions = []):
"""
Makes an extended property for a cybox object
"""
props = {}
for ext in extensions:
props.update(ext)
return props | c3bc5e52e3ebc6ff42d4bd0d79a387e0ff93ccdb | 664,245 |
def _psbl_liq_cls():
"""Returns a set of possible liquid classes available for Fluent
"""
x = ('Water Free Multi', 'Water Free Single',
'MasterMix Free Multi', 'MasterMix Free Single',
'Ethanol Free Multi', 'Ethanol Free Single',
'DMSO Free Multi', 'DMSO Free Single',
... | d70cbd006ea9af37ec5d1852ee210987d93ebad1 | 664,246 |
def _reference_wave(shape):
"""
Obtains the index of the wave that must be taken as reference to
establish the QRS complex reference point, based on the shape of the
complex and the energy of the waves.
"""
# If one wave has more than twice the enrgy than any one else, it is the
# reference.... | 396de0a7655e2abb7fb5e17267e10aaab2431370 | 664,247 |
import torch
def normalize_weights(programs, beta):
"""
:param programs: list of (token_idx_seq, weight) tuples. each weight is the negative log probability of each program (and not the probability)
:param beta: controls how much to rely on weights, with beta=0 corresponding to uniform distribution and be... | 4c3e74cae12dfd20fcda0730dac9a3e5005864d7 | 664,248 |
from typing import Dict
import json
import base64
import binascii
import time
def token_time_valid(jwt: str) -> bool:
"""
Check if the jwt is not expired.
"""
payload = jwt.split(".")[1]
# Here we decode the base64 encoded middle part of the JWT token. The length of the
# payload needs to be a... | fe157f398681c73325de868f6bc4e91e803c8d4a | 664,249 |
def cli(ctx, email, first_name, last_name, password, metadata={}):
"""Update an existing user
Output:
a dictionary containing user information
"""
return ctx.gi.users.update_user(email, first_name, last_name, password, metadata=metadata) | b8f5a1fc8c7ee9da1e34862e93d07a2203c43ad1 | 664,250 |
def translate_underscore(string, lower=False):
"""
Replaces the underscore HTML idiom <sub>—</sub> with the literal
underscore character _.
"""
if lower:
string = string.lower()
return string.replace('<sub>—</sub>','_').replace('<sub>-</sub>','_').replace(u'<sub>\u2014</sub... | d551c0fe75db84653f1dcfabd592d0ecd5511054 | 664,251 |
def calculate_IoU(geom, match):
"""Calculate intersection-over-union scores for a pair of boxes"""
intersection = geom.intersection(match).area
union = geom.union(match).area
iou = intersection/float(union)
return iou | 92480c5cc7c1e3e99b6339a950256524a017ba3a | 664,252 |
def powerset(lst):
"""returns the power set of the list - the set of all subsets of the list"""
if lst == []:
return [[]]
#power set is a list of lists
#this way is more efficent for getting the combinations of the characters in a list
lose_it = powerset(lst[1:])
use_it = map(lambda subs... | 04093ae60b1293edaea16ce9e278cfaff9f92251 | 664,253 |
import re
def tokenize(text):
"""Parses a string into a list of semantic units (words)
Args:
text (str): The string that the function will tokenize.
Returns:
list: tokens parsed out by the mechanics of your choice
"""
tokens = re.sub('[^a-zA-Z 0-9]', '', text)
tokens = t... | c5c993e05d9f7530359a44f321aa6d706cd27526 | 664,254 |
import argparse
def get_arguments():
"""Obtains command-line arguments."""
parser = argparse.ArgumentParser()
parser.add_argument('--input', type=argparse.FileType('rU'), required=True)
parser.add_argument('--output', required=True)
parser.add_argument('--shift', action='store_true', default=F... | 44534cd4b33d37fc375cd1c70ffa0c0738fe4682 | 664,255 |
def iou_bbox(gt_box, pred_box):
"""
Method to calculate the Intersection over Union between two boxes
"""
inter_box_top_left = [max(gt_box[0], pred_box[0]), max(gt_box[1], pred_box[1])]
inter_box_bottom_right = [min(gt_box[0] + gt_box[2], pred_box[0] + pred_box[2]),
min... | 5e1ef7e63713624eb6072b3b77d64b4579e618db | 664,256 |
def get_regions():
"""Returns a static list of regions for the region combobox"""
regions = ['asia-east1', 'asia-east2', 'asia-northeast1', 'asia-northeast2', 'asia-northeast3',\
'asia-south1', 'asia-southeast1', 'asia-southeast2', 'australia-southeast1', 'europe-north1', \
'europe-west1', 'europe-west2... | 0d818cb249ca07948b3ece1f1b7d55ee1429b63d | 664,257 |
from typing import Tuple
import math
def get_graph_dimen(fields: dict, uniq_cnt_threshold: int) -> Tuple[int,int]:
"""
Helper function to first figure out how many graphs we'll be
displaying, and then based on that determine the appropriate
row and column count for display
"""
graph_cnt = 0
... | 4aa06d0ccf82fca15bd10f8470f666fad91caae5 | 664,258 |
def flatten(iterable):
"""Flatten a given nested iterable."""
return (x for e in iterable for x in e) | 3f91d5f4b94ffdb484b53a18745e93d934b41c65 | 664,259 |
from datetime import datetime
def date_from_string(indate):
""" Returns a python datetime.date object from a string formatted as
'2012-11-21' = 'yyyy-mm-dd' """
return datetime.strptime(indate, "%Y-%m-%d").date() | 07abe82b0f6732a133485a223838e86872807329 | 664,260 |
import math
def ucb_score(parent, child):
"""
Upper confidence bound score
"""
prior_score = child.prior * math.sqrt(parent.visit_count) / (child.visit_count + 1)
if child.visit_count > 0:
# The value of the child is from the perspective of the opposing player
value_score = -child.... | cff7b529a26c36b81f9a9672cdf5d0d95f9c8a67 | 664,261 |
def split_preds(preds):
"""
Remove the verts from the pred dict.
"""
preds_dict = {}
verts_dict = {}
for k, v in preds.items():
if 'vert' in k:
verts_dict[k] = v
else:
preds_dict[k] = v
return preds_dict, verts_dict | 1b956f66399adf1627afc53fbeb5edefdc6af07d | 664,262 |
import torch
import gc
def torch_pca( X,
device='cpu',
mean_sub=True,
zscore=False,
rank=None,
return_cpu=True,
return_numpy=False):
"""
Principal Components Analysis for PyTorch.
If using GPU, then call... | 8fbfa9c5cd55d9311913f496ece8cbc79f4d0cea | 664,263 |
import pathlib
import yaml
def load_config_as_dict(path: pathlib.Path) -> dict:
"""
loads the ``yaml`` config file and returns a dictionary
Args:
path: path to json config file
Returns:
a nested object in which parameters are accessible using dot notations, for example ``config.model... | 4ce42ced5cf95f926a992fd077847f41aff76f9e | 664,264 |
def insertion_sort(lst: list) -> list:
"""Sort a list in ascending order. The original list is mutated and
returned. The sort is stable.
Design idea: Iterate over the list. After i iterations, the first i elements
of the list should be sorted. Insert the i+1'th element in the appropriate
spot in th... | 56b33fda5f185381e522458718f8d0c05e9ab785 | 664,265 |
import re
def parse_block(block):
"""turns list of lines (i.e. block) into hash of salient features"""
ret = {}
def _x1x2parser(line):
r = re.compile(r"(\d+)\.\.(\d+)")
m = r.findall(line)
if len(m) == 1:
return ( int(m[0][0]) , int(m[0][1]) )
else:
return ( int(m[0][0]) , int(m[-1][1]) )
ret['x1'],... | d8a1e0d14ef06fef91eef8149a9ceae484da28d8 | 664,266 |
def detect_robot_context(code: str, cursor_pos: int):
"""Return robot code context in cursor position."""
code = code[:cursor_pos]
line = code.rsplit("\n")[-1]
context_parts = code.rsplit("***", 2)
if len(context_parts) != 3:
return "__root__"
else:
context_name = context_parts[1... | ed0dd96a66ca55f479d28526804a910e4b545dd5 | 664,268 |
def create_ds_118(packer, filler1, filler2, filler3, brakectr, awdlckmax, awdlckmn, drvstate, drvtq, emergbrk, stoplmp, angle):
"""Creates a CAN message for the Ford 118 message."""
values = {
"BrkCtrFnd_B_Stat": brakectr,
"AwdLck_Tq_RqMx": awdlckmax,
"AwdLck_Tq_RqMn": awdlckmn,
"DrvSte_D_Stat": d... | 6cf3bbf04307549bf3217a9ad0ce7ac06d81cdd1 | 664,269 |
def cipher(text, shift, encrypt=True):
"""
Encrypt and decrypt letter text by using the Caesar cipher.
Parameters
----------
text : string
A string only contains letters from alphabet
shift : int
A number that you wish to replace each original letter to the letter with that number o... | 60cadd09a063af63cdd360ad62535161eab7d1bb | 664,270 |
def load_image_mask_gt_eval(dataset, image_id):
"""Load and return ground truth data for an image, no processing.
"""
# Load image and mask
image = dataset.load_image(image_id)
point, class_ids, bbox, mask = dataset.load_mask(image_id)
return image, class_ids, bbox, mask, point | 8ab648ecaf0629e52d187ba019faaf40ce8534b3 | 664,271 |
def char_is_printable(char):
""" Check if char is ascii number (<128) and printable """
if ord(char) >= 32 and ord(char) <= 126:
return True
else:
return False | 4a37f6453f5f1eb3297841960308f84c92468de8 | 664,272 |
def _url_joiner(*args):
"""Helper: construct an url by joining sections with /"""
return '/'.join(s.strip('/') for s in args) | b94b25d0f3b5820993f4adc591e5ef257b4371da | 664,273 |
import json
def validation_stat(model_name, file_path, type_='acc'):
"""
load and return accuracy and losses numbers per epoch
"""
with open(file_path) as f:
data = json.load(f)
if type_=="acc":
return data[f"{model_name}"]["test_acc"]
else:
return data[f"{model_name}... | f1c965210013628be9229ee27e4e3a99114ea67f | 664,274 |
import requests
def query(uri):
"""
Fill in this method.
Query the passed URI and return the text response.
See https://2.python-requests.org/en/master/
"""
response = requests.get(uri)
return response.text | 7cc2fee7a7cc256f59683ae2cf7832b57a63bfe9 | 664,275 |
def nonreturn(func):
""" Decorator to simplying marking a function as nonreturning for the bridge """
func._bridge_nonreturn = True
return func | 52a8a9f1b270f105c01aeeb7b8d8c904df2ffba9 | 664,276 |
def after_request(response):
"""在请求之后会调用,并且函数里面接受一个参数:响应,还需要将响应进行返回"""
print('after_request')
# 可以在此函数中对响应数据做统一的处理
return response | cf2301170f9cf053772ed1c2c360174fb3a389cc | 664,277 |
def to_int(value):
"""Returns the value as integer, or None if not integer."""
try: return int(value)
except ValueError: return None | 7345e928d0a583a87354b52a36c42ef92526fe3a | 664,278 |
def calculateAverage(list):
""" Calculate the average value from a list """
size = len(list)
if size > 0:
sum = 0
for i in range(0, size):
sum += list[i]
return sum / size
return 0 | cdcb8db816348ec3a2eae04ddc22719dc41a12a4 | 664,279 |
def get_char_tag_data(file_path):
"""
获取字符 和对应的标签
:param file_path:
:return:
"""
with open(file_path, 'r') as f:
list_all = f.readlines() # type: list
# print(list_all, len(list_all))
# ['本 O\n', '性 O\n', '的 O\n', '差 O\n', '别 O\n', '。 O\n', '\n'] 112188
i = 0
char_str = s... | 40d95b2e498f5156fe4aee1bba527fb452e0f7e7 | 664,280 |
from numpy import logspace, histogram, floor, unique, asarray
from math import ceil, log10
def pdf(data, xmin=None, xmax=None, linear_bins=False, **kwargs):
"""
Returns the probability density function (normalized histogram) of the
data.
Parameters
----------
data : list or array
xmin : f... | 4db6bba000a015f83033778097e5ca070a708af9 | 664,281 |
import argparse
import pkg_resources
def makeOpts():
"""Define an option parser and return it."""
usage = """usage: %prog <action> <jurisdiction> [options]
Jurisdictions are specified by their short letter codes (ie, us).
--launch, --info, --add are mutually exclusive.
"""
parser = argparse.Argumen... | 50dfe2002e472d54efefe0797e0060e026588d88 | 664,282 |
def toUnicode(input):
"""
Convert bytes string to string
"""
return str(input, 'utf-8') | 13c5ae604c5cc7ca11e4b510d1242369a4317147 | 664,283 |
def get_hplist(builder, object=False):
"""Get device information from the builder file.
Args:
builder: A builder dict.
object: Boolean.
Returns:
A list.
[
{ip: xx,
port: xx,
devices: [ # object only
xx, ...
... | a0319669fbd2beb4f53cb864191b3c9ce6524e61 | 664,284 |
import os
import shutil
def download_github_repository(url, cache_path, branch_or_tag="main", force=False) -> str:
"""Downloads the repository from Github.
Args:
version (str): The version to download. Defaults to the
version of the current codebase.
path (str): The path to downlo... | 1b79e495e61b23a197730d6f0148e6aad706f161 | 664,285 |
import torch
def get_vector(images, layer, model, num_ftrs, size, Flatten=False):
"""
Get feature vector from ResNet
layer: from ResNet
model: ResNet
"""
embedding = torch.zeros(images.shape[0], num_ftrs, size[0], size[1])
def copy_data(m, i, o):
embedding.copy_(o.data)
h = lay... | 8b2d9122e61e48d0336f1ad96a1b1c92e4d05a15 | 664,286 |
from typing import List
import collections
def isPossible(self, nums: List[int]) -> bool:
"""
>> greedy
1. We iterate through the array once to get the frequency of all
the elements in the array
2. We iterate through the array once more and for each element we
either s... | f2b4cd074276afb2169584a2cdc2eadef56a63ae | 664,287 |
def insertable(m) -> str:
"""A char, or a complex insert."""
return m[0] | 44d84d93e81a462b436adabda98b4be5880135df | 664,288 |
def exclude_variants(pages):
"""Checks if page is not a variant
:param pages: List of pages to check
:type pages: list
:return: List of pages that aren't variants
:rtype: list
"""
return [page for page in pages
if (hasattr(page, 'personalisation_metadata') is False)
... | 96246528732ae72e0b2eb900f36d0ca8a161a8c9 | 664,289 |
def check_input_expression_characters(expression):
"""Check whether characters of an expression are all valid.
:type expression: str
:rtype : bool
:param expression: The expression.
:return: True if all characters are valid.
"""
# Construct valid characters.
valid_char = "0123456789AB... | 4518aec25403e77c120a731013ec025359777bbe | 664,291 |
def new_incremented_param_name(basename, currnames, start=1):
"""
Generate new integer incremented version of the parameter name defined by
`basename` based on a list of current names in `currnames`.
:param basename: base name to increment
:type basename: :py:str
:param currnames: curr... | bccbc76070cdd88432f5d1c9bf1ec401e3dac556 | 664,293 |
import os
def dir_exists(dirpath):
"""Tests for existence of a directory on the string filepath"""
if os.path.exists(dirpath) and os.path.isdir(
dirpath
): # test that exists and is a directory
return True
else:
return False | 7b7741fc13b2d3e2e6cb5591402446e3f5a09323 | 664,294 |
import logging
def get_ugrid_mesh_description(nc_file):
"""
Collect UGRID mesh description from mesh file and return a list of UGRID variables;
only one mesh description is allowed
"""
# Look for UGRID mesh description dummy variable
mesh_names = []
for var_name, var in nc_file.variables.... | 47f6e782fe488b046abe7c3aef20f40fc85432f8 | 664,295 |
import socket
def is_ipv6(addr):
"""Checks if a given address is an IPv6 address."""
try:
socket.inet_pton(socket.AF_INET6, addr)
return True
except socket.error:
return False | b877ff42e0077f05ea2af205a86b40822daa7fa7 | 664,296 |
def create_schema(base, engine):
"""
Create database schema.
"""
base.metadata.create_all(engine)
return engine | d45a868edf0fce043dcee69b56cf721f7e5f7f0e | 664,297 |
from typing import OrderedDict
def sort_dict(d):
"""
Helper function; returns a recursively sorted OrderedDict (by key).
:param d: A dictionary to sort.
:return: An OrderedDict.
"""
res = OrderedDict()
for k, v in sorted(d.items()):
if isinstance(v, dict):
res[k] = sort... | e6036ce4d1622744dd09144e00008edeaa6276d4 | 664,298 |
def get_names_from_wordlist(filepath):
"""Read wordlist line by line and store each line as a list entry."""
with open(filepath) as f:
content = f.readlines()
# Remove whitespace characters like '\n' at the end of each line
return [x.strip() for x in content] | ff30553b9afeef59bc7fca8c05dc12f5d9a70686 | 664,299 |
import re
def branch_to_domain(branch_name, domain_pattern=None):
"""
Convert a git branch name into a valid domain string.
"""
# obtain domain name using regex
if domain_pattern:
if isinstance(domain_pattern, (tuple, list)):
pattern, replacer = domain_pattern
else:
... | dc2d5044f491abae4d3266370025fd599cf780bb | 664,300 |
def max_change_day(prices):
"""Returns the day (index) of the maximum single day change in price."""
diff_list = []
for x in range(len(prices)-1):
diff_list += [prices[x+1] - prices[x]]
maxindex = 0
maximum = diff_list[0]
for x in range(len(diff_list)):
if diff_list[x] ... | d49aec99c0fd7a29bbb382191c31835edd6b1ab9 | 664,301 |
def titan_PCE_quadrature(Model):
""" Still need to be reimplemented. """
return 0 | e6691de5d7befd008299acd337106eb5f1036f03 | 664,303 |
def rm_backslash(params):
""" A '-' at the begining of a line is a special charter in YAML,
used backslash to escape, need to remove the added backslach for local run.
"""
newParams = {}
for k, v in params.items():
newParams[k.strip('\\')] = v
return newParams | 05ff567aa4a454477e75f16fe7b58f6e52a8c0fe | 664,304 |
def old_word(answer):
"""
:param answer: str, the answer for this hangman game.
:return: str, hyphens(-).
"""
ans = ""
for i in range(len(answer)):
ans += '-'
return ans | 5738fc10d00f54837fb2e45c6463c4259e26c88e | 664,305 |
import json
def json_extract(json_path):
"""Converts JSON file to Python Dict
Args:
json_path (str): Path to JSON file
Returns:
data (dict): Dictionary containing JSON information
"""
with open(json_path) as f:
data = json.load(f)
return data | 903c109ece195b05c40d312eab50b64538854c17 | 664,306 |
def make_orbit_dict(orbit_codes):
"""Takes list of codes in form 'ASD)GGH' and turns them into dictionary. key is first three digits. value is list of last three (mult. occurances)Returns dictionary."""
orbit_dict = {}
for code in orbit_codes:
if code[0:3] in orbit_dict.keys():
orbit_d... | b9d357683142c10fe35ee01ba166d485cfcec8cb | 664,307 |
import functools
import logging
def auth_url(method):
"""
认证路由访问权限
:param method:
:return:
"""
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
try:
_session_obj = self.session['url']
_url_path = self.request.path
_url_path = _url_path[0:-1] if len(_url_path) > 1 \
... | b08b79384585042350b9db79f961cb8e89c70c98 | 664,308 |
import os
def expand_path(path):
"""Expands paths, starting with ``.`` or ``~``, to an absolute path."""
if path.startswith("."):
return os.path.abspath(path)
if path.startswith("~"):
return os.path.expanduser(path)
return path | 7b4371e52a7a44252be2915d17acc0ff94e5996e | 664,309 |
import re
def sorted_alphanumeric(l, reverse=False):
"""
Sorts the given iterable alphanumerically.
If values are numeric, sort numerically; if strings, alphanumerically.
If string operations don't work we just sort normally; this works for
numeric types.
"""
try:
convert = lambda ... | 34f382c7e34ee62a00bceebdeec0488d18c65e7e | 664,310 |
from typing import List
import copy
def merge_attributes(
knode1_attributes: List[dict],
knode2_attributes: List[dict],
in_place: bool = False,
) -> List[dict]:
"""Find the union of the attributes lists in knowledge graph nodes that
require merging. Note: in_place=True option is to merge the secon... | 6706f4049f06f77002e4ec1f3cf46d9e873e52a8 | 664,311 |
import math
def get_two_point_dis(point1, point2):
"""
Args:
point1 (list): point1
point2 (list): point2
Returns:
int: Euclidean distance between point1 and point2
"""
# calculate the euclidean distance
dist = math.sqrt((point1[0] - point2[0]) *
... | fbc80f35c6b824cf60e6cdc4a50c0ad015973304 | 664,313 |
import functools
def product(iterable):
"""returns the product of the elements of the iterable"""
return functools.reduce(lambda a, b: a * b, iterable, 1) | ac72acc233bd538bfc0322562acd44a6d16799a3 | 664,314 |
import requests
def list_pastes_user(devkey, userkey):
"""This function retrives a list
of pastes created by a user on pastebin."""
content = {'api_dev_key': devkey, 'api_user_key': userkey, 'api_results_limit': '100', 'api_option': 'list'}
r = requests.post('https://pastebin.com/api/api_post.php', pa... | 081a08d0bc03ffca2807d2dccc0649279f3e93da | 664,315 |
import sys
import os
import signal
def processInterrupt(uPid):
"""
Sends a SIGINT or equivalent to interrupt the specified process.
Returns True on success, False on failure.
On Windows hosts this may not work unless the process happens to be a
process group leader.
"""
if sys.platform ==... | b09a222edfa2153c359b15244cdcf4e191b26cbe | 664,317 |
def _get_volume_capacity(val):
"""
Return the capacith with unit 'M'
"""
if val.lower().endswith("gi"):
return int(val[:-2]) * 1024
elif val.lower().endswith("mi"):
return int(val[:-2]) * 1024
else:
raise Exception("Parse storage capacity({}) failed".format(val)) | daa1c775c35ad7fcc2dc3def4902e75ccd7224f4 | 664,318 |
def setup_Parameters():
"""
"""
l_obj = None
return l_obj | c45c6a468f0defb1c8063fc8574675e4da338afc | 664,319 |
import argparse
def cmd_args_parser():
"""Parsing command-line arguments"""
parser = argparse.ArgumentParser(
prog="DatasetInfo", description="Gets datasets-information",
)
parser.add_argument(
"--project_id",
type=str,
action="store",
dest="project_id",
... | 793e85588c643eb82811b8b68bbe428f0d40dd77 | 664,321 |
def assign_index(input_df, index_col='idx'):
"""Return input DataFrame with id col.
"""
out_df = input_df.reset_index(drop=True)
out_df.loc[:, index_col] = out_df.index
return out_df | 1defd9da8630d05e4a828eff0e40a7bcf51c941b | 664,322 |
import collections
def secs_to_text(cs):
"""Convert time in seconds to a human readable string.
"""
v = collections.OrderedDict()
v['s'] = cs % 60
cs //= 60
v['m'] = cs % 60
cs //= 60
v['h'] = cs % 24
cs //= 24
v['d'] = cs
parts = []
for k in v:
if v[k] != 0:
... | f5d9cc66cbf6815fc765700309eb0f3124e58192 | 664,323 |
import torch
def testing_evaluation(model, test_loader, device):
"""
:param model:
:param test_loader:
:param device:
:return:
"""
print('\n#####################################')
print('#### The {} model is evaluated on the testing dataset loader ...... '.format(model.model_name))
... | 9f9dd412992edb2dc6d7e88c8e23d181dc03c84b | 664,324 |
def connections(activities):
"""Enumerates the connections within a list of activities.
Args:
activities: The activities to process. Parents/children outside these are ignored.
Returns:
A list of two-tuples. Each tuple is a (parent, child) relationship.
"""
acts = frozenset(activitie... | 2c68cc5628ad096e7bdfef426c75017bba407be9 | 664,325 |
import glob
import re
def GetTtyDevices(tty_pattern, vendor_ids):
"""Finds all devices connected to tty that match a pattern and device id.
If a serial device is connected to the computer via USB, this function
will check all tty devices that match tty_pattern, and return the ones
that have vendor identifica... | e19851b5a54952ad03f5619e70b930e77ab264b5 | 664,326 |
import os
import subprocess
def bokeh_installer(env_name, install_string):
"""Activate an environment and run its install string to either install or update bokeh using
conda or pip.
"""
if os.name == 'nt':
command_string = 'activate %s & %s' % (env_name, install_string)
else:
com... | 674e8fa0397b1aba0cfc68e3535989a477219a71 | 664,327 |
import csv
def load_sol (filename):
"""Load best_solns file"""
data = {}
data_reader = csv.reader(open(filename, 'rU'), delimiter='\t')
# Ignore header
header = next(data_reader)
# Process each line
for row in data_reader:
if len(row) == len(header):
sample = row[1]
sample_data = {}
for el_idx, el i... | b179600bcc6c2777fae1f1ab54252d2f301c85f9 | 664,328 |
import json
def list_networks(api, filters=None):
"""list network useing filter"""
filters_param = {}
if filters:
filters_param = {'filter': filters}
response = api.get('/networks/json', filters_param)
return json.loads(str(response.read(), 'utf-8')) | f6ca90dfdcb068c6847c8aafbff0d84dec5bf993 | 664,329 |
import re
import os
import shlex
import sys
def parse_xvg(fname, sel_columns='all'):
"""Parses XVG file legends and data"""
_ignored = set(('legend', 'view'))
_re_series = re.compile('s[0-9]+$')
_re_xyaxis = re.compile('[xy]axis$')
metadata = {}
num_data = []
metadata['labels'] ... | 9bf75fe4135219f817d4d2eb63f06a0ffd2c99db | 664,330 |
import torch
def cross_squared_distance_matrix(x, y):
"""Pairwise squared distance between two (batch) matrices' rows (2nd dim).
Computes the pairwise distances between rows of x and rows of y
Args:
x: [batch_size, n, d] float `Tensor`
y: [batch_size, m, d] float `Tensor`
... | cbe660db0458554619de62d25654991c9faf6b22 | 664,331 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.