content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import configparser
def load_configuration(config_file):
"""Gets the configuration file and returns the dictionary of configuration"""
filename = config_file
config = configparser.ConfigParser()
config.read(filename)
return config | 7e119b841ce9c720f4a8f239ccbd667d4c91f287 | 637,075 |
from typing import Type
from typing import Any
def typed_property(name: str, expected_type: Type[Any]) -> property:
"""Avoids definition of repetitive property class methods.
Simplifies type assertions on class attributes values.
Illustrates an important feature of inner functions or closures.
Args:... | 2f704ae0fe0e6fae60bbc05917ee73b790d77a68 | 637,076 |
def get_all_dirty_labels(s):
"""Get any label from an outcome, irrespective of being matched or not"""
return [] | f20846f4435bf68dfb09da3a150922b031df4edb | 637,077 |
def graph():
"""Create a new empty graph."""
return {} | e21fd99046cdab414c64a7f6a3111b5d87452e7a | 637,078 |
def _amplify(ui_mat, alpha=1.0):
"""Exponentially amplify values of similarity matrix"""
if alpha == 1.0:
return ui_mat
for i, w in enumerate(ui_mat.data):
ui_mat.data[i] = w ** alpha if w > 0 else -(-w) ** alpha
return ui_mat | c5b28d749749cda40fb54f2bc84e3afad7d2ae8c | 637,079 |
def _src_lines(start_line, end_line):
"""
Test lines to write to the source file
(Line 1, Line 2, ...).
"""
return "\n".join(
[f"Line {line_num}" for line_num in range(start_line, end_line + 1)]
) | e4b602774279af8599b98413513835a72731960c | 637,080 |
def _grad_nll(p, gp, y):
"""
Given parameters and data, compute the gradient of the negative log
likelihood of the data under the george Gaussian process.
Parameters
----------
p : array
GP hyperparameters
gp : george.GP
y : array
data to condition GP on
Returns
... | 600f22945036454621860d2289fcfdd9a29fdd1e | 637,081 |
def mutation_type(alleles):
"""
Is this mutation a transition (A <-> G and C <-> T) or a transversion (everything else).
"""
alleles = set([a.upper() for a in alleles])
assert len(alleles) == 2 and alleles.issubset({"A", "C", "G", "T", "N"})
return "ts" if alleles in [{"A", "G"}, {"C", "T"}] els... | 5cd4dd0d7364516a1368860f03355cd918b1fb0e | 637,082 |
import torch
def gaussian_noise(x, std=1, **kwargs):
"""Add Gaussian noise and clips the output."""
return torch.clamp(x + torch.randn_like(x) * std, **kwargs) | 6122fc2ee8dfc52adbd8e8f76e2c01ba4e425ab2 | 637,083 |
def day_of_week(y, m, d):
"""
There is a formula to compute the week day mathematically, first posted to
comp.lang.c discussion boards in 1992 by Tomohiko Sakamoto. Further details
at https://cs.uwaterloo.ca/~alopez-o/math-faq/node73.html. Works for dates
after 1752 when Gregorian calendar formally ... | 3973a12817d16e11be0adc206a18ede247517410 | 637,084 |
from typing import Union
def human_number(number: Union[int, float]) -> str:
"""human-readable number format.
It is a general-purpose number formatter, which separates every three
digits to make it human-readable.
Args:
number (int or float): Accepts only one element (i.e., scalar).
Ret... | 9ba5c22763cc67d057eb59720c0a67b68f720b07 | 637,086 |
def strip_value_deaths(cell):
"""
Split a cell like "1234 567" into a list and return the second value
:param cell: the cell form the dataset
:return: int
"""
try:
if any(map(str.isdigit, cell)): # Verify if the cell has number or not
result = cell.split()
return... | 1128cd25be886c0426ff1e6b328d5188d7102922 | 637,087 |
import subprocess
def invoke(command):
"""Invokes a command as a subprocess"""
try:
subprocess.check_call(command, shell=True)
return True
except subprocess.CalledProcessError:
return False | b72deb9e152a8b0180830ab14f17f83963cf5242 | 637,088 |
def negaterow(row, K):
"""
Negates a row element-wise.
Examples
========
>>> from sympy.matrices.densearith import negaterow
>>> from sympy import ZZ
>>> a = [ZZ(2), ZZ(3), ZZ(4)]
>>> b = [ZZ(0), ZZ(0), ZZ(0)]
>>> negaterow(a, ZZ)
[-2, -3, -4]
>>> negaterow(b, ZZ)
[0, 0... | cf5e943b50fa917f8d5e2b191d87a26c88941652 | 637,089 |
def contains(func, iterable):
"""
Return true if one element of iterable for which function returns true.
"""
if func is None:
func = bool
for x in iterable:
if func(x):
return True
return False | 17eed61acc4bbd74ae800fe33298e0548ef7f96b | 637,090 |
def isiterable(variable):
"""
Check whether the given variable is iterable.
Lists, tuples, NumPy arrays, but strings as well are iterable. Integers,
however, are not.
Parameters
----------
variable :
variable to check for being iterable
Returns
-------
answer : :class:... | d01204c0380470cdbe69da5a9c10de1ca0365f68 | 637,091 |
def _set_tmin(ft_struct):
"""Set the start time before the event in evoked data if possible."""
times = ft_struct['time']
time_check = all(times[i][0] == times[i - 1][0]
for i, x in enumerate(times))
if time_check:
tmin = times[0][0]
else:
tmin = None
return ... | a979445ad8bfd2c32d3d77fc74d8dca8be08c003 | 637,093 |
from typing import Callable
def star(f: Callable) -> Callable:
""" Converts a function of multiple arguments, to a function taking a tuple.
Useful for e.g. min(list_of_tuples, key=star(lambda a,b: ....)). """
return lambda args: f(*args) | 59a6f4bcca310e4468a038cc72eb2200367a9708 | 637,094 |
def output_container(f):
"""add a prompt-area next to an output"""
def wrapped(self, output):
rendered = f(self, output)
if not rendered:
# empty output
return []
lines = []
lines.append('<div class="hbox output_area">')
lines.extend(self._out_prom... | 35387863301451225956a95df57f839c31b3944c | 637,095 |
import json
def format_json_for_object_property(obj, prop_name):
""" Returns the property given by `prop_name` of the given
API object as a nicely-formatted JSON string (if it exists) """
prop = getattr(obj, prop_name, None)
if prop is None:
# NOTE: return an empty JSON object string to
... | f2c7ee15fcdac81b3e387968433a2030b20d171f | 637,096 |
import platform
def getPlatform():
"""Return a string describing the platform
"""
platformData = platform.platform()
if platformData.lower().startswith("darwin"):
try:
# try to replace Version-kernel#- with MacOSX-vers#-
# this fails on some versions of Python, so ignor... | 5b632811c884f1839b3614600008ae956fb78e94 | 637,097 |
def get_row_column(play, board):
"""
prompt for user input until its correct
catch any letters or incomplete values in user input
:param play - string, user command:
:param board - object, board:
:return row, column - int, locations on board in 2-D:
"""
# loop until there is valid user i... | b6905eb5ad89ef83f3841378d309f49b72e48b7e | 637,098 |
def metadata_function(metadata_batches):
"""Gets the metadata."""
logit_32_batch = metadata_batches[0]
logit_16_batch = metadata_batches[1]
metadata_list = []
for idx in range(logit_16_batch.shape[0]):
metadata_list.append((logit_32_batch[idx], logit_16_batch[idx]))
return metadata_list | fa97fafee0cb69e6e4ee47d455c430d2a4a50629 | 637,099 |
from typing import OrderedDict
import sys
import logging
def record_from_entry(key, entry, collection):
"""
Create a single BibJSON record from a BibTeX entry dictionary.
:param key: entry key (citekey)
:param entry: BibTeX entry dictionary
:param collection: collection name
:return BibJSON re... | 0e6eac4b1fc9cd52a08caee9d9f3985ff74e1d27 | 637,101 |
def viterbi_segment(text, P):
"""Find the best segmentation of the string of characters, given the
UnigramTextModel P."""
# best[i] = best probability for text[0:i]
# words[i] = best word ending at position i
n = len(text)
words = [''] + list(text)
best = [1.0] + [0.0] * n
## Fill in the... | 50f41cfc9f0080aa0245c1857eff77aefc70126d | 637,102 |
import platform
import os
def config_base_directory():
"""Returns the OpenCue config base directory.
This platform-dependent directory, stored within your user profile, is used by
OpenCue components as the default location for various configuration files. Typically
if you store your config files in t... | a7063a1d2bf6443ffe3b51c1ced4439a19be5d57 | 637,103 |
import math
def continued_fraction_expansion(target, terms):
"""
Return continued fraction expansion of a real number.
>>> continued_fraction_expansion(1.4142, 2)
[1, 2, 2]
The first component is the integer part, and rest is fractional
part, whose number of terms is specified by the second ... | 020ce08ecbdbced0e6ee907d2eaf774e5c5aabd1 | 637,104 |
import argparse
def pars(s) :
""" routine to parse command-line triples
"""
try :
x, y, z = s.split(',')
return x, y, z
except :
raise argparse.ArgumentTypeError("range must be specified as number,start,delta") | 2da33148cd588c18bf21c3dfcb821570f96db624 | 637,105 |
def compute_prob(eng: float, beta: float, num_spin: int) -> float:
"""Boltzmann probability distribution
Args:
eng (float): Energy of the sample.
beta (float): Inverse temperature
num_spin (int): Number of spins in the sample.
Returns:
float: Log-Boltzmann probability.
... | e6e043bd5ad5c4269c1c22b5a17e9f114bf37619 | 637,106 |
import opcode
def _opcode(name):
"""Return the opcode by name from the opcode module."""
return opcode.opmap[name] | bdd5491ad6626317e64c58d40afb249b380ceeb4 | 637,107 |
def augment_lab_config(lab_config):
"""augment the configuration by
- adding a "connected_to" attribute to each port which has a cable plugged in
Args:
lab_config (dict): [description]
Returns:
dict: lab_config
"""
for cable in lab_config["cables"]:
lab_config["devices"][cable["sour... | 10afe404f8e08e2d617add5dcb1602bd50c12259 | 637,108 |
import re
def get_prerelease_suffix(version):
""" Returns the prerelease suffix from the version string argument """
def mfunc(m):
return " %s %s %s" % (m.group('prefix'),
{'a': 'Alpha', 'b': 'Beta'}[m.group('c')],
m.group('suffix'))
result, c = re.subn(r'^... | b95494f44b8a2bfbde9dc7a6810a52f5fff5611c | 637,109 |
import os
def change_extension(filename: str, new_extension: str) -> str:
"""
Смена расширения у файла (без физического переименования!).
:param filename:
:param new_extension:
:return:
"""
return os.path.splitext(filename)[0] + new_extension | 7535cacd26dd03cd8b8f4d4b67cc22b88f5a168f | 637,110 |
def subcommand_kubectl(args, kctl):
"""Runs a Kubernetes command in the context of the configured Application.
"""
cmd = args.args
if cmd and cmd[0] == '--':
cmd = cmd[1:]
return kctl.run(cmd) | 9518acc64c3a9f1b7e7b2951ea02f083ef6f5c91 | 637,111 |
def format_link(link):
"""
Append site url
"""
return "https://old.reddit.com" + link if link[:3] == "/r/" else link | 53bec63d072239f63e81be7ff56a690416f798dd | 637,112 |
def purity(label_pred, label_true, Ia_flag=0):
"""Calculate purity.
input: label_pred, predicted labels
label_true, true labels
Ia_flag, Ia flag (optional, default is 0)
output: purity
"""
cc_Ia = sum([label_pred[i] == label_true[i] and label_true[i] == Ia_flag f... | 72487a0b1afa768deb23d50057a38b0a9e1c3309 | 637,113 |
import json
import time
def serialize_spool_file_contents(reason, expiration=None, creation=None):
"""Serialize the contents of the spool file (as JSON).
:param reason: a string representing the reason why the downtime exists.
:param expiration: The unix time when this downtime should be considered valid... | 07e91580321ed5de67dee44c841c5487d1a6a30d | 637,114 |
from pathlib import Path
import click
def validate_json_yaml_filename(ctx, param, value):
"""Validate the name of the file has the proper extension and add the extension to the file object"""
if value is None:
return value
if not hasattr(value, "name") or value.name == "<stdout>":
# stdin... | 2adf1053cd1c4326f8ba2de137ca4f3c81a1c4a6 | 637,115 |
def get_middle_point(xx, yy):
"""
Roughly get the middle point of line of x, y coordinates
:param xx: np.array , x array coordinates
:param yy: np.array , y array coordinates
:return: (x_center, y_center)
"""
half = int(len(xx) / 2)
return xx[half], yy[half] | 3bfc0684755e5a3b5976b61ff8da9d6cd819dd9b | 637,116 |
def GetRegionFromZone(zone):
"""Returns the GCP region that the input zone is in."""
return '-'.join(zone.split('-')[:-1]).lower() | c00acab2899d33efcc33672848a91e8845a09fba | 637,117 |
def take_keys(keys, data_dict):
"""Take keys from dict
Arguments:
keys {List[str]} -- Keys it include in output dict
data_dict {Dict}
Returns:
[Dict]
"""
return {k: v for k, v in data_dict.items() if k in keys} | 223f3bb59662abbe875c6d1cd06883f47a0d8f65 | 637,118 |
def targetName():
"""Creates a list of marker names.
Returns
-------
target_names : array
A list of marker names.
Examples
--------
>>> targetName() #doctest: +NORMALIZE_WHITESPACE
['C7', 'T10', 'CLAV', 'STRN', 'RBAK', 'LPSI', 'RPSI',
'RASI', 'LASI', 'SACR', 'LKNE', 'LKNE'... | ad252199da001bd72ee2a7b6328fc31676766a38 | 637,119 |
def locationGenerator(r,t,c,data='data', contextMgr=False):
"""
Given R, T, C, this funtion will generate a path to data in an imaris file
default data == 'data' the path will reference with array of data
if data == 'attrib' the bath will reference the channel location where attributes are stored
""... | 1c5b88c0e03d2f50e0891c7a77800752a631409d | 637,120 |
def drop_substring_from_str(item: str, substring: str) -> str:
"""Drops 'substring' from 'item'.
Args:
item (str): item to be modified.
substring (str): substring to be added to 'item'.
Returns:
str: modified str.
"""
if substring in item:
return item.replace(s... | 0f1bc24d21809afc2e5416efd396153efb75c76c | 637,121 |
import re
def format_species(name, mhchem=False, mathrm=False):
""" Format the name of a chemical species.
Usage: formatted_name = format_species(name, mhchem=False)
Takes a string which represents an atomic or molecular species
and returns a string with LaTeX-style sub- and superscripts... | 1c91e52beba0ecdc8dd60f0f0d435166d6753f5e | 637,123 |
def is_decorated(func):
"""Return True if |func| is decorated by @public or @require decorators."""
return hasattr(func, '__auth_public') or hasattr(func, '__auth_require') | bdb6a3a1dfa9a9da7d045fa57966318190454f7a | 637,124 |
def decode_bytes(s, encoding='utf-8', errors='replace'):
"""Decodes bytes to str, str to unicode."""
return s.decode(encoding, errors=errors) if isinstance(s, bytes) else s | 2ff943128e83585b9c3241e8bed4db80d9090c38 | 637,125 |
def metaslice(alen, nmeta, trim=0, thickness=False):
"""
Return *[imin,imax,istp]* so that `range(imin,imax+1,istp)` are the
boundary indices for *nmeta* (centered) metaslices.
Note: *imax* is the end boundary index of last metaslice,
therefore element *imax* is *not* included in last
... | 2a3a47958fd11bb92b8c049e57f087ed4039e553 | 637,126 |
def sin(x):
"""
sin(x)
"""
return 42 | 7d64164e8707c5161ddafacabcfa5c2cfe323b29 | 637,128 |
def get_bind_host(conf):
"""
使用选项 bind_host
"""
return getattr(conf, 'bind_host', None) | 980e821a134608ece4715395fac84f1cdd19a9bc | 637,129 |
def kgConv(df):
"""
Converts weight from kilograms to grams
"""
df['Weight'] = df['Weight'] * 1000
return df | 4ca0e602c8376386d2effe96cd16b8e406772048 | 637,130 |
def dataNormalize (data):
"""
args: data; output from sudoku_solve()
returns: Normalized output of input - Diplayed at console
"""
ans=""
sudoku_nums = [ eachPos[1] for eachPos in sorted( data[0].items() ) ]
for step in range(0,81,9):
print(sudoku_nums[step:step+9])
ans = ans... | af57fade49d4a133f59ec1925d59a948e03dcd16 | 637,131 |
import json
def import_json(path):
"""Decodes and returns the JSON object in the file at the specified path.
Args:
path (str): The path of the file to read.
"""
with open(path) as data_file:
return json.load(data_file) | b61b56851995a3e000d631187a3501c12066a081 | 637,132 |
import torch
def get_distorted_x(x, prob, corrupt=True):
"""
Distorts the node feature matrix (X) either through corruption or through blanking out
- Corruption: Add uniform random noise in [0,1] to the node feature matrix
- Blanking out: Replace entries in the node feature matrix with zer... | 6ba6d5ef38cf5bedd332c6176d2ccf7aa1042019 | 637,133 |
import os
def path_to_h5_file(data_folder):
"""
Input: string
data_folder: name of folder where h5 file is located
Output: string
full path of h5 file
"""
count = 0
for file in os.listdir(data_folder):
if file.endswith(".h5"):
# print(os.path.join(data_folde... | 2f8ceb9bbaf85b956a1b127aaccaecc8f60d180d | 637,134 |
def quadKey_to_Bing_URL(quadKey, api_key):
"""Create a URL linking to a Bing tile server"""
tile_url = ("http://t0.tiles.virtualearth.net/tiles/a{}.jpeg?"
"g=854&mkt=en-US&token={}".format(quadKey, api_key))
#print "\nThe tile URL is: {}".format(tile_url)
return tile_url | 1ca508cd73a0a9068f21fa4bdba85954200e3768 | 637,136 |
def string_end(code, index):
"""
code = "abc"
index = 1
"""
s = ''
offset = index
escape_map = {
'"': '"',
'n': '\n',
't': '\t',
'r': '\r',
'\\': '\\',
}
while offset < len(code):
c = code[offset]
if c == '"':
# 找到了字... | 4ac059ca078832c6626aa1e89ecd940347b671ea | 637,138 |
def compute_sum(tol = 1e-2):
"""Function computes the sum of 1/k**2.
tol represents a specific tolerance.
Summation is to stop when the sum would be smaller than the specified tolerance."""
k=1
sum_total = 0
sum_term = 1
while sum_term > tol:
sum_term = 1/(k**2)
sum_total += ... | 8dbe167784a7fb71d37be69ee7a080fe57c8c607 | 637,139 |
def _select_entries_param(list, param):
"""Takes a list of logfile_entry objects and returns a sub set of it.
The sub set includes a entries that have a source attribute that occurs in the param argument.
Positional arguments:
list -- a list of logfile_entry objects
param -- a list of strings, representing source... | e92c7a68543f790095e1ea65a0b72c4c68447a96 | 637,141 |
def split(number, nparts):
"""
split a number in n parts
:param number: the number to split
:type number: int
:param nparts: number of parts (n)
:type nparts: int
:return:
"""
return (
[number // nparts for i in range(nparts)]
if number % nparts == 0
else [
... | 3b21865d4cbf9880407c2318007782bcc76e0561 | 637,142 |
def rotate_matrix__90_clk_inplace(matrix):
"""In-place rotation. Changes the input matrix.
Args:
A square 2-dim matrix.
Returns:
Rotated matrix (in-place)
"""
n = len(matrix)
if n <= 1:
return matrix
for i in range(n//2):
for j in range(i, n - i - 1):
... | f57766453d8523594baa8c939dc2057702fa79c5 | 637,143 |
def choose_robots(exclude_bimanual=False):
"""
Prints out robot options, and returns the requested robot. Restricts options to single-armed robots if
@exclude_bimanual is set to True (False by default)
Args:
exclude_bimanual (bool): If set, excludes bimanual robots from the robot options
R... | c090639380ca301a51973e235ff6bbbbe848c1b6 | 637,144 |
def _formula2listf(formula):
"""Splits a polynomial to a difference of two formulas with positive
coefficients and extracts coefficients and function
arguments of both formulas."""
lfun=[]
lcoef=[]
rfun=[]
rcoef=[]
for addend in formula.as_ordered_terms():
coef,facts=addend.as_coeff_mul()
if(coef<0):
lco... | b6d356571217dd409230ac3f39faadf1328e581e | 637,145 |
def is_empty(name, data, check_value=True):
"""
:param name: 字段名
:param data: 数据对象
:param check_value:是否检查值
:return:
"""
if not check_value:
return not (name in data)
if name in data and (data[name] or data[name] == 0):
return False
else:
return True | e566961615127763ec7f0124e8c84a4d2f657515 | 637,146 |
def order_to_process(a, b):
"""
Takes two sorted lists of tuples and returns a
combined list sorted by lowest first element
Paramters:
a, b - a sorted list of tuples
"""
ret_l = []
while a and b:
ret_l.append(a.pop(0) if a <= b else b.pop(0))
ret_l.extend(a)
ret_l.exten... | 7d2af630240201a1608058c73325e6afdcf538c6 | 637,147 |
import collections
def _add_combine_info(output, combine_map, file_key):
"""Do not actually combine, but add details for later combining work.
Each sample will contain information on the out file and additional files
to merge, enabling other splits and recombines without losing information.
"""
f... | bc971e319574b68bfabbf45e9cf7aca4e5ab7781 | 637,148 |
def simd_loop_filter(loops, tuning):
""" Filter out the SIMD candidate loops based on the tuning information.
We select the legal simd loop with the highest score.
If there is no such loop, we will set "loops" to all "1"s.
AutoSA will not tile loops with the tiling factor as one for latency hiding or
... | bf9c261aa6a3af7fd4cb30205f3745c7ed29a551 | 637,149 |
from bs4 import BeautifulSoup
def scrape_target_elements(html, target, target_type, specific_tag=''):
"""Scrape target from the html document
Positional Arguments:
html (str): standard html document
target (str): name of tag, id or class
target_type (str): tag (html element such as <l... | 9494138b275a09b2cec20aa42eee8d06bdc89e40 | 637,150 |
def life_check(g, ch, dashed, life):
"""
this function check if the life should be minus
"""
ans = ''
for i in range(len(ch)): # for loop for letter number of random word times
if g == dashed[i]: # enter the letter which has guessed before
return life ... | 32269a3c68ae98b5ff7facd3f0be44d1765a296b | 637,152 |
import itertools
def _MakeBytes(bits, toks):
"""Creates a multi-byte string from ASCII strings and/or ASCII codes.
Args:
bits: Number of bits per character, must be in {8, 16, 32}.
toks: A list of tokens, each of which is a ASCII strings or an integer
representing a character's ASCII value (e.g., 0... | 858541b8ab9a872c4f92ff1cc720bc26219d823f | 637,153 |
def limit(string, print_length=58):
"""Limit the length of a string to print_length characters
Replaces the middle with ...
"""
if len(string) > print_length:
trim = int((print_length-3)/2)
return string[:trim] + '...' + string[-trim:]
else:
return string | 1c92d104a5732c0d7f4ebe35f048b6e492824f93 | 637,154 |
def get_haplotype_population(counts):
"""
# ========================================================================
GET HAPLOTYPE POPULATION
PURPOSE
-------
Returns the population of haplotypes.
INPUT
-----
[INT LIST] [counts]
A haplotype counts, from the counts of th... | 953a886f0f74d40261dd6369cf0197c5479cf1c5 | 637,155 |
def reduce_subjects(doc):
"""Iterates and sort all topic and subject related fields and
returns a set of unique subjects.
:param doc: Dictionary of subject values from the Solr document
query
:rtype: Set of subject terms
"""
subjects = []
if doc.has_key('subject'):
f... | 61c0797c858d91852d1c9f27b59dc4402612eada | 637,156 |
import random
def get_otp_code() -> str:
"""Get random 6-digit OTP code"""
return "".join([random.choice("0123456789") for i in range(6)]) | e652c6bafb9066b944ecd4b7e944b2eef564d549 | 637,158 |
def nifty_reg_transform(nifty_bin, ref=None, ref2=None, invAff1=None, invAff2=None, invNrr1=None, invNrr2=None,
invNrr3=None, disp1=None, disp2=None, def1=None, def2=None, comp1=None, comp2=None,
comp3=None):
"""
call niftyreg transform, see niftyreg doc, http://c... | 95201affb8c47a365d39467e3879aae120df169f | 637,159 |
def guides_query(self, store_id, userid=None, mobile=None, work_id=None, limit=None, offset=0, sub_mchid=None):
"""服务人员查询
:params store_id: 门店ID, 示例值:1234
:params userid: 企业微信的员工ID, 示例值:'robert'
:params mobile: 手机号码, 需进行加密处理, 示例值:'7mKQeypi9fKjAggRfvNFPf/bNxPvork4mMVgZkA=='
:params work_id: 工号, 示例值:'... | 9091b1cc04a762630a5ffac0ba4297413bdbd323 | 637,160 |
import os
def listdir(path):
"""
Lists content of a folder.
:param str path: Folder to get list from
:returns: Directory content list
:rtype: tuple
example::
dirs, files = xbmcvfs.listdir(path)
"""
dirs = []
files = []
path = path
for item_name in os.listdir(path... | 0093540a1d3835b0880cd9cb29ffdac9f8606391 | 637,161 |
def compressChunk(tiles):
""" Compress an array of tiles counting sequence of same numbers """
compressedChunk = []
countVal = 1
buffer = tiles[0]
size = len(tiles) - 1
## Compressing loop with RLE encoding
index = 0
for tile in tiles:
if(index == 0):
index += 1;
continue
if(index == size):
if(... | 7a89e373c6a2c31795343c632a9a0b0f9328bc29 | 637,162 |
def by_det(evtdata, det_id=0):
""" Apply Det filtering to the data.
Parameters
----------
evtdata: FITS data class
This should be an hdu.data structure from a NuSTAR FITS file.
det_id: int
Values of 0,1,2 or 3
Defaults to 0
"""
det_filter = (evtd... | 80520b0829b2e6832b38772991659af6873e678a | 637,163 |
import os
def fixture(filename):
"""
Get the handle / path to the test data folder.
"""
return os.path.join(os.path.dirname(__file__), 'fixtures', filename) | 76285afc84cad6cd646abc15e738c55ad42194b5 | 637,168 |
import os
def find_jars(directory):
"""
Find .jar files beneath a given directory.
:param directory: the folder to be searched
:return: a list of JAR files
"""
jars = []
for root, dirs, files in os.walk(directory):
for f in files:
if f.lower().endswith('.jar'):
... | 19f02a042da11cc5b6e719f6c4a2e38bb1cd55e4 | 637,169 |
def template_json():
"""Return the template json."""
return {
"boards": [
{
"name": "Board Name",
"lists": [
{
"name": "List Name",
"cards": [
{
... | 81c7972781d8d586632570131da20bacfa9da5c6 | 637,170 |
import os
import glob
def find_with_extension(in_dir, ext, depth=3, sort=True):
"""Naive depth-search into a directory for files with a given extension.
Parameters
----------
in_dir : str
Path to search.
ext : str
File extension to match.
depth : int
Depth of directori... | ff7ea24486ec42affeba4463ce1f892208e9e810 | 637,171 |
def find_set_points(minmax_terms, var_name):
"""Return a list of sorted set points.
Args:
minmax_terms (list): A list of minmax_term objects.
var_name (str): A character, which is the name of the variable.
Returns:
list: An empty list if there are variables but all coefficients are... | 4db29d8ddf30b5fa7cba970398b3df1a1e4fc6a1 | 637,172 |
def instanciate_dual_reg(color_map, reg_class, reg_list):
""" Instanciate a pair of registers formed by the registers in reg_list """
instanciated_list = [reg.instanciate(color_map) for reg in reg_list]
return reg_class.build_multi_reg(instanciated_list) | cf838cc12f39df41234049f541b978d3cabd97a3 | 637,173 |
def bleu(pixel):
"""
Donne la valeur de bleu du pixel ``pixel``.
Arguments :
pixel : un pixel, c'est à dire un triplet de trois nombres entiers entre 0 et 255. Par exemple : (0,0,0) (pixel noir) ou : (255,255,255) (pixel blanc)
"""
return pixel[2] | 247dfa28bddd85790b7afdeee4d85d6560e61adf | 637,174 |
import requests
def download_json(url, args={}):
"""
Downloads a JSON
:param url: The URL of the JSON
:type url: string
:param args: Optional keyword arguments for requests
:type args: dict
:return: The downloaded JSON
:rtype: dict
"""
r = requests.get(url, **args)
return r.json() | d73878e5a17f3d7665f5533dde739a23c5f25206 | 637,176 |
def load_all_vectors(embd, wikiWordsPath):
"""Loads all word vectors for all words in the list of words as a matrix
Arguments
embd : Dictonary of word-to-embedding for all words
wikiWordsPath : URL to the path where all embeddings are stored
Returns
all_words_index : Dictonary of w... | 29e3a7f1cf9a46917623ed909ecdaaac1f98cbb3 | 637,177 |
import uuid
def get_guid() -> str:
""" Returns a new guid """
return uuid.uuid4().hex | 5f7bc873a3e786bae10465ab4328d04d4c328df4 | 637,178 |
def record2dict(record):
"""Convert a Sumatra record to nested dicts"""
data = {
"label": record.label, # 0.1: 'group'
"timestamp": record.timestamp.strftime("%Y-%m-%d %H:%M:%S"),
"reason": record.reason,
"duration": record.duration,
"executable": {
"path": r... | 91bc2efd9f8f556a19cd7861d045f3e361645938 | 637,179 |
def gen_team(name):
"""Generate a dict to represent a soccer team
"""
return {'name': name, 'avg_height': 0, 'players': []} | e4e064158e5791e2fde66dcd22ac2206f7ed421f | 637,180 |
import json
def _convert_result(result): # pragma: no cover
"""Translate SOAP result entries into dictionaries."""
translation = {
'NOMBRE': 'name',
'COMPROBANTE': 'proof',
'ES_VALIDO': 'is_valid',
'MENSAJE_VALIDACION': 'validation_message',
'RNC': 'rnc',
'NCF'... | a111e78fa6123d1a7578f3caa469d8b51a9946e1 | 637,181 |
import pickle
def learn_emb(MethObj, graphs, params, res_pre, m_summ):
"""Function to learn embedding
Attributes:
MethObj (obj): Object of the algorithm class
graphs (Object): Networkx Graph Object
params (dict): Dictionary of parameters necessa... | 3029e6665ae877c225881e449eeee8cd6a2b3454 | 637,182 |
import numpy
def bbox_idx(x, thresh=None):
"""
Returns indices of bounding box of receptive filed. This is useful for visualize receptive field.
Parameters
----------
x
output image of the target model with inpulse input image
thresh
Returns
-------
list of indices of bou... | 7a78f0e25e6b54f7d98d31fbd01ada952780d1e5 | 637,183 |
def indent_code(code):
"""Applies rudimentary indentation to code"""
return code | 8c86e98dab3277af90893baadc7f1f44ce6f3850 | 637,184 |
import pwd
import os
def is_superuser() -> bool:
"""
Is current user the superuser?
"""
pwuid = pwd.getpwuid(os.getuid())
return pwuid.pw_uid == 0 | 2ad1fd7788492374d142f4f40b68a1fe50c57205 | 637,185 |
import time
def timing(func):
"""Outputs the time a function takes to execute.
"""
def func_wrapper(*args, **kwargs):
t1 = time.time()
func(*args, **kwargs)
t2 = time.time()
print("- Processed in %.1f s.\n" % (t2-t1))
return func_wrapper | 3e1573ef15a34818f11744a88b1c098574cce8d3 | 637,186 |
def addReading(
sensore, readingid, origin, deviceName, resourceName, profileName, valueType, value
):
"""
sensore is a dict ,origin is int number, else all string.
"""
reading = {
"id": readingid,
"origin": origin,
"deviceName": deviceName,
"resourceName": resourceNa... | 321f4bedba16cccb26a80689a85995f7aa82d4a2 | 637,187 |
from typing import Callable
from typing import Tuple
from typing import Mapping
import inspect
def get_function_parameters(
f: Callable,
) -> Tuple[Mapping[str, inspect.Parameter], type]:
"""
Returns function's signature as parameters and the output type.
:param f: the function
:return: the param... | e087c220a5b788b8081d224e1c8f2d7771a32df6 | 637,188 |
import time
def timefunc(func):
"""
decorator to measure the execution time of the decorated function.
"""
def profiled_func(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(func.__name__, 'took', end - start, 'time')
... | afe66ad28afa7a4eb5640f4da9e707c38776a48f | 637,189 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.